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
ffef1561b7a36df59a33aa850718dcfbf088e50c
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/topology/metric_space/cau_seq_filter.lean
520cd1ee8ad8e9518a1d83d5a79abd1edc1f041e
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
16,303
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Sébastien Gouëzel Characterize completeness of metric spaces in terms of Cauchy sequences. In particular, reconcile the filter notion of Cauchy-ness with the cau_seq notion on normed spaces. -/ import topology.uniform_space.basic analysis.normed_space.basic data.real.cau_seq analysis.specific_limits import tactic.linarith universes u v open set filter classical emetric variable {β : Type v} /- We show that a metric space in which all Cauchy sequences converge is complete, i.e., all Cauchy filters converge. For this, we approximate any Cauchy filter by a Cauchy sequence, taking advantage of the fact that there is a sequence tending to `0` in ℝ. The proof also gives a more precise result, that to get completeness it is enough to have the convergence of all sequence that are Cauchy in a fixed quantitative sense, for instance satisfying `dist (u n) (u m) < 2^{- min m n}`. The classical argument to obtain this criterion is to start from a Cauchy sequence, extract a subsequence that satisfies this property, deduce the convergence of the subsequence, and then the convergence of the original sequence. All this argument is completely bypassed by the following proof, which avoids any use of subsequences and is written partly in terms of filters. -/ namespace sequentially_complete section /- We fix a cauchy filter `f`, and a bounding sequence `B` made of positive numbers. We will prove that, if all sequences satisfying `dist (u n) (u m) < B (min n m)` converge, then the cauchy filter `f` is converging. The idea is to construct from `f` a Cauchy sequence that satisfies this property, therefore converges, and then to deduce the convergence of `f` from this. We give the argument in the more general setting of emetric spaces, and specialize it to metric spaces at the end. -/ variables [emetric_space β] {f : filter β} (hf : cauchy f) (B : ℕ → ennreal) (hB : ∀n, 0 < B n) /--A positive sequence that tends to `0` in `ennreal`-/ noncomputable def F (n : ℕ) : ennreal := nnreal.of_real (1 / ((n : ℝ) + 1)) lemma F_pos (n : ℕ) : 0 < F n := begin simp only [F, -one_div_eq_inv, ennreal.zero_lt_coe_iff, add_comm, ennreal.zero_lt_coe_iff, add_comm, nnreal.of_real_pos], apply one_div_pos_of_pos, have : (↑n : ℝ) ≥ 0 := nat.cast_nonneg _, by linarith end lemma F_lim : tendsto (λn, F n) at_top (nhds 0) := begin unfold F, rw [← ennreal.coe_zero, ennreal.tendsto_coe, ← nnreal.of_real_zero], exact nnreal.tendsto_of_real tendsto_one_div_add_at_top_nhds_0_nat end /--Auxiliary sequence, which is bounded by `B`, positive, and tends to `0`.-/ noncomputable def FB (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (n : ℕ) := (F n) ⊓ (B n) lemma FB_pos (n : ℕ) : 0 < (FB B hB n) := by unfold FB; simp [F_pos n, hB n] lemma FB_lim : tendsto (λn, FB B hB n) at_top (nhds 0) := begin have : ∀n, FB B hB n ≤ F n := λn, lattice.inf_le_left, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds F_lim (by simp) (by simp [this]) end /-- Define a decreasing sequence of sets in the filter `f`, of diameter bounded by `FB n`. -/ def set_seq_of_cau_filter : ℕ → set β | 0 := some ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB 0)) | (n+1) := (set_seq_of_cau_filter n) ∩ some ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB (n + 1))) /-- These sets are in the filter. -/ lemma set_seq_of_cau_filter_mem_sets : ∀ n, set_seq_of_cau_filter hf B hB n ∈ f.sets | 0 := some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB 0))) | (n+1) := inter_mem_sets (set_seq_of_cau_filter_mem_sets n) (some (some_spec ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB (n + 1))))) /-- These sets are nonempty. -/ lemma set_seq_of_cau_filter_inhabited (n : ℕ) : ∃ x, x ∈ set_seq_of_cau_filter hf B hB n := inhabited_of_mem_sets (emetric.cauchy_iff.1 hf).1 (set_seq_of_cau_filter_mem_sets hf B hB n) /-- By construction, their diameter is controlled by `FB n`. -/ lemma set_seq_of_cau_filter_spec : ∀ n, ∀ {x y}, x ∈ set_seq_of_cau_filter hf B hB n → y ∈ set_seq_of_cau_filter hf B hB n → edist x y < FB B hB n | 0 := some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB 0))) | (n+1) := λ x y hx hy, some_spec (some_spec ((emetric.cauchy_iff.1 hf).2 _ (FB_pos B hB (n+1)))) x y (mem_of_mem_inter_right hx) (mem_of_mem_inter_right hy) -- this must exist somewhere, no? private lemma mono_of_mono_succ_aux {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) (m : ℕ) : ∀ n, f (m + n) ≤ f m | 0 := le_refl _ | (k+1) := le_trans (h _) (mono_of_mono_succ_aux _) lemma mono_of_mono_succ {α} [partial_order α] (f : ℕ → α) (h : ∀ n, f (n+1) ≤ f n) {m n : ℕ} (hmn : m ≤ n) : f n ≤ f m := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hmn in by simpa [hk] using mono_of_mono_succ_aux f h m k lemma set_seq_of_cau_filter_monotone' (n : ℕ) : set_seq_of_cau_filter hf B hB (n+1) ⊆ set_seq_of_cau_filter hf B hB n := inter_subset_left _ _ /-- These sets are nested. -/ lemma set_seq_of_cau_filter_monotone {n k : ℕ} (hle : n ≤ k) : set_seq_of_cau_filter hf B hB k ⊆ set_seq_of_cau_filter hf B hB n := mono_of_mono_succ (set_seq_of_cau_filter hf B hB) (set_seq_of_cau_filter_monotone' hf B hB) hle /-- Define the approximating Cauchy sequence for the Cauchy filter `f`, obtained by taking a point in each set. -/ noncomputable def seq_of_cau_filter (n : ℕ) : β := some (set_seq_of_cau_filter_inhabited hf B hB n) /-- The approximating sequence indeed belong to our good sets. -/ lemma seq_of_cau_filter_mem_set_seq (n : ℕ) : seq_of_cau_filter hf B hB n ∈ set_seq_of_cau_filter hf B hB n := some_spec (set_seq_of_cau_filter_inhabited hf B hB n) /-- The distance between points in the sequence is bounded by `FB N`. -/ lemma seq_of_cau_filter_bound {N n k : ℕ} (hn : N ≤ n) (hk : N ≤ k) : edist (seq_of_cau_filter hf B hB n) (seq_of_cau_filter hf B hB k) < FB B hB N := set_seq_of_cau_filter_spec hf B hB N (set_seq_of_cau_filter_monotone hf B hB hn (seq_of_cau_filter_mem_set_seq hf B hB n)) (set_seq_of_cau_filter_monotone hf B hB hk (seq_of_cau_filter_mem_set_seq hf B hB k)) /-- The approximating sequence is indeed Cauchy as `FB n` tends to `0` with `n`. -/ lemma seq_of_cau_filter_is_cauchy : cauchy_seq (seq_of_cau_filter hf B hB) := emetric.cauchy_seq_iff_le_tendsto_0.2 ⟨FB B hB, λ n m N hn hm, le_of_lt (seq_of_cau_filter_bound hf B hB hn hm), FB_lim B hB⟩ /-- If the approximating Cauchy sequence is converging, to a limit `y`, then the original Cauchy filter `f` is also converging, to the same limit. Given `t1` in the filter `f` and `t2` a neighborhood of `y`, it suffices to show that `t1 ∩ t2` is nonempty. Pick `ε` so that the ε-eball around `y` is contained in `t2`. Pick `n` with `FB n < ε/2`, and `n2` such that `dist(seq n2, y) < ε/2`. Let `N = max(n, n2)`. We defined `seq` by looking at a decreasing sequence of sets of `f` with shrinking radius. The Nth one has radius `< FB N < ε/2`. This set is in `f`, so we can find an element `x` that's also in `t1`. `dist(x, seq N) < ε/2` since `seq N` is in this set, and `dist (seq N, y) < ε/2`, so `x` is in the ε-ball around `y`, and thus in `t2`. -/ lemma le_nhds_cau_filter_lim {y : β} (H : tendsto (seq_of_cau_filter hf B hB) at_top (nhds y)) : f ≤ nhds y := begin refine (le_nhds_iff_adhp_of_cauchy hf).2 _, refine forall_sets_neq_empty_iff_neq_bot.1 (λs hs, _), rcases filter.mem_inf_sets.2 hs with ⟨t1, ht1, t2, ht2, ht1t2⟩, rcases emetric.mem_nhds_iff.1 ht2 with ⟨ε, hε, ht2'⟩, cases emetric.cauchy_iff.1 hf with hfb _, have : ε / 2 > 0 := ennreal.half_pos hε, rcases inhabited_of_mem_sets (by simp) ((tendsto_orderable.1 (FB_lim B hB)).2 _ this) with ⟨n, hnε⟩, simp only [set.mem_set_of_eq] at hnε, -- hnε : ε / 2 > FB B hB n cases (emetric.tendsto_at_top _).1 H _ this with n2 hn2, let N := max n n2, have ht1sn : t1 ∩ set_seq_of_cau_filter hf B hB N ∈ f.sets, from inter_mem_sets ht1 (set_seq_of_cau_filter_mem_sets hf B hB _), have hts1n_ne : t1 ∩ set_seq_of_cau_filter hf B hB N ≠ ∅, from forall_sets_neq_empty_iff_neq_bot.2 hfb _ ht1sn, cases exists_mem_of_ne_empty hts1n_ne with x hx, -- x : β, hx : x ∈ t1 ∩ set_seq_of_cau_filter hf B hB N -- we still have to show that x ∈ t2, i.e., edist x y < ε have I1 : seq_of_cau_filter hf B hB N ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) (seq_of_cau_filter_mem_set_seq hf B hB N), have I2 : x ∈ set_seq_of_cau_filter hf B hB n := (set_seq_of_cau_filter_monotone hf B hB (le_max_left n n2)) hx.2, have hdist1 : edist x (seq_of_cau_filter hf B hB N) < FB B hB n := set_seq_of_cau_filter_spec hf B hB _ I2 I1, have hdist2 : edist (seq_of_cau_filter hf B hB N) y < ε / 2 := hn2 N (le_max_right _ _), have hdist : edist x y < ε := calc edist x y ≤ edist x (seq_of_cau_filter hf B hB N) + edist (seq_of_cau_filter hf B hB N) y : edist_triangle _ _ _ ... < FB B hB n + ε/2 : ennreal.add_lt_add hdist1 hdist2 ... ≤ ε/2 + ε/2 : add_le_add_right' (le_of_lt hnε) ... = ε : ennreal.add_halves _, have hxt2 : x ∈ t2, from ht2' hdist, exact ne_empty_iff_exists_mem.2 ⟨x, ht1t2 (mem_inter hx.left hxt2)⟩ end end end sequentially_complete /-- An emetric space in which every Cauchy sequence converges is complete. -/ theorem complete_of_cauchy_seq_tendsto {α : Type u} [emetric_space α] (H : ∀u : ℕ → α, cauchy_seq u → ∃x, tendsto u at_top (nhds x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f` intros f hf, -- Introduce a sequence `u` approximating the filter `f`. We don't need the bound `B`, -- so take for instance `B n = 1` for all `n`. let u := sequentially_complete.seq_of_cau_filter hf (λn, 1) (λn, ennreal.zero_lt_one), -- It is Cauchy. have : cauchy_seq u := sequentially_complete.seq_of_cau_filter_is_cauchy hf (λn, 1) (λn, ennreal.zero_lt_one), -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf (λn, 1) (λn, ennreal.zero_lt_one) hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem emetric.complete_of_convergent_controlled_sequences {α : Type u} [emetric_space α] (B : ℕ → ennreal) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (nhds x)) : complete_space α := ⟨begin -- Consider a Cauchy filter `f`. intros f hf, -- Introduce a sequence `u` approximating the filter `f`. let u := sequentially_complete.seq_of_cau_filter hf B hB, -- It satisfies the required bound. have : ∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N := λN n m hn hm, calc edist (u n) (u m) < sequentially_complete.FB B hB N : sequentially_complete.seq_of_cau_filter_bound hf B hB hn hm ... ≤ B N : lattice.inf_le_right, -- Therefore, it converges by assumption. Let `x` be its limit. rcases H u this with ⟨x, hx⟩, -- The original filter also converges to `x`. exact ⟨x, sequentially_complete.le_nhds_cau_filter_lim hf B hB hx⟩ end⟩ /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences {α : Type u} [metric_space α] (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (nhds x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, have Z := Hu N n m hn hm, rw [edist_dist, ennreal.of_real_lt_of_real_iff] at Z, exact Z, exact hB N } end section /- Now, we will apply these results to `cau_seq`, i.e., "Cauchy sequences" defined by a multiplicative absolute value on normed fields. -/ lemma tendsto_limit [normed_ring β] [hn : is_absolute_value (norm : β → ℝ)] (f : cau_seq β norm) [cau_seq.is_complete β norm] : tendsto f at_top (nhds f.lim) := _root_.tendsto_nhds.mpr begin intros s os lfs, suffices : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → f b ∈ s, by simpa using this, rcases metric.is_open_iff.1 os _ lfs with ⟨ε, ⟨hε, hεs⟩⟩, cases setoid.symm (cau_seq.equiv_lim f) _ hε with N hN, existsi N, intros b hb, apply hεs, dsimp [metric.ball], rw [dist_comm, dist_eq_norm], solve_by_elim end variables [normed_field β] /- This section shows that if we have a uniform space generated by an absolute value, topological completeness and Cauchy sequence completeness coincide. The problem is that there isn't a good notion of "uniform space generated by an absolute value", so right now this is specific to norm. Furthermore, norm only instantiates is_absolute_value on normed_field. This needs to be fixed, since it prevents showing that ℤ_[hp] is complete -/ instance normed_field.is_absolute_value : is_absolute_value (norm : β → ℝ) := { abv_nonneg := norm_nonneg, abv_eq_zero := norm_eq_zero, abv_add := norm_triangle, abv_mul := normed_field.norm_mul } open metric lemma cauchy_of_filter_cauchy (f : ℕ → β) (hf : cauchy_seq f) : is_cau_seq norm f := begin cases cauchy_iff.1 hf with hf1 hf2, intros ε hε, rcases hf2 {x | dist x.1 x.2 < ε} (dist_mem_uniformity hε) with ⟨t, ⟨ht, htsub⟩⟩, simp at ht, cases ht with N hN, existsi N, intros j hj, rw ←dist_eq_norm, apply @htsub (f j, f N), apply set.mk_mem_prod; solve_by_elim [le_refl] end lemma filter_cauchy_of_cauchy (f : cau_seq β norm) : cauchy_seq f := begin apply cauchy_iff.2, split, { exact map_ne_bot at_top_ne_bot }, { intros s hs, rcases mem_uniformity_dist.1 hs with ⟨ε, ⟨hε, hεs⟩⟩, cases cau_seq.cauchy₂ f hε with N hN, existsi {n | n ≥ N}.image f, simp, split, { existsi N, intros b hb, existsi b, simp [hb] }, { rintros ⟨a, b⟩ ⟨⟨a', ⟨ha'1, ha'2⟩⟩, ⟨b', ⟨hb'1, hb'2⟩⟩⟩, dsimp at ha'1 ha'2 hb'1 hb'2, rw [←ha'2, ←hb'2], apply hεs, rw dist_eq_norm, apply hN; assumption }}, { apply_instance } end /-- In a normed field, `cau_seq` coincides with the usual notion of Cauchy sequences. -/ lemma cau_seq_iff_cauchy_seq {α : Type u} [normed_field α] {u : ℕ → α} : is_cau_seq norm u ↔ cauchy_seq u := ⟨λh, filter_cauchy_of_cauchy ⟨u, h⟩, λh, cauchy_of_filter_cauchy u h⟩ /-- A complete normed field is complete as a metric space, as Cauchy sequences converge by assumption and this suffices to characterize completeness. -/ instance complete_space_of_cau_seq_complete [cau_seq.is_complete β norm] : complete_space β := begin apply complete_of_cauchy_seq_tendsto, assume u hu, have C : is_cau_seq norm u := cau_seq_iff_cauchy_seq.2 hu, existsi cau_seq.lim ⟨u, C⟩, rw metric.tendsto_at_top, assume ε εpos, cases (cau_seq.equiv_lim ⟨u, C⟩) _ εpos with N hN, existsi N, simpa [dist_eq_norm] using hN end end
3e35be8513da1fa978fb9255a60e0d36d73aca07
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/termination_by2.lean
cc801d0452c3c301e2cee09ecb17cacbc793ccf5
[ "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
994
lean
mutual def f (n : Nat) := if n == 0 then 0 else f (n / 2) + 1 termination_by _ => n end def g' (n : Nat) := match n with | 0 => 1 | n+1 => g' n * 3 termination_by g' n => n _ n => n mutual def isEven : Nat → Bool | 0 => true | n+1 => isOdd n def isOdd : Nat → Bool | 0 => false | n+1 => isEven n end termination_by isEven x => x -- Error mutual def isEven : Nat → Bool | 0 => true | n+1 => isOdd n def isOdd : Nat → Bool | 0 => false | n+1 => isEven n end termination_by isEven x => x isOd x => x -- Error mutual def isEven : Nat → Bool | 0 => true | n+1 => isOdd n def isOdd : Nat → Bool | 0 => false | n+1 => isEven n end termination_by isEven x => x isEven y => y -- Error mutual def isEven : Nat → Bool | 0 => true | n+1 => isOdd n def isOdd : Nat → Bool | 0 => false | n+1 => isEven n end termination_by isEven x => x _ x => x _ x => x + 1 -- Error
08f1e1af159348e952e60195ab7b9c8a284352e5
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/group_constructions.hlean
d7c9a36e118171ab39aef515e8c6a99d5d3afb74
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,285
hlean
/- 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, Egbert Rijke Constructions with groups -/ import .free_commutative_group open eq algebra is_trunc sigma sigma.ops prod trunc function equiv namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} /- Tensor group (WIP) -/ /- namespace tensor_group variables {A B} local abbreviation ι := @free_ab_group_inclusion inductive tensor_rel_type : free_ab_group (Set_of_Group A ×t Set_of_Group B) → Type := | mul_left : Π(a₁ a₂ : A) (b : B), tensor_rel_type (ι (a₁, b) * ι (a₂, b) * (ι (a₁ * a₂, b))⁻¹) | mul_right : Π(a : A) (b₁ b₂ : B), tensor_rel_type (ι (a, b₁) * ι (a, b₂) * (ι (a, b₁ * b₂))⁻¹) open tensor_rel_type definition tensor_rel' (x : free_ab_group (Set_of_Group A ×t Set_of_Group B)) : Prop := ∥ tensor_rel_type x ∥ definition tensor_group_rel (A B : AbGroup) : normal_subgroup_rel (free_ab_group (Set_of_Group A ×t Set_of_Group B)) := sorry /- relation generated by tensor_rel'-/ definition tensor_group [constructor] : AbGroup := quotient_ab_group (tensor_group_rel A B) end tensor_group-/ end group
bdeccfb73dd4f4682291b8a794123770bf0f620a
f20db13587f4dd28a4b1fbd31953afd491691fa0
/leanpkg/leanpkg/lean_version.lean
3375e36f37b065f60dfff363f801c787b579457a
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
542
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ namespace leanpkg def lean_version_string_core := let (major, minor, patch) := lean.version in sformat!("{major}.{minor}.{patch}") def lean_version_string := if lean.is_release then lean_version_string_core else "master" def ui_lean_version_string := if lean.is_release then lean_version_string_core else "master (" ++ lean_version_string_core ++ ")" end leanpkg
b051431800db3ce89947b6e8112c5b08cb8000b1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group_power/identities.lean
a5f1ea7d3902b6bf3f161368db793f7839d14ea5
[ "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
3,367
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen, Kevin Lacker -/ import tactic.ring /-! # Identities > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/531 > Any changes to this file require a corresponding PR to mathlib4. This file contains some "named" commutative ring identities. -/ variables {R : Type*} [comm_ring R] {a b x₁ x₂ x₃ x₄ x₅ x₆ x₇ x₈ y₁ y₂ y₃ y₄ y₅ y₆ y₇ y₈ n : R} /-- Brahmagupta-Fibonacci identity or Diophantus identity, see <https://en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity>. This sign choice here corresponds to the signs obtained by multiplying two complex numbers. -/ theorem sq_add_sq_mul_sq_add_sq : (x₁^2 + x₂^2) * (y₁^2 + y₂^2) = (x₁*y₁ - x₂*y₂)^2 + (x₁*y₂ + x₂*y₁)^2 := by ring /-- Brahmagupta's identity, see <https://en.wikipedia.org/wiki/Brahmagupta%27s_identity> -/ theorem sq_add_mul_sq_mul_sq_add_mul_sq : (x₁^2 + n*x₂^2) * (y₁^2 + n*y₂^2) = (x₁*y₁ - n*x₂*y₂)^2 + n*(x₁*y₂ + x₂*y₁)^2 := by ring /-- Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>. -/ theorem pow_four_add_four_mul_pow_four : a^4 + 4*b^4 = ((a - b)^2 + b^2) * ((a + b)^2 + b^2) := by ring /-- Sophie Germain's identity, see <https://www.cut-the-knot.org/blue/SophieGermainIdentity.shtml>. -/ theorem pow_four_add_four_mul_pow_four' : a^4 + 4*b^4 = (a^2 - 2*a*b + 2*b^2) * (a^2 + 2*a*b + 2*b^2) := by ring /-- Euler's four-square identity, see <https://en.wikipedia.org/wiki/Euler%27s_four-square_identity>. This sign choice here corresponds to the signs obtained by multiplying two quaternions. -/ theorem sum_four_sq_mul_sum_four_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2) * (y₁^2 + y₂^2 + y₃^2 + y₄^2) = (x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄)^2 + (x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃)^2 + (x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂)^2 + (x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁)^2 := by ring /-- Degen's eight squares identity, see <https://en.wikipedia.org/wiki/Degen%27s_eight-square_identity>. This sign choice here corresponds to the signs obtained by multiplying two octonions. -/ theorem sum_eight_sq_mul_sum_eight_sq : (x₁^2 + x₂^2 + x₃^2 + x₄^2 + x₅^2 + x₆^2 + x₇^2 + x₈^2) * (y₁^2 + y₂^2 + y₃^2 + y₄^2 + y₅^2 + y₆^2 + y₇^2 + y₈^2) = (x₁*y₁ - x₂*y₂ - x₃*y₃ - x₄*y₄ - x₅*y₅ - x₆*y₆ - x₇*y₇ - x₈*y₈)^2 + (x₁*y₂ + x₂*y₁ + x₃*y₄ - x₄*y₃ + x₅*y₆ - x₆*y₅ - x₇*y₈ + x₈*y₇)^2 + (x₁*y₃ - x₂*y₄ + x₃*y₁ + x₄*y₂ + x₅*y₇ + x₆*y₈ - x₇*y₅ - x₈*y₆)^2 + (x₁*y₄ + x₂*y₃ - x₃*y₂ + x₄*y₁ + x₅*y₈ - x₆*y₇ + x₇*y₆ - x₈*y₅)^2 + (x₁*y₅ - x₂*y₆ - x₃*y₇ - x₄*y₈ + x₅*y₁ + x₆*y₂ + x₇*y₃ + x₈*y₄)^2 + (x₁*y₆ + x₂*y₅ - x₃*y₈ + x₄*y₇ - x₅*y₂ + x₆*y₁ - x₇*y₄ + x₈*y₃)^2 + (x₁*y₇ + x₂*y₈ + x₃*y₅ - x₄*y₆ - x₅*y₃ + x₆*y₄ + x₇*y₁ - x₈*y₂)^2 + (x₁*y₈ - x₂*y₇ + x₃*y₆ + x₄*y₅ - x₅*y₄ - x₆*y₃ + x₇*y₂ + x₈*y₁)^2 := by ring
6da058a80512c2dad8073253719e6a46a92d6ba3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/basic.lean
5ebcea554dcabbfcaec37110d741bcef4ae687cc
[ "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
122,452
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, Kevin Buzzard, Yury Kudryashov -/ import algebra.big_operators.pi import algebra.module.prod import algebra.module.submodule_lattice import data.dfinsupp import data.finsupp.basic import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first, second and third isomorphism laws for modules are proved as `linear_map.quot_ker_equiv_range`, `linear_map.quotient_inf_equiv_sup_quotient` and `submodule.quotient_quotient_equiv_quotient`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function open_locale big_operators pointwise universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type u} {R : Type v} {M : Type w} {M₂ : Type x} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variables (α : Type*) [fintype α] variables (R M) [add_comm_monoid M] [semiring R] [module R M] /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } @[simp] lemma linear_equiv_fun_on_fintype_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α) (single x m) = pi.single x m := begin ext a, change (equiv_fun_on_fintype (single x m)) a = _, convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α).symm (pi.single x m) = single x m := begin ext a, change (equiv_fun_on_fintype.symm (pi.single x m)) a = _, convert congr_fun (equiv_fun_on_fintype_symm_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_coe (f : α →₀ M) : (linear_equiv_fun_on_fintype R M α).symm f = f := by { ext, simp [linear_equiv_fun_on_fintype], } end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₗ[R] M₂) (p : submodule R M) : p →ₗ[R] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl @[simp] lemma default_def : default (M →ₗ[R] M₂) = 0 := rfl instance unique_of_left [subsingleton M] : unique (M →ₗ[R] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₗ[R] M₂) := coe_injective.unique /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f + g, map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₗ[R] M₂) := { zero := 0, add := (+), add_assoc := by intros; ext; simp [add_comm, add_left_comm], zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, nsmul_zero' := λ f, by { ext x, simp }, nsmul_succ' := λ n f, by { ext x, simp [nat.succ_eq_one_add, add_nsmul] } } /-- Evaluation of an `R`-linear map at a fixed `a`, as an `add_monoid_hom`. -/ def eval_add_monoid_hom (a : M) : (M →ₗ[R] M₂) →+ M₂ := { to_fun := λ f, f a, map_add' := λ f g, linear_map.add_apply f g a, map_zero' := rfl } lemma add_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (h + g).comp f = h.comp f + g.comp f := rfl lemma comp_add (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (f + g) = h.comp f + h.comp g := by { ext, simp } /-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/ def to_add_monoid_hom' : (M →ₗ[R] M₂) →+ (M →+ M₂) := { to_fun := to_add_monoid_hom, map_zero' := by ext; refl, map_add' := by intros; ext; refl } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _ section smul_right variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₂ →ₗ[R] S) (x : M) : M₂ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₂ →ₗ[R] S) (x : M) : (smul_right f x : M₂ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₂ →ₗ[R] S) (x : M) (c : M₂) : smul_right f x c = f c • x := rfl end smul_right instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : M →ₗ[R] M) = id := rfl lemma mul_eq_comp (f g : M →ₗ[R] M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_apply (f g : M →ₗ[R] M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : M →ₗ[R] M) = _root_.id := rfl lemma coe_mul (f g : M →ₗ[R] M) : ⇑(f * g) = f ∘ g := rfl instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₗ[R] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R M M₂ _ _ _ _ _, rfl, λ x y, rfl⟩ _ _ instance : monoid (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩ }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₗ[R] M₂} {g : module.End R M} {g₂ : module.End R M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M} {g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g) {k : ℕ} (hG : G^k = 0) : g^k = 0 := begin ext m, have hg : N.subtype.comp (g^k) m = 0, { rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], }, simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg, rw [hg, linear_map.zero_apply], end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end lemma surjective_of_iterate_surjective {n : ℕ} (hn : n ≠ 0) (h : surjective ⇑(f' ^ n)) : surjective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), nat.succ_eq_add_one, add_comm, pow_add] at h, exact surjective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f g : M →ₗ[R] M₂) /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl @[simp] lemma comp_neg (g : M₂ →ₗ[R] M₃) : g.comp (- f) = - g.comp f := by { ext, simp } /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₗ[R] M₂) := ⟨λ f g, { to_fun := f - g, map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm], map_smul' := λ r x, by simp only [pi.sub_apply, map_smul, smul_sub] }⟩ @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl lemma sub_comp (g : M₂ →ₗ[R] M₃) (h : M₂ →ₗ[R] M₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (g : M →ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) : h.comp (g - f) = h.comp g - h.comp f := by { ext, simp } /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add_left_neg := _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smul, smul_comm n c (f x)] }, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. linear_map.add_comm_monoid }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one] end add_comm_group section has_scalar variables {S : Type*} [semiring R] [monoid S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [distrib_mul_action S M₂] [smul_comm_class R S M₂] (f : M →ₗ[R] M₂) instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, { to_fun := a • f, map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add], map_smul' := λ c x, by simp only [pi.smul_apply, f.map_smul, smul_comm c] }⟩ @[simp] lemma smul_apply (a : S) (x : M) : (a • f) x = a • f x := rfl instance {T : Type*} [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance {T : Type*} [monoid T] [has_scalar S T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl end has_scalar section module variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := { to_fun := f.comp, map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _, map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ } /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section semiring variables [semiring R] [add_comm_monoid M] [module R M] instance endomorphism_semiring : semiring (M →ₗ[R] M) := by refine_struct { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, .. linear_map.add_comm_monoid, .. }; intros; try { refl }; apply linear_map.ext; simp {proj := ff} /-- The tautological action by `M →ₗ[R] M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_module : module (M →ₗ[R] M) M := { smul := ($), smul_zero := linear_map.map_zero, smul_add := linear_map.map_add, add_smul := linear_map.add_apply, zero_smul := (linear_map.zero_apply : ∀ m, (0 : M →ₗ[R] M) m = 0), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : M →ₗ[R] M) (a : M) : f • a = f a := rfl /-- `linear_map.apply_module` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (M →ₗ[R] M) M := ⟨λ _ _, linear_map.ext⟩ instance apply_smul_comm_class : smul_comm_class R (M →ₗ[R] M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M →ₗ[R] M) R M := { smul_comm := linear_map.map_smul } end semiring section ring variables [ring R] [add_comm_group M] [module R M] instance endomorphism_ring : ring (M →ₗ[R] M) := { ..linear_map.endomorphism_semiring, ..linear_map.add_comm_group } end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `ℕ`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} [add_comm_monoid A] [add_comm_monoid B] : (A →+ B) ≃ₗ[ℕ] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `ℤ`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} [add_comm_group A] [add_comm_group B] : (A →+ B) ≃ₗ[ℤ] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl theorem of_le_injective (h : p ≤ p') : function.injective (of_le h) := λ x y h, subtype.val_injective (subtype.mk.inj h) variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } instance pointwise_add_comm_monoid : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl variables (R) @[simp] lemma subsingleton_iff : subsingleton (submodule R M) ↔ subsingleton M := have h : subsingleton (submodule R M) ↔ subsingleton (add_submonoid M), { rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq.symm; refl, }, h.trans add_submonoid.subsingleton_iff @[simp] lemma nontrivial_iff : nontrivial (submodule R M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mpr ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mpr ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, smul_mem' := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₗ[R] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma map_add_le (f g : M →ₗ[R] M₂) : map (f + g) p ≤ map f p + map g p := begin rintros x ⟨m, hm, rfl⟩, exact add_mem_sup (mem_map_of_mem hm) (mem_map_of_mem hm), end lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₗ[R] M₂) → submodule R M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ /-- The pushforward of a submodule by an injective linear map is linearly equivalent to the original submodule. -/ noncomputable def equiv_map_of_injective (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) : p ≃ₗ[R] p.map f := { map_add' := by { intros, simp, refl, }, map_smul' := by { intros, simp, refl, }, ..(equiv.set.image f p i) } @[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₗ[R] M₂) (i : injective f) (p : submodule R M) (x : p) : (equiv_map_of_injective f i p x : M₂) = f x := rfl /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ section galois_insertion variables {f : M →ₗ[R] M₂} (hf : surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x hx, begin rcases hf x with ⟨y, rfl⟩, simp only [mem_map, mem_comap], exact ⟨y, hx, rfl⟩ end) lemma map_comap_eq_of_surjective (p : submodule R M₂) : (p.comap f).map f = p := (gi_map_comap hf).l_u_eq _ lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective lemma map_sup_comap_of_surjective (p q : submodule R M₂) : (p.comap f ⊔ q.comap f).map f = p ⊔ q := (gi_map_comap hf).l_sup_u _ _ lemma map_supr_comap_of_sujective (S : ι → submodule R M₂) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ lemma map_inf_comap_of_surjective (p q : submodule R M₂) : (p.comap f ⊓ q.comap f).map f = p ⊓ q := (gi_map_comap hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (S : ι → submodule R M₂) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ lemma comap_le_comap_iff_of_surjective (p q : submodule R M₂) : p.comap f ≤ q.comap f ↔ p ≤ q := (gi_map_comap hf).u_le_u_iff lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion section galois_coinsertion variables {f : M →ₗ[R] M₂} (hf : injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables {α : Type*} [monoid α] [distrib_mul_action α M] [smul_comm_class α R M] /-- The action on a submodule corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_distrib_mul_action : distrib_mul_action α (submodule R M) := { smul := λ a S, S.map (distrib_mul_action.to_linear_map _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (linear_map.ext $ by exact one_smul α)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (linear_map.ext $ by exact mul_smul _ _)).trans (S.map_comp _ _), smul_zero := λ a, map_bot _, smul_add := λ a S₁ S₂, map_sup _ _ _ } localized "attribute [instance] submodule.pointwise_distrib_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (a : α) (S : submodule R M) : ↑(a • S) = a • (S : set M) := rfl @[simp] lemma pointwise_smul_to_add_submonoid (a : α) (S : submodule R M) : (a • S).to_add_submonoid = a • S.to_add_submonoid := rfl @[simp] lemma pointwise_smul_to_add_subgroup {R M : Type*} [ring R] [add_comm_group M] [distrib_mul_action α M] [module R M] [smul_comm_class α R M] (a : α) (S : submodule R M) : (a • S).to_add_subgroup = a • S.to_add_subgroup := rfl lemma smul_mem_pointwise_smul (m : M) (a : α) (S : submodule R M) : m ∈ S → a • m ∈ a • S := (set.smul_mem_smul_set : _ → _ ∈ a • (S : set M)) @[simp] lemma smul_le_self_of_tower {α : Type*} [semiring α] [module α R] [module α M] [smul_comm_class α R M] [is_scalar_tower α R M] (a : α) (S : submodule R M) : a • S ≤ S := begin rintro y ⟨x, hx, rfl⟩, exact smul_of_tower_mem _ a hx, end end section variables {α : Type*} [semiring α] [module α M] [smul_comm_class α R M] /-- The action on a submodule corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. This is a stronger version of `submodule.pointwise_distrib_mul_action`. Note that `add_smul` does not hold so this cannot be stated as a `module`. -/ protected def pointwise_mul_action_with_zero : mul_action_with_zero α (submodule R M) := { zero_smul := λ S, (congr_arg (λ f, S.map f) (linear_map.ext $ by exact zero_smul α)).trans S.map_zero, .. submodule.pointwise_distrib_mul_action } localized "attribute [instance] submodule.pointwise_mul_action_with_zero" in pointwise end section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span (f : M →ₗ[R] M₂) (s : set M) : (span R s).map f = span R (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) (s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end alias submodule.map_span_le ← linear_map.map_span_le /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₗ[R] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (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 {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) := by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, } end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul' hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image (f : M →ₗ[R] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_add_iff_not_mem {I : submodule R M} {a : M} : I < I + (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I + (R ∙ a) ≤ I, { simp only [add_eq_sup, sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [add_eq_sup, le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I + (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q.to_add_submonoid } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm, add_assoc] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (@_root_.quotient.mk _ (quotient_rel p) x) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : has_sub (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a - b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ (neg_mem p h₂)⟩ @[simp] theorem mk_sub : (mk (x - y) : quotient p) = mk x - mk y := rfl instance : add_comm_group (quotient p) := { zero := (0 : quotient p), add := (+), neg := has_neg.neg, sub := has_sub.sub, add_assoc := by { rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, simp only [←mk_add p, quot_mk_eq_mk, add_assoc] }, zero_add := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, quot_mk_eq_mk, zero_add] }, add_zero := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, add_zero, quot_mk_eq_mk] }, add_comm := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, quot_mk_eq_mk, add_comm] }, add_left_neg := by { rintro ⟨x⟩, simp only [←mk_zero p, ←mk_add p, ←mk_neg p, quot_mk_eq_mk, add_left_neg] }, sub_eq_add_neg := by { rintros ⟨x⟩ ⟨y⟩, simp only [←mk_add p, ←mk_neg p, ←mk_sub p, sub_eq_add_neg, quot_mk_eq_mk] }, nsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, nsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, nsmul_succ' := by { rintros n ⟨⟩, simp only [nat.succ_eq_one_add, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul], refl }, gsmul := λ n x, quotient.lift_on' x (λ x, mk (n • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_of_tower_mem p n h, gsmul_zero' := by { rintros ⟨⟩, simp only [mk_zero, quot_mk_eq_mk, zero_smul], refl }, gsmul_succ' := by { rintros n ⟨⟩, simp [nat.succ_eq_add_one, add_nsmul, mk_add, quot_mk_eq_mk, one_nsmul, add_smul, add_comm], refl }, gsmul_neg' := by { rintros n ⟨x⟩, simp_rw [gsmul_neg_succ_of_nat, gsmul_coe_nat], refl }, } instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl @[simp] theorem mk_nsmul (n : ℕ) : (mk (n • x) : quotient p) = n • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] lemma mk_surjective : function.surjective (@mk _ _ _ _ _ p) := by { rintros ⟨x⟩, exact ⟨x, rfl⟩ } lemma nontrivial_of_lt_top (h : p < ⊤) : nontrivial (p.quotient) := begin obtain ⟨x, _, not_mem_s⟩ := set_like.exists_of_lt h, refine ⟨⟨mk x, 0, _⟩⟩, simpa using not_mem_s end end quotient lemma quot_hom_ext ⦃f g : quotient p →ₗ[R] M₂⦄ (h : ∀ x, f (quotient.mk x) = g (quotient.mk x)) : f = g := linear_map.ext $ λ x, quotient.induction_on' x h end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₗ[R] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₗ[R] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₗ[R] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] section sum variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₗ[R] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end sum section sum_add_hom variables [Π i, add_zero_class (γ i)] @[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₗ[R] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t := f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _ end sum_add_hom end dfinsupp theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range {f : M →ₗ[R] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map (f : M →ₗ[R] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self (f : M →ₗ[R] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : M →ₗ[R] M₂) : M →ₗ[R] f.range := f.cod_restrict f.range f.mem_range_self /-- The range of a linear map is finite if the domain is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype M₂`. -/ instance fintype_range [fintype M] [decidable_eq M₂] (f : M →ₗ[R] M₂) : fintype (range f) := set.fintype_range f section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₗ[R] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₗ[R] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M} (h : g.comp f = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma _root_.submodule.map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma _root_.submodule.map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [submodule.map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₗ[R] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) theorem ker_eq_bot_of_injective {f : M →ₗ[R] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule lemma _root_.submodule.comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma _root_.submodule.comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [submodule.comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₗ[R] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, submodule.comap_map_eq] theorem map_le_map_iff' {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables {f : M →ₗ[R] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables {T : semiring R} [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := { to_fun := quotient.mk, map_add' := by simp, map_smul' := by simp } @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- Two `linear_map`s from a quotient module are equal if their compositions with `submodule.mkq` are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma linear_map_qext ⦃f g : p.quotient →ₗ[R] M₂⦄ (h : f.comp p.mkq = g.comp p.mkq) : f = g := linear_map.ext $ λ x, quotient.induction_on' x $ (linear_map.congr_fun h : _) /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := { to_fun := λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, map_add' := by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, map_smul' := by rintro a ⟨x⟩; exact f.map_smul a x } @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] @[simp] theorem map_mkq_eq_top : map p.mkq p' = ⊤ ↔ p ⊔ p' = ⊤ := by simp only [map_eq_top_iff p.range_mkq, sup_comm, ker_mkq] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := by simpa only [range_eq_map] using map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.rel_iso : submodule R p.quotient ≃o {p' : submodule R M // p ≤ p'} := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simpa [comap_map_mkq p], map_rel_iff' := λ p₁ p₂, comap_le_comap_iff $ range_mkq _ } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.order_embedding : submodule R p.quotient ↪o submodule R M := (rel_iso.to_rel_embedding $ comap_mkq.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.order_embedding p p' = comap p.mkq p' := rfl lemma span_preimage_eq {f : M →ₗ[R] M₂} {s : set M₂} (h₀ : s.nonempty) (h₁ : s ⊆ range f) : span R (f ⁻¹' s) = (span R s).comap f := begin suffices : (span R s).comap f ≤ span R (f ⁻¹' s), { exact le_antisymm (span_preimage_le f s) this, }, have hk : ker f ≤ span R (f ⁻¹' s), { let y := classical.some h₀, have hy : y ∈ s, { exact classical.some_spec h₀, }, rw ker_le_iff, use [y, h₁ hy], rw ← set.singleton_subset_iff at hy, exact set.subset.trans subset_span (span_mono (set.preimage_mono hy)), }, rw ← left_eq_sup at hk, rw f.range_coe at h₁, rw [hk, ← map_le_map_iff, map_span, map_comap_eq, set.image_preimage_eq_of_subset h₁], exact inf_le_right, end end ring end submodule namespace linear_map section semiring variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top {f : M →ₗ[R] M₂} (g : M₂ →ₗ[R] M₃) (hf : range f = ⊤) : range (g.comp f) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₗ[R] M₂) {g : M₂ →ₗ[R] M₃} (hg : ker g = ⊥) : ker (g.comp f) = ker f := by rw [ker_comp, hg, submodule.comap_bot] end semiring section ring variables [ring R] [add_comm_monoid M] [add_comm_group M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] lemma range_mkq_comp (f : M →ₗ[R] M₂) : f.range.mkq.comp f = 0 := linear_map.ext $ λ x, by simp lemma ker_le_range_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : g.ker ≤ f.range ↔ f.range.mkq.comp g.ker.subtype = 0 := by rw [←range_le_ker_iff, submodule.ker_mkq, submodule.range_subtype] /-- An epimorphism is surjective. -/ lemma range_eq_top_of_cancel {f : M →ₗ[R] M₂} (h : ∀ (u v : M₂ →ₗ[R] f.range.quotient), u.comp f = v.comp f → u = v) : f.range = ⊤ := begin have h₁ : (0 : M₂ →ₗ[R] f.range.quotient).comp f = 0 := zero_comp _, rw [←submodule.ker_mkq f.range, ←h 0 f.range.mkq (eq.trans h₁ (range_mkq_comp _).symm)], exact ker_zero end end ring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section subsingleton variables [module R M] [module R M₂] [subsingleton M] [subsingleton M₂] /-- Between two zero modules, the zero map is an equivalence. -/ instance : has_zero (M ≃ₗ[R] M₂) := ⟨{ to_fun := 0, inv_fun := 0, right_inv := λ x, subsingleton.elim _ _, left_inv := λ x, subsingleton.elim _ _, ..(0 : M →ₗ[R] M₂)}⟩ -- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're -- nice to have as `rfl`-lemmas for `dsimp`. @[simp] lemma zero_symm : (0 : M ≃ₗ[R] M₂).symm = 0 := rfl @[simp] lemma coe_zero : ⇑(0 : M ≃ₗ[R] M₂) = 0 := rfl lemma zero_apply (x : M) : (0 : M ≃ₗ[R] M₂) x = 0 := rfl /-- Between two zero modules, the zero map is the only equivalence. -/ instance : unique (M ≃ₗ[R] M₂) := { uniq := λ f, to_linear_map_injective (subsingleton.elim _ _), default := 0 } end subsingleton section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma map_eq_comap {p : submodule R M} : (p.map e : submodule R M₂) = p.comap e.symm := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₗ[R] ↥(p.map ↑e : submodule R M₂) := { inv_fun := λ y, ⟨e.symm y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₗ[R] M₂).dom_restrict p).cod_restrict (p.map ↑e) (λ x, ⟨x, by simp⟩) } @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map ↑e : submodule R M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl end section finsupp variables {γ : Type*} [module R M] [module R M₂] [has_zero γ] @[simp] lemma map_finsupp_sum (f : M ≃ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] [module R M] [module R M₂] @[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] (f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ @[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₗ[R] M₂) (t : Π₀ i, γ i) (g : Π i, γ i →+ M) : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t := f.to_add_equiv.map_dfinsupp_sum_add_hom _ _ end dfinsupp section uncurry variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables {module_M : module R M} {module_M₂ : module R M₂} {module_M₃ : module R M₃} variables (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) (e : M ≃ₗ[R] M₂) (h : M₂ →ₗ[R] M₃) (l : M₃ →ₗ[R] M) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R M₂) (h : p.map ↑e = q) : p ≃ₗ[R] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : U.comap (f : M →ₗ[R] M₂) ≃ₗ[R] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U.comap (f : M →ₗ[R] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R M₂] (f : M ≃ₗ[R] M₂) (U : submodule R M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp : (h.comp (e : M →ₗ[R] M₂)).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range @[simp] theorem ker_comp : ((e : M →ₗ[R] M₂).comp l).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e.ker variables {f g} /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₗ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } @[simp] lemma of_left_inverse_apply (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl variables (f) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective (h : injective f) : M ≃ₗ[R] f.range := of_left_inverse $ classical.some_spec h.has_left_inverse @[simp] theorem of_injective_apply {h : injective f} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. -/ noncomputable def of_bijective (hf₁ : injective f) (hf₂ : surjective f) : M ≃ₗ[R] M₂ := (of_injective f hf₁).trans (of_top _ $ linear_map.range_eq_top.2 hf₂) @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ[R] M) (((a⁻¹ : units R) : R) • 1 : M →ₗ[R] M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp e₁.symm, inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp e₁, left_inv := λ f, by { ext x, simp only [symm_apply_apply, coe_comp, comp_app, coe_coe] }, right_inv := λ f, by { ext x, simp only [apply_symm_apply, coe_comp, comp_app, coe_coe] }, map_add' := λ f g, by { ext x, simp only [map_add, add_apply, coe_comp, comp_app, coe_coe] }, map_smul' := λ c f, by { ext x, simp only [map_smul, smul_apply, coe_comp, comp_app, coe_coe] } } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_monoid N] [add_comm_monoid N₂] [add_comm_monoid N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂] [add_comm_monoid M₃] [module R M₃] [add_comm_monoid N₁] [module R N₁] [add_comm_monoid N₂] [module R N₂] [add_comm_monoid N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ[R] (M →ₗ[R] M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp e.symm := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp e := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_semiring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_eq_bot.1 $ ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ @[simps] def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module variables [ring R] [add_comm_group M] [module R M] variables (p : submodule R M) open linear_map /-- If `p = ⊥`, then `M / p ≃ₗ[R] M`. -/ def quot_equiv_of_eq_bot (hp : p = ⊥) : p.quotient ≃ₗ[R] M := linear_equiv.of_linear (p.liftq id $ hp.symm ▸ bot_le) p.mkq (liftq_mkq _ _ _) $ p.quot_hom_ext $ λ x, rfl @[simp] lemma quot_equiv_of_eq_bot_apply_mk (hp : p = ⊥) (x : M) : p.quot_equiv_of_eq_bot hp (quotient.mk x) = x := rfl @[simp] lemma quot_equiv_of_eq_bot_symm_apply (hp : p = ⊥) (x : M) : (p.quot_equiv_of_eq_bot hp).symm x = quotient.mk x := rfl @[simp] lemma coe_quot_equiv_of_eq_bot_symm (hp : p = ⊥) : ((p.quot_equiv_of_eq_bot hp).symm : M →ₗ[R] p.quotient) = p.mkq := rfl variables (q : submodule R M) /-- Quotienting by equal submodules gives linearly equivalent quotients. -/ def quot_equiv_of_eq (h : p = q) : p.quotient ≃ₗ[R] q.quotient := { map_add' := by { rintros ⟨x⟩ ⟨y⟩, refl }, map_smul' := by { rintros x ⟨y⟩, refl }, ..@quotient.congr _ _ (quotient_rel p) (quotient_rel q) (equiv.refl _) $ λ a b, by { subst h, refl } } @[simp] lemma quot_equiv_of_eq_mk (h : p = q) (x : M) : submodule.quot_equiv_of_eq p q h (submodule.quotient.mk x) = submodule.quotient.mk x := rfl end submodule namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) @[simp] lemma mem_map_equiv {e : M ≃ₗ[R] M₂} {x : M₂} : x ∈ p.map (e : M →ₗ[R] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end lemma map_equiv_eq_comap_symm (e : M ≃ₗ[R] M₂) (K : submodule R M) : K.map (e : M →ₗ[R] M₂) = K.comap e.symm := submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe]) lemma comap_equiv_eq_map_symm (e : M ≃ₗ[R] M₂) (K : submodule R M₂) : K.comap (e : M →ₗ[R] M₂) = K.map e.symm := (map_equiv_eq_comap_symm e.symm K).symm lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw set_like.le_def, intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply q.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero_mem' := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, map_add' := λ x y, by { ext, refl, }, map_smul' := λ c f, by { ext, refl, } } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv namespace linear_map open submodule section isomorphism_laws variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := (linear_equiv.of_injective (f.ker.liftq f $ le_refl _) $ ker_eq_bot.mp $ submodule.ker_liftq_eq_bot _ _ _ (le_refl f.ker)).trans (linear_equiv.of_eq _ _ $ submodule.range_liftq _ _ _) /-- The first isomorphism theorem for surjective linear maps. -/ noncomputable def quot_ker_equiv_of_surjective (f : M →ₗ[R] M₂) (hf : function.surjective f) : f.ker.quotient ≃ₗ[R] M₂ := f.quot_ker_equiv_range.trans (linear_equiv.of_top f.range (linear_map.range_eq_top.2 hf)) @[simp] lemma quot_ker_equiv_range_apply_mk (x : M) : (f.quot_ker_equiv_range (submodule.quotient.mk x) : M₂) = f x := rfl @[simp] lemma quot_ker_equiv_range_symm_apply_image (x : M) (h : f x ∈ f.range) : f.quot_ker_equiv_range.symm ⟨f x, h⟩ = f.ker.mkq x := f.quot_ker_equiv_range.symm_apply_apply (f.ker.mkq x) /-- Canonical linear map from the quotient `p/(p ∩ p')` to `(p+p')/p'`, mapping `x + (p ∩ p')` to `x + p'`, where `p` and `p'` are submodules of an ambient module. -/ def quotient_inf_to_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf_right _ le_sup_left) end /-- Second Isomorphism Law : the canonical map from `p/(p ∩ p')` to `(p+p')/p'` as a linear isomorphism. -/ noncomputable def quotient_inf_equiv_sup_quotient (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := linear_equiv.of_bijective (quotient_inf_to_sup_quotient p p') begin rw [← ker_eq_bot, quotient_inf_to_sup_quotient, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], exact λ ⟨x, hx1⟩ hx2, ⟨hx1, hx2⟩ end begin rw [← range_eq_top, quotient_inf_to_sup_quotient, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end @[simp] lemma coe_quotient_inf_to_sup_quotient (p p' : submodule R M) : ⇑(quotient_inf_to_sup_quotient p p') = quotient_inf_equiv_sup_quotient p p' := rfl @[simp] lemma quotient_inf_equiv_sup_quotient_apply_mk (p p' : submodule R M) (x : p) : quotient_inf_equiv_sup_quotient p p' (submodule.quotient.mk x) = submodule.quotient.mk (of_le (le_sup_left : p ≤ p ⊔ p') x) := rfl lemma quotient_inf_equiv_sup_quotient_symm_apply_left (p p' : submodule R M) (x : p ⊔ p') (hx : (x:M) ∈ p) : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = submodule.quotient.mk ⟨x, hx⟩ := (linear_equiv.symm_apply_eq _).2 $ by simp [of_le_apply] @[simp] lemma quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff {p p' : submodule R M} {x : p ⊔ p'} : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 ↔ (x:M) ∈ p' := (linear_equiv.symm_apply_eq _).trans $ by simp [of_le_apply] lemma quotient_inf_equiv_sup_quotient_symm_apply_right (p p' : submodule R M) {x : p ⊔ p'} (hx : (x:M) ∈ p') : (quotient_inf_equiv_sup_quotient p p').symm (submodule.quotient.mk x) = 0 := quotient_inf_equiv_sup_quotient_symm_apply_eq_zero_iff.2 hx end isomorphism_laws end linear_map section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} namespace linear_map /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := { to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, simp only [← linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id] end end linear_map namespace linear_equiv open linear_map /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end linear_equiv end fun_left namespace linear_equiv variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } /-- Restriction from `R`-linear automorphisms of `M` to `R`-linear endomorphisms of `M`, promoted to a monoid hom. -/ def automorphism_group.to_linear_map_monoid_hom : (M ≃ₗ[R] M) →* (M →ₗ[R] M) := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The tautological action by `M ≃ₗ[R] M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_distrib_mul_action : distrib_mul_action (M ≃ₗ[R] M) M := { smul := ($), smul_zero := linear_equiv.map_zero, smul_add := linear_equiv.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : M ≃ₗ[R] M) (a : M) : f • a = f a := rfl /-- `linear_equiv.apply_distrib_mul_action` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (M ≃ₗ[R] M) M := ⟨λ _ _, linear_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (M ≃ₗ[R] M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M ≃ₗ[R] M) R M := { smul_comm := linear_equiv.map_smul } end linear_equiv namespace linear_map variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ section third_iso_thm variables (S T : submodule R M) (h : S ≤ T) /-- The map from the third isomorphism theorem for modules: `(M / S) / (T / S) → M / T`. -/ def quotient_quotient_equiv_quotient_aux : quotient (T.map S.mkq) →ₗ[R] quotient T := liftq _ (mapq S T linear_map.id h) (by { rintro _ ⟨x, hx, rfl⟩, rw [linear_map.mem_ker, mkq_apply, mapq_apply], exact (quotient.mk_eq_zero _).mpr hx }) @[simp] lemma quotient_quotient_equiv_quotient_aux_mk (x : S.quotient) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk x) = mapq S T linear_map.id h x := liftq_apply _ _ _ @[simp] lemma quotient_quotient_equiv_quotient_aux_mk_mk (x : M) : quotient_quotient_equiv_quotient_aux S T h (quotient.mk (quotient.mk x)) = quotient.mk x := by rw [quotient_quotient_equiv_quotient_aux_mk, mapq_apply, linear_map.id_apply] /-- **Noether's third isomorphism theorem** for modules: `(M / S) / (T / S) ≃ M / T`. -/ def quotient_quotient_equiv_quotient : quotient (T.map S.mkq) ≃ₗ[R] quotient T := { to_fun := quotient_quotient_equiv_quotient_aux S T h, inv_fun := mapq _ _ (mkq S) (le_comap_map _ _), left_inv := λ x, quotient.induction_on' x $ λ x, quotient.induction_on' x $ λ x, by simp, right_inv := λ x, quotient.induction_on' x $ λ x, by simp, .. quotient_quotient_equiv_quotient_aux S T h } end third_iso_thm end submodule
b63cb0919a3474b616662e99d2f46e8d70e67420
137c667471a40116a7afd7261f030b30180468c2
/src/data/list/basic.lean
4caf35a1c18e03933a6c042ca44a5c67eaaec68b
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
195,128
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import control.monad.basic import data.nat.basic import order.rel_classes import algebra.group_power.basic /-! # Basic properties of lists -/ open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l := mt (congr_arg length) (nat.succ_ne_self _) theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) @[simp] theorem cons_injective {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := cons_injective.eq_iff theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L := by { induction l with c l', contradiction, use [c,l'], } /-! ### mem -/ theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ 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 _root_.decidable.list.eq_or_ne_mem_of_mem [decidable_eq α] {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := decidable.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} : a ∈ b :: l → a = b ∨ (a ≠ b ∧ a ∈ l) := by classical; exact decidable.list.eq_or_ne_mem_of_mem theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {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, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] lemma map_bind (g : β → list γ) (f : α → β) : ∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a)) | [] := rfl | (a::l) := by simp only [cons_bind, map_cons, map_bind l] /-! ### length -/ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ @[simp] lemma length_singleton (a : α) : length [a] = 1 := rfl theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] := λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1) theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l := λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0 theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ lemma exists_mem_of_ne_nil (l : list α) (h : l ≠ []) : ∃ x, x ∈ l := exists_mem_of_length_pos (length_pos_of_ne_nil h) theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ lemma exists_of_length_succ {n} : ∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t | [] H := absurd H.symm $ succ_ne_zero n | (h :: t) H := ⟨h, t, rfl⟩ @[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α := begin split, { intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl }, { intros hα l1 l2 hl, induction l1 generalizing l2; cases l2, { refl }, { cases hl }, { cases hl }, congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl } end @[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) := length_injective_iff.mpr $ by apply_instance /-! ### set-theoretic notation of lists -/ lemma empty_eq : (∅ : list α) = [] := by refl lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) : has_insert.insert x l = x :: l := if_neg h lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) : has_insert.insert x l = l := if_pos h lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] := by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] } /-! ### bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. theorem forall_mem_cons : ∀ {p : α → Prop} {a : α} {l : list α}, (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := ball_cons theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /-! ### list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_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 _) @[simp] theorem append_subset_iff {l₁ l₂ l : list α} : l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := begin split, { intro h, simp only [subset_def] at *, split; intros; simp* }, { rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 } end theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) : map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ := begin refine ⟨_, map_subset f⟩, intros h2 x hx, rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩, cases h hxx', exact hx' end /-! ### append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl @[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl 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 @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[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 only [split_at, split_at_eq_take_drop n xs, take, drop] @[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) := congr_arg (cons x) $ 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_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_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' {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 only [length_append] at hap; rwa [← hl] at hap theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_injective (s : list α) : function.injective (λ t, s ++ t) := λ t₁ t₂, append_left_cancel theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := (append_right_injective s).eq_iff theorem append_left_injective (t : list α) : function.injective (λ s, s ++ t) := λ s₁ s₂, append_right_cancel theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := (append_left_injective t).eq_iff theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /-! ### repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n ↔ n ≠ 0 ∧ b = a | 0 := by simp | (n + 1) := by simp [mem_repeat] theorem eq_of_mem_repeat {a b : α} {n} (h : b ∈ repeat a n) : b = a := (mem_repeat.1 h).2 theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) : function.injective (λ a : α, repeat a n) := λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩ lemma repeat_left_inj {a b : α} {n : ℕ} (hn : n ≠ 0) : repeat a n = repeat b n ↔ a = b := (repeat_left_injective hn).eq_iff @[simp] lemma repeat_left_inj' {a b : α} : ∀ {n}, repeat a n = repeat b n ↔ n = 0 ∨ a = b | 0 := by simp | (n + 1) := (repeat_left_inj n.succ_ne_zero).trans $ by simp only [n.succ_ne_zero, false_or] lemma repeat_right_injective (a : α) : function.injective (repeat a) := function.left_inverse.injective (length_repeat a) @[simp] lemma repeat_right_inj {a : α} {n m : ℕ} : repeat a n = repeat a m ↔ n = m := (repeat_right_injective a).eq_iff /-! ### pure -/ @[simp] theorem mem_pure {α} (x y : α) : x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret] /-! ### bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl -- TODO: duplicate of a lemma in core theorem bind_append (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ @[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x := append_nil (f x) /-! ### concat -/ theorem concat_nil (a : α) : concat [] a = [a] := rfl theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact append_right_cancel h end theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b := begin intro h, rw [concat_eq_append, concat_eq_append] at h, exact head_eq_of_cons_eq (append_left_cancel h) end theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by simp theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by simp theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by simp /-! ### reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[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; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l := by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl @[simp] theorem reverse_involutive : involutive (@reverse α) := λ l, reverse_reverse l @[simp] theorem reverse_injective : injective (@reverse α) := reverse_involutive.injective @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff lemma reverse_eq_iff {l l' : list α} : l.reverse = l' ↔ l = l'.reverse := reverse_involutive.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ /-! ### empty -/ attribute [simp] list.empty lemma empty_iff_eq_nil {l : list α} : l.empty ↔ l = [] := list.cases_on l (by simp) (by simp) /-! ### init -/ @[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1 | [] := rfl | [a] := rfl | (a :: b :: l) := begin rw init, simp only [add_left_inj, length, succ_add_sub_one], exact length_init (b :: l) end /-! ### 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, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[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 init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l | [] h := absurd rfl h | [a] h := rfl | (a::b::l) h := begin rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)], congr, exact init_append_last (cons_ne_nil b l) end theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l | [] h := absurd rfl h | [a] h := or.inl rfl | (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) } lemma last_repeat_succ (a m : ℕ) : (repeat a m.succ).last (ne_nil_of_length_eq_succ (show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a := begin induction m with k IH, { simp }, { simpa only [repeat_succ, last] } end /-! ### last' -/ @[simp] theorem last'_is_none : ∀ {l : list α}, (last' l).is_none ↔ l = [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_none (b::l)] @[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ [] | [] := by simp | [a] := by simp | (a::b::l) := by simp [@last'_is_some (b::l)] theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h | [] x hx := false.elim $ by simpa using hx | [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩ | (a::b::l) x hx := begin rw last' at hx, rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩, use cons_ne_nil _ _, rwa [last_cons] end theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l := let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _ theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l | [] a ha := (option.not_mem_none a ha).elim | [a] _ rfl := rfl | (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] } theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget | [] := by simp [ilast, arbitrary] | [a] := rfl | [a, b] := rfl | [a, b, c] := rfl | (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)] @[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α), last' (l₁ ++ a :: l₂) = last' (a :: l₂) | [] a l₂ := rfl | [b] a l₂ := rfl | (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons] theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []), last' (l₁ ++ l₂) = last' l₂ | [] hl₂ := by contradiction | (b::l₂) _ := last'_append_cons l₁ b l₂ /-! ### head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l | [] h := (option.not_mem_none _ h).elim | (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl } @[simp] theorem head_cons [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 [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) : tail (l ++ [a]) = tail l ++ [a] := by { induction l, contradiction, rw [tail,cons_append,tail], } theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l | [] a h := by contradiction | (b::l) a h := by { simp at h, simp [h] } theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l | [] h := by contradiction | (a::l) h := rfl theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := cons_head'_tail (head_mem_head' h) lemma head_mem_self [inhabited α] {l : list α} (h : l ≠ nil) : l.head ∈ l := begin have h' := mem_cons_self l.head l.tail, rwa cons_head_tail h at h', end @[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl lemma tail_append_of_ne_nil (l l' : list α) (h : l ≠ []) : (l ++ l').tail = l.tail ++ l' := begin cases l, { contradiction }, { simp } end /-! ### Induction from the right -/ /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /-- Bidirectional induction principle for lists: if a property holds for the empty list, the singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def bidirectional_rec {C : list α → Sort*} (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l | [] := H0 | [a] := H1 a | (a :: b :: l) := let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in have length l' < length (a :: b :: l), by { change _ < length l + 2, simp }, begin rw ←init_append_last (cons_ne_nil b l), have : C l', from bidirectional_rec l', exact Hn a l' b' ‹C l'› end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] } /-- Like `bidirectional_rec`, but with the list parameter placed first. -/ @[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a]) (Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l := bidirectional_rec H0 H1 Hn 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_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_append_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact ih.append_right [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff] using h.reverse, λ h, h.append_right l⟩ theorem sublist.append {l₁ l₂ r₁ r₂ : list α} (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := (hl.append_right _).trans ((append_sublist_append_left _).2 hr) theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset 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 _ (sublist.subset s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, h.subset (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset @[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] := ⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩ theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /-! ### index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp, priority 990] 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, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp, priority 980] 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, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, decidable.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_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_len_le hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ @[simp] theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n := begin intros, split, { intro h, by_contradiction h', have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩, rw [← nth_eq_some, h] at h₂, cases h₂ }, { solve_by_elim [nth_len_le] }, end theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm lemma nth_zero (l : list α) : l.nth 0 = l.head' := by cases l; refl lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ} (h₀ : i < xs.length) (h₁ : nodup xs) (h₂ : xs.nth i = xs.nth j) : i = j := begin induction xs with x xs generalizing i j, { cases h₀ }, { cases i; cases j, case nat.zero nat.zero { refl }, case nat.succ nat.succ { congr, cases h₁, apply xs_ih; solve_by_elim [lt_of_succ_lt_succ] }, iterate 2 { dsimp at h₂, cases h₁ with _ _ h h', cases h x _ rfl, rw mem_iff_nth, exact ⟨_, h₂.symm⟩ <|> exact ⟨_, h₂⟩ } }, end @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl /-- A version of `nth_le_map` that can be used for rewriting. -/ theorem nth_le_map_rev (f : α → β) {l n} (H) : f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) := (nth_le_map f _ _).symm @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ /-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as `hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make such a rewrite, with `rw (nth_le_of_eq h)`. -/ lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) : nth_le L i hi = nth_le L' i (h ▸ hi) := by { congr, exact h} @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) : L.nth_le 0 h = L.head := by { cases L, cases h, simp, } lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length := begin rw list.length_append at h₂, convert (nat.sub_lt_sub_right_iff h₁).mpr h₂, simp, end lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂), (l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂) | [] _ n h₁ h₂ := rfl | (a :: l) _ (n+1) h₁ h₂ := begin dsimp, conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], }, rw nth_le_append_right (nat.lt_succ_iff.mp h₁), end @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) : (list.repeat a n).nth_le m h = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] lemma nth_append_right {l₁ l₂ : list α} {n : ℕ} (hn : l₁.length ≤ n) : (l₁ ++ l₂).nth n = l₂.nth (n - l₁.length) := begin by_cases hl : n < (l₁ ++ l₂).length, { rw [nth_le_nth hl, nth_le_nth, nth_le_append_right hn] }, { rw [nth_len_le (le_of_not_lt hl), nth_len_le], rw [not_lt, length_append] at hl, exact nat.le_sub_left_of_add_le hl } end lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos) | [] h := rfl | [a] h := by rw [last_singleton, nth_le_singleton] | (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)], refl, exact cons_ne_nil b l } @[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] lemma nth_le_cons_length (x : α) (xs : list α) (n : ℕ) (h : n = xs.length) : (x :: xs).nth_le n (by simp [h]) = (x :: xs).last (cons_ne_nil x xs) := begin rw last_eq_nth_le, congr, simp [h] end @[ext] 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 only [aa, ext (λn, h (n+1))]; split; refl 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_len_le h₁, nth_len_le], 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 h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[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, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) lemma index_of_inj [decidable_eq α] {l : list α} {x y : α} (hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y := ⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) = nth_le l (index_of y l) (index_of_lt_length.2 hy), by simp only [h], by simpa only [index_of_nth_le], λ h, by subst h⟩ 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 _ _ _ _ _ lemma nth_le_reverse' (l : list α) (n : ℕ) (hn : n < l.reverse.length) (hn') : l.reverse.nth_le n hn = l.nth_le (l.length - 1 - n) hn' := begin rw eq_comm, convert nth_le_reverse l.reverse _ _ _ using 1, { simp }, { simpa } end lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) : l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] := begin refine ext_le (by convert h) (λ n h₁ h₂, _), simp only [nth_le_singleton], congr, exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂) end lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] @[simp] lemma update_nth_nil (n : ℕ) (a : α) : [].update_nth n a = [] := rfl @[simp] lemma update_nth_succ (x : α) (xs : list α) (n : ℕ) (a : α) : (x :: xs).update_nth n.succ a = x :: xs.update_nth n a := rfl lemma update_nth_comm (a b : α) : Π {n m : ℕ} (l : list α) (h : n ≠ m), (l.update_nth n a).update_nth m b = (l.update_nth m b).update_nth n a | _ _ [] _ := by simp | 0 0 (x :: t) h := absurd rfl h | (n + 1) 0 (x :: t) h := by simp [list.update_nth] | 0 (m + 1) (x :: t) h := by simp [list.update_nth] | (n + 1) (m + 1) (x :: t) h := by { simp only [update_nth, true_and, eq_self_iff_true], exact update_nth_comm t (λ h', h $ nat.succ_inj'.mpr h'), } @[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α) (h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a := by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at * @[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α) (hj : j < (l.update_nth i a).length) : (l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) := by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth] lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α} (h : a ∈ l.update_nth n b), a ∈ l ∨ a = b | [] n a b h := false.elim h | (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim or.inr (or.inl ∘ mem_cons_of_mem _) | (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim (λ h, h ▸ or.inl (mem_cons_self _ _)) (λ h, (mem_or_eq_of_mem_update_nth h).elim (or.inl ∘ mem_cons_of_mem _) or.inr) section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl @[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length), a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l | 0 as h := iff.rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := begin dsimp [list.insert_nth], erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff, ← or.assoc, or_comm (a = a'), or.assoc] end end insert_nth /-! ### map -/ @[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl theorem map_eq_foldr (f : α → β) (l : list α) : map f l = foldr (λ a bs, f a :: bs) [] l := by induction l; simp * lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) := begin refine ⟨_, map_congr⟩, intros h x hx, rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩, rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h end theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl @[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f := begin split; intros h x y hxy, { suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] }, { induction y generalizing x, simpa using hxy, cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] } end /-- A single `list.map` of a composition of functions is equal to composing a `list.map` with another `list.map`, fully applied. This is the reverse direction of `list.map_map`. -/ lemma comp_map (h : β → γ) (g : α → β) (l : list α) : map (h ∘ g) l = map h (map g l) := (map_map _ _ _).symm /-- Composing a `list.map` with another `list.map` is equal to a single `list.map` of composed functions. -/ @[simp] lemma map_comp_map (g : β → γ) (f : α → β) : map g ∘ map f = map (g ∘ f) := by { ext l, rw comp_map } theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) : map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as := by { induction as, { refl }, { simp! [*, apply_ite (map f)] } } lemma last_map (f : α → β) {l : list α} (hl : l ≠ []) : (l.map f).last (mt eq_nil_of_map_eq_nil hl) = f (l.last hl) := begin induction l with l_ih l_tl l_ih, { apply (hl rfl).elim }, { cases l_tl, { simp }, { simpa using l_ih } } end /-! ### map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl @[simp] theorem map₂_flip (f : α → β → γ) : ∀ as bs, map₂ (flip f) bs as = map₂ f as bs | [] [] := rfl | [] (b :: bs) := rfl | (a :: as) [] := rfl | (a :: as) (b :: bs) := by { simp! [map₂_flip], refl } /-! ### take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[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 @[simp] theorem take_length : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → 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_le (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left 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 rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m) | n 0 := by simp | 0 m := by simp | (succ n) (succ m) := by simp [min_succ_succ, take_repeat] lemma map_take {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_take], } lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] /-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first `i` elements of `l₂` to `l₁`. -/ lemma take_append {l₁ l₂ : list α} (i : ℕ) : take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self] end /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) : nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) := by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ } /-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of length `> i`. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) : nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) := by { simp at hi, rw nth_le_take L _ hi.1 } lemma nth_take {l : list α} {n m : ℕ} (h : m < n) : (l.take n).nth m = l.nth m := begin induction n with n hn generalizing l m, { simp only [nat.nat_zero_eq_zero] at h, exact absurd h (not_lt_of_le m.zero_le) }, { cases l with hd tl, { simp only [take_nil] }, { cases m, { simp only [nth, take] }, { simpa only using hn (nat.lt_of_succ_lt_succ h) } } }, end @[simp] lemma nth_take_of_succ {l : list α} {n : ℕ} : (l.take (n + 1)).nth n = l.nth n := nth_take (nat.lt_succ_self n) lemma take_succ {l : list α} {n : ℕ} : l.take (n + 1) = l.take n ++ (l.nth n).to_list := begin induction l with hd tl hl generalizing n, { simp only [option.to_list, nth, take_nil, append_nil]}, { cases n, { simp only [option.to_list, nth, eq_self_iff_true, and_self, take, nil_append] }, { simp only [hl, cons_append, nth, eq_self_iff_true, and_self, take] } } end @[simp] lemma take_eq_nil_iff {l : list α} {k : ℕ} : l.take k = [] ↔ l = [] ∨ k = 0 := by { cases l; cases k; simp [nat.succ_ne_zero] } lemma init_eq_take (l : list α) : l.init = l.take l.length.pred := begin cases l with x l, { simp [init] }, { induction l with hd tl hl generalizing x, { simp [init], }, { simp [init, hl] } } end lemma init_take {n : ℕ} {l : list α} (h : n < l.length) : (l.take n).init = l.take n.pred := by simp [init_eq_take, min_eq_left_of_lt h, take_take, pred_le] @[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) : l.drop k = [] := by simpa [←length_eq_zero] using nat.sub_eq_zero_of_le h lemma drop_eq_nil_iff_le {l : list α} {k : ℕ} : l.drop k = [] ↔ l.length ≤ k := begin refine ⟨λ h, _, drop_eq_nil_of_le⟩, induction k with k hk generalizing l, { simp only [drop] at h, simp [h] }, { cases l, { simp }, { simp only [drop] at h, simpa [nat.succ_le_succ_iff] using hk h } } end lemma tail_drop (l : list α) (n : ℕ) : (l.drop n).tail = l.drop (n + 1) := begin induction l with hd tl hl generalizing n, { simp }, { cases n, { simp }, { simp [hl] } } end lemma cons_nth_le_drop_succ {l : list α} {n : ℕ} (hn : n < l.length) : l.nth_le n hn :: l.drop (n + 1) = l.drop n := begin induction l with hd tl hl generalizing n, { exact absurd n.zero_le (not_le_of_lt (by simpa using hn)) }, { cases n, { simp }, { simp only [nat.succ_lt_succ_iff, list.length] at hn, simpa [list.nth_le, list.drop] using hl hn } } end theorem drop_nil : ∀ n, drop n [] = ([] : list α) := λ _, drop_eq_nil_of_le (nat.zero_le _) lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α} (h : x ∈ l.drop n) : x ∈ l := begin induction l generalizing n, case list.nil : n h { simpa using h }, case list.cons : l_hd l_tl l_ih n h { cases n; simp only [mem_cons_iff, drop] at h ⊢, { exact h }, right, apply l_ih h }, end @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_length (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] /-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements up to `i` in `l₂`. -/ lemma drop_append {l₁ l₂ : list α} (i : ℕ) : drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ := begin induction l₁, { simp }, have : length l₁_tl + 1 + i = (length l₁_tl + i).succ, by { rw nat.succ_eq_add_one, exact succ_add _ _ }, simp only [cons_append, length, this, drop, l₁_ih] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/ lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) : nth_le L (i + j) h = nth_le (L.drop i) j begin have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h, rw (take_append_drop i L).symm at h, simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h end := begin have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)], rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right]; simp [A] end /-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/ lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) : nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) := by rw nth_le_drop lemma nth_drop (L : list α) (i j : ℕ) : nth (L.drop i) j = nth L (i + j) := begin ext, simp only [nth_eq_some, nth_le_drop', option.mem_def], split; exact λ ⟨h, ha⟩, ⟨by simpa [nat.lt_sub_left_iff_add_lt] using h, ha⟩ end @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by ac_refl, by simpa [take_cons, h] using drop_take m n l lemma map_drop {α β : Type*} (f : α → β) : ∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [map_drop], } theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] lemma reverse_take {α} {xs : list α} (n : ℕ) (h : n ≤ xs.length) : xs.reverse.take n = (xs.drop (xs.length - n)).reverse := begin induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil], cases h.lt_or_eq_dec with h' h', { replace h' := le_of_succ_le_succ h', rwa [take_append_of_le_length, xs_ih _ h'], rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop], { rwa [succ_eq_add_one, nat.sub_add_comm] }, { rwa length_reverse } }, { subst h', rw [length, nat.sub_self, drop], suffices : xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, by rw [this, take_length, reverse_cons], rw [length_append, length_reverse], refl } end @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /-! ### foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; 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; [refl, simp only [*, map, 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; [refl, simp only [*, map, foldr]] theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldl f' (g a) (l.map g) = g (list.foldl f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β) (a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) : list.foldr f' (g a) (l.map g) = g (list.foldr f a l) := begin induction l generalizing a, { simp }, { simp [l_ih, h] } end theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α) (h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) := eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] } theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α) (h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) := by { revert a, induction l; intros; [refl, simp only [*, foldr]] } lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α} (hl : ∀ f ∈ l, function.injective f) (hf : function.injective f): function.injective (@list.foldl (α → α) (α → α) function.comp f l) := begin induction l generalizing f, { exact hf }, { apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)), apply function.injective.comp hf, apply hl _ (list.mem_cons_self _ _) } end /-- Induction principle for values produced by a `foldr`: if a property holds for the seed element `b : β` and for all incremental `op : α → β → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldr_rec_on {C : β → Sort*} (l : list α) (op : α → β → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op a b)) : C (foldr op b l) := begin induction l with hd tl IH, { exact hb }, { refine hl _ _ hd (mem_cons_self hd tl), refine IH _, intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) } end /-- Induction principle for values produced by a `foldl`: if a property holds for the seed element `b : β` and for all incremental `op : β → α → β` performed on the elements `(a : α) ∈ l`. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ def foldl_rec_on {C : β → Sort*} (l : list α) (op : β → α → β) (b : β) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ l), C (op b a)) : C (foldl op b l) := begin induction l with hd tl IH generalizing b, { exact hb }, { refine IH _ _ _, { intros y hy x hx, exact hl y hy x (mem_cons_of_mem hd hx) }, { exact hl b hb hd (mem_cons_self hd tl) } } end @[simp] lemma foldr_rec_on_nil {C : β → Sort*} (op : α → β → β) (b) (hb : C b) (hl) : foldr_rec_on [] op b hb hl = hb := rfl @[simp] lemma foldr_rec_on_cons {C : β → Sort*} (x : α) (l : list α) (op : α → β → β) (b) (hb : C b) (hl : ∀ (b : β) (hb : C b) (a : α) (ha : a ∈ (x :: l)), C (op a b)) : foldr_rec_on (x :: l) op b hb hl = hl _ (foldr_rec_on l op b hb (λ b hb a ha, hl b hb a (mem_cons_of_mem _ ha))) x (mem_cons_self _ _) := rfl @[simp] lemma foldl_rec_on_nil {C : β → Sort*} (op : β → α → β) (b) (hb : C b) (hl) : foldl_rec_on [] op b hb hl = hb := rfl /- scanl -/ section scanl variables {f : β → α → β} {b : β} {a : α} {l : list α} lemma length_scanl : ∀ a l, length (scanl f a l) = l.length + 1 | a [] := rfl | a (x :: l) := by erw [length_cons, length_cons, length_scanl] @[simp] lemma scanl_nil (b : β) : scanl f b nil = [b] := rfl @[simp] lemma scanl_cons : scanl f b (a :: l) = [b] ++ scanl f (f b a) l := by simp only [scanl, eq_self_iff_true, singleton_append, and_self] @[simp] lemma nth_zero_scanl : (scanl f b l).nth 0 = some b := begin cases l, { simp only [nth, scanl_nil] }, { simp only [nth, scanl_cons, singleton_append] } end @[simp] lemma nth_le_zero_scanl {h : 0 < (scanl f b l).length} : (scanl f b l).nth_le 0 h = b := begin cases l, { simp only [nth_le, scanl_nil] }, { simp only [nth_le, scanl_cons, singleton_append] } end lemma nth_succ_scanl {i : ℕ} : (scanl f b l).nth (i + 1) = ((scanl f b l).nth i).bind (λ x, (l.nth i).map (λ y, f x y)) := begin induction l with hd tl hl generalizing b i, { symmetry, simp only [option.bind_eq_none', nth, forall_2_true_iff, not_false_iff, option.map_none', scanl_nil, option.not_mem_none, forall_true_iff] }, { simp only [nth, scanl_cons, singleton_append], cases i, { simp only [option.map_some', nth_zero_scanl, nth, option.some_bind'] }, { simp only [hl, nth] } } end lemma nth_le_succ_scanl {i : ℕ} {h : i + 1 < (scanl f b l).length} : (scanl f b l).nth_le (i + 1) h = f ((scanl f b l).nth_le i (nat.lt_of_succ_lt h)) (l.nth_le i (nat.lt_of_succ_lt_succ (lt_of_lt_of_le h (le_of_eq (length_scanl b l))))) := begin induction i with i hi generalizing b l, { cases l, { simp only [length, zero_add, scanl_nil] at h, exact absurd h (lt_irrefl 1) }, { simp only [scanl_cons, singleton_append, nth_le_zero_scanl, nth_le] } }, { cases l, { simp only [length, add_lt_iff_neg_right, scanl_nil] at h, exact absurd h (not_lt_of_lt nat.succ_pos') }, { simp_rw scanl_cons, rw nth_le_append_right _, { simpa only [hi, length, succ_add_sub_one] }, { simp only [length, nat.zero_le, le_add_iff_nonneg_left] } } } end end scanl /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section foldl_eq_foldlr' variables {f : α → β → α} variables hf : ∀ a b c, f (f a b) c = f (f a c) b include hf theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b | a b [] := rfl | a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf] theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l | a [] := rfl | a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl end foldl_eq_foldlr' section foldl_eq_foldlr' variables {f : α → β → β} variables hf : ∀ a b c, f a (f b c) = f b (f a c) include hf theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l | a b [] := rfl | a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl end foldl_eq_foldlr' section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### mfoldl, mfoldr, mmap -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl theorem mfoldr_eq_foldr (f : α → β → m β) (b l) : mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l := by induction l; simp * attribute [simp] mmap mmap' variables [is_lawful_monad m] theorem mfoldl_eq_foldl (f : β → α → m β) (b l) : mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l := begin suffices h : ∀ (mb : m β), (mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l, by simp [←h (pure b)], induction l; intro, { simp }, { simp only [mfoldl, foldl, ←l_ih] with monad_norm } end @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /-! ### prod and sum -/ -- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet. attribute [to_additive] list.prod section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive] theorem prod_nil : ([] : list α).prod = 1 := rfl @[to_additive] theorem prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, priority 500, to_additive] theorem prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { rw pow_zero, refl }, { rw [list.repeat_succ, list.prod_cons, ih, pow_succ] } end @[simp, to_additive] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] /-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial monoid with zero with no divisors, then this implication becomes an `iff`, see `list.prod_eq_zero_iff`. -/ theorem prod_eq_zero {M₀ : Type*} [monoid_with_zero M₀] {L : list M₀} (h : (0 : M₀) ∈ L) : L.prod = 0 := begin induction L with a L ihL, { exact absurd h (not_mem_nil _) }, { rw prod_cons, cases (mem_cons_iff _ _ _).1 h with ha hL, exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] } end /-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also `list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/ @[simp] theorem prod_eq_zero_iff {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} : L.prod = 0 ↔ (0 : M₀) ∈ L := begin induction L with a L ihL, { simp }, { rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] } end theorem prod_ne_zero {M₀ : Type*} [monoid_with_zero M₀] [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 := mt prod_eq_zero_iff.1 hL @[to_additive] theorem prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[to_additive] theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop} {f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] theorem prod_hom [monoid β] (l : list α) (f : α →* β) : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, f.map_one.symm], exact l.foldl_hom _ _ _ 1 f.map_mul } @[to_additive] lemma prod_is_unit [monoid β] : Π {L : list β} (u : ∀ m ∈ L, is_unit m), is_unit L.prod | [] _ := by simp | (h :: t) u := begin simp only [list.prod_cons], exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt))) end -- `to_additive` chokes on the next few lemmas, so we do them by hand below @[simp] lemma prod_take_mul_prod_drop : ∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], } @[simp] lemma prod_take_succ : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], } /-- A list with product not one must have positive length. -/ lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } lemma prod_update_nth : ∀ (L : list α) (n : ℕ) (a : α), (L.update_nth n a).prod = (L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod | (x::xs) 0 a := by simp [update_nth] | (x::xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc] | [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt] end monoid section group variables [group α] /-- This is the `list.prod` version of `mul_inv_rev` -/ @[to_additive "This is the `list.sum` version of `add_neg_rev`"] lemma prod_inv_reverse : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod | [] := by simp | (x :: xs) := by simp [prod_inv_reverse xs] /-- A non-commutative variant of `list.prod_reverse` -/ @[to_additive "A non-commutative variant of `list.sum_reverse`"] lemma prod_reverse_noncomm : ∀ (L : list α), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ := by simp [prod_inv_reverse] end group section comm_group variables [comm_group α] /-- This is the `list.prod` version of `mul_inv` -/ @[to_additive "This is the `list.sum` version of `add_neg`"] lemma prod_inv : ∀ (L : list α), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod | [] := by simp | (x :: xs) := by simp [mul_comm, prod_inv xs] end comm_group @[simp] lemma sum_take_add_sum_drop [add_monoid α] : ∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum | [] i := by simp | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], } @[simp] lemma sum_take_succ [add_monoid α] : ∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], } lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁), rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, exact add_left_cancel this end lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) : monotone (λ i, (L.take i).sum) := begin apply monotone_of_monotone_nat (λ n, _), by_cases h : n < L.length, { rw sum_take_succ _ _ h, exact le_self_add }, { push_neg at h, simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) : 1 ≤ l.prod := begin induction l with hd tl ih, { simp }, rw prod_cons, exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))), end @[to_additive] lemma single_le_prod [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) : ∀ x ∈ l, x ≤ l.prod := begin induction l, { simp }, simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁, split, { exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) }, { exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) }, end @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid α] {l : list α} (hl₁ : ∀ x ∈ l, (1 : α) ≤ x) (hl₂ : l.prod = 1) : ∀ x ∈ l, x = (1 : α) := λ x hx, le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx) lemma sum_eq_zero_iff [canonically_ordered_add_monoid α] (l : list α) : l.sum = 0 ↔ ∀ x ∈ l, x = (0 : α) := ⟨all_zero_of_le_zero_le_of_sum_eq_zero (λ _ _, zero_le _), begin induction l, { simp }, { intro h, rw [sum_cons, add_eq_zero_iff], rw forall_mem_cons at h, exact ⟨h.1, l_ih h.2⟩ }, end⟩ /-- A list with sum not zero must have positive length. -/ lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length := by { cases L, { simp at h, cases h, }, { simp, }, } /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- Now we tie those lemmas back to their multiplicative versions. attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one /-- A list with positive sum must have positive length. -/ -- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications. lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) : 0 < L.length := length_pos_of_sum_ne_zero L (ne_of_gt h) @[simp, to_additive] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases decidable.list.eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] lemma exists_lt_of_sum_lt [linear_ordered_cancel_add_comm_monoid β] {l : list α} (f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x := begin induction l with x l, { exfalso, exact lt_irrefl _ h }, { by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) } end lemma exists_le_of_sum_le [linear_ordered_cancel_add_comm_monoid β] {l : list α} (hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x := begin cases l with x l, { contradiction }, { by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩, rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩, exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h, exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) } end -- Several lemmas about sum/head/tail for `list ℕ`. -- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. -- We'd like to state this as `L.head * L.tail.prod = L.prod`, -- but because `L.head` relies on an inhabited instances and -- returns a garbage value for the empty list, this is not possible. -- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`, -- and below, restate the lemma just for `ℕ`. @[to_additive] lemma head_mul_tail_prod' [monoid α] (L : list α) : (L.nth 0).get_or_else 1 * L.tail.prod = L.prod := by { cases L, { simp, refl, }, { simp, }, } lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl, }, { simp, }, } lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel] section variables {G : Type*} [comm_group G] attribute [to_additive] alternating_prod @[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list G) = 1 := rfl @[simp, to_additive] lemma alternating_prod_singleton (g : G) : alternating_prod [g] = g := rfl @[simp, to_additive alternating_sum_cons_cons'] lemma alternating_prod_cons_cons (g h : G) (l : list G) : alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) : alternating_sum (g :: h :: l) = g - h + alternating_sum l := by rw [sub_eq_add_neg, alternating_sum] end /-! ### join -/ attribute [simp] join @[simp] theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] @[simp] theorem join_filter_empty_eq_ff [decidable_pred (λ l : list α, l.empty = ff)] : ∀ {L : list (list α)}, join (L.filter (λ l, l.empty = ff)) = L.join | [] := rfl | ([]::L) := by simp [@join_filter_empty_eq_ff L] | ((a::l)::L) := by simp [@join_filter_empty_eq_ff L] @[simp] theorem join_filter_ne_nil [decidable_pred (λ l : list α, l ≠ [])] {L : list (list α)} : join (L.filter (λ l, l ≠ [])) = L.join := by simp [join_filter_empty_eq_ff, ← empty_iff_eq_nil] lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join := by { induction l, simp, simp [l_ih] } /-- In a join, taking the first elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join of the first `i` sublists. -/ lemma take_sum_join (L : list (list α)) (i : ℕ) : L.join.take ((L.map length).take i).sum = (L.take i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [take_append, L_ih] end /-- In a join, dropping all the elements up to an index which is the sum of the lengths of the first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/ lemma drop_sum_join (L : list (list α)) (i : ℕ) : L.join.drop ((L.map length).take i).sum = (L.drop i).join := begin induction L generalizing i, { simp }, cases i, { simp }, simp [drop_append, L_ih], end /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) : (L.take (i+1)).drop i = [nth_le L i hi] := begin induction L generalizing i, { simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim }, cases i, { simp }, have : i < L_tl.length, { simp at hi, exact nat.lt_of_succ_lt_succ hi }, simp [L_ih this], refl end /-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and `B` is the sum of the lengths of sublists of index `≤ i`. -/ lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) : (L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi := begin have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take], simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi] end /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum := by simp [hi, sum_take_succ, hj] /-- Auxiliary lemma to control elements in a join. -/ lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : ((L.map length).take i).sum + j < L.join.length := begin convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi), have : L.length = (L.map length).length, by simp, simp [this, -length_map] end /-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist, where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists of index `< i`, and adding `j`. -/ lemma nth_le_join (L : list (list α)) {i j : ℕ} (hi : i < L.length) (hj : j < (nth_le L i hi).length) : nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) = nth_le (nth_le L i hi) j hj := by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj), nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)] /-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the sublists. -/ theorem eq_iff_join_eq (L L' : list (list α)) : L = L' ↔ L.join = L'.join ∧ map length L = map length L' := begin refine ⟨λ H, by simp [H], _⟩, rintros ⟨join_eq, length_eq⟩, apply ext_le, { have : length (map length L) = length (map length L'), by rw length_eq, simpa using this }, { assume n h₁ h₂, rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] } end /-! ### lexicographic ordering -/ /-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which `[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`. The definition is given for any relation `r`, not only strict orders. -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ @[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l []. instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem _root_.decidable.list.lex.ne_iff [decidable_eq α] {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { by_cases ab : a = b, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := by classical; exact decidable.list.lex.ne_iff H end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ /-! ### all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /-! ### map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) : sizeof x < sizeof l := begin induction l with h t ih; cases hx, { rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) }, { exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) } end theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_map {p : β → Prop} (g : ∀ b, p b → γ) (f : α → β) (l H) : pmap g (map f l) H = pmap (λ a h, g (f a) h) l (λ a h, H _ (mem_map_of_mem _ h)) := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap @[simp] lemma pmap_eq_nil {p : α → Prop} {f : Π a, p a → β} {l H} : pmap f l H = [] ↔ l = [] := by rw [← length_eq_zero, length_pmap, length_eq_zero] @[simp] lemma attach_eq_nil (l : list α) : l.attach = [] ↔ l = [] := pmap_eq_nil lemma last_pmap {α β : Type*} (p : α → Prop) (f : Π a, p a → β) (l : list α) (hl₁ : ∀ a ∈ l, p a) (hl₂ : l ≠ []) : (l.pmap f hl₁).last (mt list.pmap_eq_nil.1 hl₂) = f (l.last hl₂) (hl₁ _ (list.last_mem hl₂)) := begin induction l with l_hd l_tl l_ih, { apply (hl₂ rfl).elim }, { cases l_tl, { simp }, { apply l_ih } } end lemma nth_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) (n : ℕ) : nth (pmap f l h) n = option.pmap f (nth l n) (λ x H, h x (nth_mem H)) := begin induction l with hd tl hl generalizing n, { simp }, { cases n; simp [hl] } end lemma nth_le_pmap {p : α → Prop} (f : Π a, p a → β) {l : list α} (h : ∀ a ∈ l, p a) {n : ℕ} (hn : n < (pmap f l h).length) : nth_le (pmap f l h) n hn = f (nth_le l n (@length_pmap _ _ p f l h ▸ hn)) (h _ (nth_le_mem l n (@length_pmap _ _ p f l h ▸ hn))) := begin induction l with hd tl hl generalizing n, { simp only [length, pmap] at hn, exact absurd hn (not_lt_of_le n.zero_le) }, { cases n, { simp }, { simpa [hl] } } end /-! ### find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /-! ### lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /-! ### filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl lemma filter_map_append {α β : Type*} (l l' : list α) (f : α → option β) : filter_map f (l ++ l') = filter_map f l ++ filter_map f l' := begin induction l with hd tl hl generalizing l', { simp }, { rw [cons_append, filter_map, filter_map], cases f hd; simp only [filter_map, hl, cons_append, eq_self_iff_true, and_self] } end theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem sublist.map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := filter_map_eq_map f ▸ s.filter_map _ /-! ### reduce_option -/ @[simp] lemma reduce_option_cons_of_some (x : α) (l : list (option α)) : reduce_option (some x :: l) = x :: l.reduce_option := by simp only [reduce_option, filter_map, id.def, eq_self_iff_true, and_self] @[simp] lemma reduce_option_cons_of_none (l : list (option α)) : reduce_option (none :: l) = l.reduce_option := by simp only [reduce_option, filter_map, id.def] @[simp] lemma reduce_option_nil : @reduce_option α [] = [] := rfl @[simp] lemma reduce_option_map {l : list (option α)} {f : α → β} : reduce_option (map (option.map f) l) = map f (reduce_option l) := begin induction l with hd tl hl, { simp only [reduce_option_nil, map_nil] }, { cases hd; simpa only [true_and, option.map_some', map, eq_self_iff_true, reduce_option_cons_of_some] using hl }, end lemma reduce_option_append (l l' : list (option α)) : (l ++ l').reduce_option = l.reduce_option ++ l'.reduce_option := filter_map_append l l' id lemma reduce_option_length_le (l : list (option α)) : l.reduce_option.length ≤ l.length := begin induction l with hd tl hl, { simp only [reduce_option_nil, length] }, { cases hd, { exact nat.le_succ_of_le hl }, { simpa only [length, add_le_add_iff_right, reduce_option_cons_of_some] using hl} } end lemma reduce_option_length_eq_iff {l : list (option α)} : l.reduce_option.length = l.length ↔ ∀ x ∈ l, option.is_some x := begin induction l with hd tl hl, { simp only [forall_const, reduce_option_nil, not_mem_nil, forall_prop_of_false, eq_self_iff_true, length, not_false_iff] }, { cases hd, { simp only [mem_cons_iff, forall_eq_or_imp, bool.coe_sort_ff, false_and, reduce_option_cons_of_none, length, option.is_some_none, iff_false], intro H, have := reduce_option_length_le tl, rw H at this, exact absurd (nat.lt_succ_self _) (not_lt_of_le this) }, { simp only [hl, true_and, mem_cons_iff, forall_eq_or_imp, add_left_inj, bool.coe_sort_tt, length, option.is_some_some, reduce_option_cons_of_some] } } end lemma reduce_option_length_lt_iff {l : list (option α)} : l.reduce_option.length < l.length ↔ none ∈ l := begin rw [(reduce_option_length_le l).lt_iff_ne, ne, reduce_option_length_eq_iff], induction l; simp *, rw [eq_comm, ← option.not_is_some_iff_eq_none, decidable.imp_iff_not_or] end lemma reduce_option_singleton (x : option α) : [x].reduce_option = x.to_list := by cases x; refl lemma reduce_option_concat (l : list (option α)) (x : option α) : (l.concat x).reduce_option = l.reduce_option ++ x.to_list := begin induction l with hd tl hl generalizing x, { cases x; simp [option.to_list] }, { simp only [concat_eq_append, reduce_option_append] at hl, cases hd; simp [hl, reduce_option_append] } end lemma reduce_option_concat_of_some (l : list (option α)) (x : α) : (l.concat (some x)).reduce_option = l.reduce_option.concat x := by simp only [reduce_option_nil, concat_eq_append, reduce_option_append, reduce_option_cons_of_some] lemma reduce_option_mem_iff {l : list (option α)} {x : α} : x ∈ l.reduce_option ↔ (some x) ∈ l := by simp only [reduce_option, id.def, mem_filter_map, exists_eq_right] lemma reduce_option_nth_iff {l : list (option α)} {x : α} : (∃ i, l.nth i = some (some x)) ↔ ∃ i, l.reduce_option.nth i = some x := by rw [←mem_iff_nth, ←mem_iff_nth, reduce_option_mem_iff] /-! ### filter -/ section filter variables {p : α → Prop} [decidable_pred p] theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) : filter p l = foldr (λ a out, if p a then a :: out else out) [] l := by induction l; simp [*, filter] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := (filter_sublist l).subset theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, 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 only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] variable (p) theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ theorem map_filter (f : β → α) (l : list β) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter (q) [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) : @filter α (λ _, true) h l = l := by convert filter_eq_self.2 (λ _ _, trivial) @[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) : @filter α (λ _, false) h l = [] := by convert filter_eq_nil.2 (λ _ _, id) @[simp] theorem span_eq_take_drop : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter p s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /-! ### count -/ section count variable [decidable_eq α] @[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) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length), l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0 | (_ :: _) a h := by { rw [count_cons], split_ifs; simp } theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist _ theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append _ theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := decidable.by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) : repeat a (count a l) = l := eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l))) (eq.trans (length_repeat a (count a l)) h) @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /-! ### prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by rw ← list.append_assoc; apply infix_append theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s @[simp] theorem eq_nil_iff_infix_nil {l : list α} : l <:+: [] ↔ l = [] := ⟨eq_nil_of_infix_nil, λ h, h ▸ infix_refl _⟩ theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s @[simp] theorem eq_nil_iff_prefix_nil {l : list α} : l <+: [] ↔ l = [] := ⟨eq_nil_of_prefix_nil, λ h, h ▸ prefix_refl _⟩ theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s @[simp] theorem eq_nil_iff_suffix_nil {l : list α} : l <:+ [] ↔ l = [] := ⟨eq_nil_of_suffix_nil, λ h, h ▸ suffix_refl _⟩ theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem suffix_cons_iff {x : α} {l₁ l₂ : list α} : l₁ <:+ x :: l₂ ↔ l₁ = x :: l₂ ∨ l₁ <:+ l₂ := begin split, { rintro ⟨⟨hd, tl⟩, hl₃⟩, { exact or.inl hl₃ }, { simp only [cons_append] at hl₃, exact or.inr ⟨_, hl₃.2⟩ } }, { rintro (rfl | hl₁), { exact (x :: l₂).suffix_refl }, { exact hl₁.trans (l₂.suffix_cons _) } } end theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_right_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_right_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix lemma tail_sublist (l : list α) : l.tail <+ l := sublist_of_suffix (tail_suffix l) theorem tail_subset (l : list α) : tail l ⊆ l := (tail_sublist l).subset theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ 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_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- 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 $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h lemma prefix_take_le_iff {L : list (list (option α))} {m n : ℕ} (hm : m < L.length) : (take m L) <+: (take n L) ↔ m ≤ n := begin simp only [prefix_iff_eq_take, length_take], induction m with m IH generalizing L n, { simp only [min_eq_left, eq_self_iff_true, nat.zero_le, take] }, { cases n, { simp only [nat.nat_zero_eq_zero, nonpos_iff_eq_zero, take, take_nil], split, { cases L, { exact absurd hm (not_lt_of_le m.succ.zero_le) }, { simp only [forall_prop_of_false, not_false_iff, take] } }, { intro h, contradiction } }, { cases L with l ls, { exact absurd hm (not_lt_of_le m.succ.zero_le) }, { simp only [length] at hm, specialize @IH ls n (nat.lt_of_succ_lt_succ hm), simp only [le_of_lt (nat.lt_of_succ_lt_succ hm), min_eq_left] at IH, simp only [le_of_lt hm, IH, true_and, min_eq_left, eq_self_iff_true, length, take], exact ⟨nat.succ_le_succ, nat.le_of_succ_le_succ⟩ } } }, end lemma cons_prefix_iff {l l' : list α} {x y : α} : x :: l <+: y :: l' ↔ x = y ∧ l <+: l' := begin split, { rintro ⟨L, hL⟩, simp only [cons_append] at hL, exact ⟨hL.left, ⟨L, hL.right⟩⟩ }, { rintro ⟨rfl, h⟩, rwa [prefix_cons_inj] }, end lemma map_prefix {l l' : list α} (f : α → β) (h : l <+: l') : l.map f <+: l'.map f := begin induction l with hd tl hl generalizing l', { simp only [nil_prefix, map_nil] }, { cases l' with hd' tl', { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, simp only [h, prefix_cons_inj, hl, map] } }, end lemma is_prefix.filter_map {l l' : list α} (h : l <+: l') (f : α → option β) : l.filter_map f <+: l'.filter_map f := begin induction l with hd tl hl generalizing l', { simp only [nil_prefix, filter_map_nil] }, { cases l' with hd' tl', { simpa only using eq_nil_of_prefix_nil h }, { rw cons_prefix_iff at h, rw [←@singleton_append _ hd _, ←@singleton_append _ hd' _, filter_map_append, filter_map_append, h.left, prefix_append_right_inj], exact hl h.right } }, end lemma is_prefix.reduce_option {l l' : list (option α)} (h : l <+: l') : l.reduce_option <+: l'.reduce_option := h.filter_map id @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ lemma inits_cons (a : α) (l : list α) : inits (a :: l) = [] :: l.inits.map (λ t, a :: t) := by simp lemma tails_cons (a : α) (l : list α) : tails (a :: l) = (a :: l) :: l.tails := by simp @[simp] lemma inits_append : ∀ (s t : list α), inits (s ++ t) = s.inits ++ t.inits.tail.map (λ l, s ++ l) | [] [] := by simp | [] (a::t) := by simp | (a::s) t := by simp [inits_append s t] @[simp] lemma tails_append : ∀ (s t : list α), tails (s ++ t) = s.tails.map (λ l, l ++ t) ++ t.tails.tail | [] [] := by simp | [] (a::t) := by simp | (a::s) t := by simp [tails_append s t] -- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'` lemma inits_eq_tails : ∀ (l : list α), l.inits = (reverse $ map reverse $ tails $ reverse l) | [] := by simp | (a :: l) := by simp [inits_eq_tails l, map_eq_map_iff] lemma tails_eq_inits : ∀ (l : list α), l.tails = (reverse $ map reverse $ inits $ reverse l) | [] := by simp | (a :: l) := by simp [tails_eq_inits l, append_left_inj] lemma inits_reverse (l : list α) : inits (reverse l) = reverse (map reverse l.tails) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], } lemma tails_reverse (l : list α) : tails (reverse l) = reverse (map reverse l.inits) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], } lemma map_reverse_inits (l : list α) : map reverse l.inits = (reverse $ tails $ reverse l) := by { rw inits_eq_tails l, simp [reverse_involutive.comp_self], } lemma map_reverse_tails (l : list α) : map reverse l.tails = (reverse $ inits $ reverse l) := by { rw tails_eq_inits l, simp [reverse_involutive.comp_self], } 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⟩⟩ /-! ### permutations -/ section permutations theorem permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β), (permutations_aux2 t ts r ys f).1 = ys ++ ts | [] f := rfl | (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with | ⟨_, zs⟩, rfl := rfl end @[simp] theorem permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) : (permutations_aux2 t ts r [] f).2 = r := rfl @[simp] theorem permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) :: (permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 := match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts → (permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with | ⟨_, zs⟩, rfl := rfl end /-- The `r` argument to `permutations_aux2` is the same as appending. -/ theorem permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 := by induction ys generalizing f; simp * /-- The `ts` argument to `permutations_aux2` can be folded into the `f` argument. -/ theorem permutations_aux2_comp_append {t : α} {ts ys : list α} {r : list β} (f : list α → β) : (permutations_aux2 t [] r ys $ λ x, f (x ++ ts)).2 = (permutations_aux2 t ts r ys f).2 := begin induction ys generalizing f, { simp }, { simp [ys_ih (λ xs, f (ys_hd :: xs))] }, end theorem map_permutations_aux2' {α β α' β'} (g : α → α') (g' : β → β') (t : α) (ts ys : list α) (r : list β) (f : list α → β) (f' : list α' → β') (H : ∀ a, g' (f a) = f' (map g a)) : map g' (permutations_aux2 t ts r ys f).2 = (permutations_aux2 (g t) (map g ts) (map g' r) (map g ys) f').2 := begin induction ys generalizing f f'; simp *, apply ys_ih, simp [H], end /-- The `f` argument to `permutations_aux2` when `r = []` can be eliminated. -/ theorem map_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : (permutations_aux2 t ts [] ys id).2.map f = (permutations_aux2 t ts [] ys f).2 := begin convert map_permutations_aux2' id _ _ _ _ _ _ _ _; simp only [map_id, id.def], exact (λ _, rfl) end /-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from `permutations_aux2`. `(permutations_aux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are produced by inserting `t` into every non-terminal position of `ys` in order. As an example: ```lean #eval permutations_aux2 1 [] [] [2, 3, 4] id -- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]] ``` -/ lemma permutations_aux2_snd_eq (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) : (permutations_aux2 t ts r ys f).2 = (permutations_aux2 t [] [] ys id).2.map (λ x, f (x ++ ts)) ++ r := by rw [←permutations_aux2_append, map_permutations_aux2, permutations_aux2_comp_append] theorem map_map_permutations_aux2 {α α'} (g : α → α') (t : α) (ts ys : list α) : map (map g) (permutations_aux2 t ts [] ys id).2 = (permutations_aux2 (g t) (map g ts) [] (map g ys) id).2 := map_permutations_aux2' _ _ _ _ _ _ _ _ (λ _, rfl) theorem mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} : l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts := begin induction ys with y ys ih generalizing l, { simp {contextual := tt} }, { rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]), by funext; simp, mem_cons_iff, ih], split; intro h, { rcases h with e | ⟨l₁, l₂, l0, ye, _⟩, { subst l', exact ⟨[], y::ys, by simp⟩ }, { substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } }, { rcases h with ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩, { simp [ye] }, { simp at ye, rcases ye with ⟨rfl, rfl⟩, exact or.inr ⟨l₁, l₂, l0, by simp⟩ } } } end theorem mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} : l ∈ (permutations_aux2 t ts [] ys id).2 ↔ ∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts := by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2 theorem length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) : length (permutations_aux2 t ts [] ys f).2 = length ys := by induction ys generalizing f; simp * theorem foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : foldr (λy r, (permutations_aux2 t ts r y id).2) r L = L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r := by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}] theorem mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} : l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔ l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts := have (∃ (a : list α), a ∈ L ∧ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔ ∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts), from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩, λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩, by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this, or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc] theorem length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r := by simp [foldr_permutations_aux2, (∘), length_permutations_aux2] theorem length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α)) (n) (H : ∀ l ∈ L, length l = n) : length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r := begin rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)], induction L with l L ih, {simp}, have sum_map : sum (map length L) = n * length L := ih (λ l m, H l (mem_cons_of_mem _ m)), have length_l : length l = n := H _ (mem_cons_self _ _), simp [sum_map, length_l, mul_add, add_comm] end @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl theorem map_permutations_aux (f : α → β) : ∀ (ts is : list α), map (map f) (permutations_aux ts is) = permutations_aux (map f ts) (map f is) := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2, rw map at IH2, simp only [foldr_permutations_aux2, map_append, map, map_map_permutations_aux2, permutations, bind_map, IH1, append_assoc, permutations_aux_cons, cons_bind, ← IH2, map_bind], end theorem map_permutations (f : α → β) (ts : list α) : map (map f) (permutations ts) = permutations (map f ts) := by rw [permutations, permutations, map, map_permutations_aux, map] end permutations /-! ### insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp, priority 980] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp, priority 970] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /-! ### erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := (erasep_sublist l).subset theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /-! ### erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp, priority 980] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := (erase_sublist a l).subset theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact sublist.erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] @[simp] theorem count_erase_self (a : α) : ∀ (s : list α), count a (list.erase s a) = pred (count a s) | [] := by simp | (h :: t) := begin rw erase_cons, by_cases p : h = a, { rw [if_pos p, count_cons', if_pos p.symm], simp }, { rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self], simp, } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) : ∀ (s : list α), count a (list.erase s b) = count a s | [] := by simp | (x :: xs) := begin rw erase_cons, split_ifs with h, { rw [count_cons', h, if_neg ab], simp }, { rw [count_cons', count_cons', count_erase_of_ne] } end end erase /-! ### diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] lemma diff_cons_right (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.diff l₂).erase a := begin induction l₂ with b l₂ ih generalizing l₁ a, { simp_rw [diff_cons, diff_nil] }, { rw [diff_cons, diff_cons, erase_comm, ← diff_cons, ih, ← diff_cons] } end lemma diff_erase (l₁ l₂ : list α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ := by rw [← diff_cons_right, diff_cons] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist _ _).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, (h.erase _).diff_right] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (h.erase b) end diff /-! ### enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ theorem mem_enum_from {x : α} {i : ℕ} : ∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs | j [] := by simp [enum_from] | j (y :: ys) := suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys → j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys), by simpa [enum_from, mem_enum_from ys], begin rintro (h|h), { refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩, apply nat.lt_add_of_pos_right; simp }, { obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h, refine ⟨_, _, _⟩, { exact le_trans (nat.le_succ _) hji }, { convert hijlen using 1, ac_refl }, { simp [hmem] } } end /-! ### product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /-! ### sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /-! ### disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] := by rw disjoint_comm; exact disjoint_nil_left _ @[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) : disjoint (l.take m) (l.drop n) := begin induction l generalizing m n, case list.nil : m n { simp }, case list.cons : x xs xs_ih m n { cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop, true_or, eq_self_iff_true, not_true, false_and, disjoint_nil_left, take], { cases h }, cases hl with _ _ h₀ h₁, split, { intro h, exact h₀ _ (mem_of_mem_drop h) rfl, }, solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } }, end end disjoint /-! ### union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /-! ### inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h @[simp] lemma inter_reverse {xs ys : list α} : xs.inter ys.reverse = xs.inter ys := by simp only [list.inter, mem_reverse]; congr end inter section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose /-! ### map₂_left' -/ section map₂_left' -- The definitional equalities for `map₂_left'` can already be used by the -- simplifie because `map₂_left'` is marked `@[simp]`. @[simp] theorem map₂_left'_nil_right (f : α → option β → γ) (as) : map₂_left' f as [] = (as.map (λ a, f a none), []) := by cases as; refl end map₂_left' /-! ### map₂_right' -/ section map₂_right' variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right'_nil_left : map₂_right' f [] bs = (bs.map (f none), []) := by cases bs; refl @[simp] theorem map₂_right'_nil_right : map₂_right' f as [] = ([], as) := rfl @[simp] theorem map₂_right'_nil_cons : map₂_right' f [] (b :: bs) = (f none b :: bs.map (f none), []) := rfl @[simp] theorem map₂_right'_cons_cons : map₂_right' f (a :: as) (b :: bs) = let rec := map₂_right' f as bs in (f (some a) b :: rec.fst, rec.snd) := rfl end map₂_right' /-! ### zip_left' -/ section zip_left' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left'_nil_right : zip_left' as ([] : list β) = (as.map (λ a, (a, none)), []) := by cases as; refl @[simp] theorem zip_left'_nil_left : zip_left' ([] : list α) bs = ([], bs) := rfl @[simp] theorem zip_left'_cons_nil : zip_left' (a :: as) ([] : list β) = ((a, none) :: as.map (λ a, (a, none)), []) := rfl @[simp] theorem zip_left'_cons_cons : zip_left' (a :: as) (b :: bs) = let rec := zip_left' as bs in ((a, some b) :: rec.fst, rec.snd) := rfl end zip_left' /-! ### zip_right' -/ section zip_right' variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right'_nil_left : zip_right' ([] : list α) bs = (bs.map (λ b, (none, b)), []) := by cases bs; refl @[simp] theorem zip_right'_nil_right : zip_right' as ([] : list β) = ([], as) := rfl @[simp] theorem zip_right'_nil_cons : zip_right' ([] : list α) (b :: bs) = ((none, b) :: bs.map (λ b, (none, b)), []) := rfl @[simp] theorem zip_right'_cons_cons : zip_right' (a :: as) (b :: bs) = let rec := zip_right' as bs in ((some a, b) :: rec.fst, rec.snd) := rfl end zip_right' /-! ### map₂_left -/ section map₂_left variables (f : α → option β → γ) (as : list α) -- The definitional equalities for `map₂_left` can already be used by the -- simplifier because `map₂_left` is marked `@[simp]`. @[simp] theorem map₂_left_nil_right : map₂_left f as [] = as.map (λ a, f a none) := by cases as; refl theorem map₂_left_eq_map₂_left' : ∀ as bs, map₂_left f as bs = (map₂_left' f as bs).fst | [] bs := by simp! | (a :: as) [] := by simp! | (a :: as) (b :: bs) := by simp! [*] theorem map₂_left_eq_map₂ : ∀ as bs, length as ≤ length bs → map₂_left f as bs = map₂ (λ a b, f a (some b)) as bs | [] [] h := by simp! | [] (b :: bs) h := by simp! | (a :: as) [] h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! [*] } end map₂_left /-! ### map₂_right -/ section map₂_right variables (f : option α → β → γ) (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem map₂_right_nil_left : map₂_right f [] bs = bs.map (f none) := by cases bs; refl @[simp] theorem map₂_right_nil_right : map₂_right f as [] = [] := rfl @[simp] theorem map₂_right_nil_cons : map₂_right f [] (b :: bs) = f none b :: bs.map (f none) := rfl @[simp] theorem map₂_right_cons_cons : map₂_right f (a :: as) (b :: bs) = f (some a) b :: map₂_right f as bs := rfl theorem map₂_right_eq_map₂_right' : map₂_right f as bs = (map₂_right' f as bs).fst := by simp only [map₂_right, map₂_right', map₂_left_eq_map₂_left'] theorem map₂_right_eq_map₂ (h : length bs ≤ length as) : map₂_right f as bs = map₂ (λ a b, f (some a) b) as bs := begin have : (λ a b, flip f a (some b)) = (flip (λ a b, f (some a) b)) := rfl, simp only [map₂_right, map₂_left_eq_map₂, map₂_flip, *] end end map₂_right /-! ### zip_left -/ section zip_left variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_left_nil_right : zip_left as ([] : list β) = as.map (λ a, (a, none)) := by cases as; refl @[simp] theorem zip_left_nil_left : zip_left ([] : list α) bs = [] := rfl @[simp] theorem zip_left_cons_nil : zip_left (a :: as) ([] : list β) = (a, none) :: as.map (λ a, (a, none)) := rfl @[simp] theorem zip_left_cons_cons : zip_left (a :: as) (b :: bs) = (a, some b) :: zip_left as bs := rfl theorem zip_left_eq_zip_left' : zip_left as bs = (zip_left' as bs).fst := by simp only [zip_left, zip_left', map₂_left_eq_map₂_left'] end zip_left /-! ### zip_right -/ section zip_right variables (a : α) (as : list α) (b : β) (bs : list β) @[simp] theorem zip_right_nil_left : zip_right ([] : list α) bs = bs.map (λ b, (none, b)) := by cases bs; refl @[simp] theorem zip_right_nil_right : zip_right as ([] : list β) = [] := rfl @[simp] theorem zip_right_nil_cons : zip_right ([] : list α) (b :: bs) = (none, b) :: bs.map (λ b, (none, b)) := rfl @[simp] theorem zip_right_cons_cons : zip_right (a :: as) (b :: bs) = (some a, b) :: zip_right as bs := rfl theorem zip_right_eq_zip_right' : zip_right as bs = (zip_right' as bs).fst := by simp only [zip_right, zip_right', map₂_right_eq_map₂_right'] end zip_right /-! ### to_chunks -/ section to_chunks @[simp] theorem to_chunks_nil (n) : @to_chunks α n [] = [] := by cases n; refl theorem to_chunks_aux_eq (n) : ∀ xs i, @to_chunks_aux α n xs i = (xs.take i, (xs.drop i).to_chunks (n+1)) | [] i := by cases i; refl | (x::xs) 0 := by rw [to_chunks_aux, drop, to_chunks]; cases to_chunks_aux n xs n; refl | (x::xs) (i+1) := by rw [to_chunks_aux, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons' (n) : ∀ {xs : list α} (h : xs ≠ []), xs.to_chunks (n+1) = xs.take (n+1) :: (xs.drop (n+1)).to_chunks (n+1) | [] e := (e rfl).elim | (x::xs) _ := by rw [to_chunks, to_chunks_aux_eq]; refl theorem to_chunks_eq_cons : ∀ {n} {xs : list α} (n0 : n ≠ 0) (x0 : xs ≠ []), xs.to_chunks n = xs.take n :: (xs.drop n).to_chunks n | 0 _ e := (e rfl).elim | (n+1) xs _ := to_chunks_eq_cons' _ theorem to_chunks_aux_join {n} : ∀ {xs i l L}, @to_chunks_aux α n xs i = (l, L) → l ++ L.join = xs | [] _ _ _ rfl := rfl | (x::xs) i l L e := begin cases i; [ cases e' : to_chunks_aux n xs n with l L, cases e' : to_chunks_aux n xs i with l L]; { rw [to_chunks_aux, e', to_chunks_aux] at e, cases e, exact (congr_arg (cons x) (to_chunks_aux_join e') : _) } end @[simp] theorem to_chunks_join : ∀ n xs, (@to_chunks α n xs).join = xs | n [] := by cases n; refl | 0 (x::xs) := by simp only [to_chunks, join]; rw append_nil | (n+1) (x::xs) := begin rw to_chunks, cases e : to_chunks_aux n xs n with l L, exact (congr_arg (cons x) (to_chunks_aux_join e) : _), end theorem to_chunks_length_le : ∀ n xs, n ≠ 0 → ∀ l : list α, l ∈ @to_chunks α n xs → l.length ≤ n | 0 _ e _ := (e rfl).elim | (n+1) xs _ l := begin refine (measure_wf length).induction xs _, intros xs IH h, by_cases x0 : xs = [], {subst xs, cases h}, rw to_chunks_eq_cons' _ x0 at h, rcases h with rfl|h, { apply length_take_le }, { refine IH _ _ h, simp only [measure, inv_image, length_drop], exact nat.sub_lt_self (length_pos_iff_ne_nil.2 x0) (succ_pos _) }, end end to_chunks /-! ### Miscellaneous lemmas -/ theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (ilast'_mem b l) @[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val end list @[to_additive] theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) : f l.prod = (l.map f).prod := (l.prod_hom f).symm namespace list @[to_additive] theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm} theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β) (f : β → α) (r : α) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r universes u v @[simp] theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) : (y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs := begin induction xs with x xs, { simp only [not_mem_nil, map_nil] }, { cases x with a b, simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih, and_comm] }, end lemma slice_eq {α} (xs : list α) (n m : ℕ) : slice n m xs = xs.take n ++ xs.drop (n+m) := begin induction n generalizing xs, { simp [slice] }, { cases xs; simp [slice, *, nat.succ_add], } end lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) : sizeof (list.slice i j xs) < sizeof xs := begin induction xs generalizing i j, case list.nil : i j h { cases hi }, case list.cons : x xs xs_ih i j h { cases i; simp only [-slice_eq, list.slice], { cases j, cases h, dsimp only [drop], unfold_wf, apply @lt_of_le_of_lt _ _ _ xs.sizeof, { clear_except, induction xs generalizing j; unfold_wf, case list.nil : j { refl }, case list.cons : xs_hd xs_tl xs_ih j { cases j; unfold_wf, refl, transitivity, apply xs_ih, simp }, }, unfold_wf, apply zero_lt_one_add, }, { unfold_wf, apply xs_ih _ _ h, apply lt_of_succ_lt_succ hi, } }, end end list
46ce8d60b0ebe5db484a4c23a40f2212673b46f5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/gen.lean
33f4e3715347726fc3870fcb10917f465a476384
[ "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
241
lean
def main (xs : List String) : IO UInt32 := let n := xs.head.toNat in IO.println "prelude\ninductive Bool : Type\n| ff : Bool\n| tt : Bool\n\n" *> Nat.mrepeat n (λ i, IO.println ("theorem x" ++ toString i ++ " : Bool := Bool.tt")) *> pure 0
5969beab82fe71f377186a67e76bde616578388e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/int/dvd/basic.lean
2905eb1a1494e651784361dc160076d3d2cd807f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,636
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.int.order.basic import data.nat.cast.basic /-! # Basic lemmas about the divisibility relation in `ℤ`. -/ open nat namespace int @[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_right ℤ _ 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 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' 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 end int
ea41ba1df2041df84658673b8cf7ef652f2bc092
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/meta_env1.lean
c1ed2743a2e8d1cb12cc07c2a2ca9e85f573446c
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,053
lean
open list meta definition e := environment.mk_std 0 definition hints := reducibility_hints.regular 10 tt #eval environment.trust_lvl e #eval (environment.add e (declaration.defn `foo [] (expr.sort (level.succ (level.zero))) (expr.sort (level.succ (level.zero))) hints tt) : exceptional environment) meta definition e1 := (environment.add e (declaration.defn `foo [] (expr.sort (level.succ (level.zero))) (expr.sort level.zero) hints tt) : exceptional environment) #print "-----------" open name #eval do e₁ ← environment.add e (declaration.defn `foo [] (expr.sort (level.succ (level.zero))) (expr.sort level.zero) hints tt), e₂ ← environment.add_inductive e₁ `Two [] 0 (expr.sort (level.succ level.zero)) [(`Zero, expr.const `Two []), (`One, expr.const `Two [])] tt, d₁ ← environment.get e₂ `Zero, d₂ ← environment.get e₂ `foo, /- TODO(leo): use return (declaration.type d) We currently don't use 'return' because the type is too high-order. return : ∀ {m : Type → Type} [monad m] {A : Type}, A → m A It is the kind of example where we should fallback to first-order unification for inferring the (m : Type → Type) The new elaborator should be able to handle it. -/ exceptional.success (declaration.type d₁, declaration.type d₂, environment.is_recursor e₂ `Two.rec, environment.constructors_of e₂ `Two, environment.fold e₂ (to_format "") (λ d r, r ++ format.line ++ to_fmt (declaration.to_name d)))
dbb5b105f261e52ef95535cd2c67ad022f5a7c62
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/uniform_space/compact_convergence.lean
357eee4ebcf10a620a03fe37a26af688f487563b
[ "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
22,082
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import topology.compact_open import topology.uniform_space.uniform_convergence /-! # Compact convergence (uniform convergence on compact sets) Given a topological space `α` and a uniform space `β` (e.g., a metric space or a topological group), the space of continuous maps `C(α, β)` carries a natural uniform space structure. We define this uniform space structure in this file and also prove the following properties of the topology it induces on `C(α, β)`: 1. Given a sequence of continuous functions `Fₙ : α → β` together with some continuous `f : α → β`, then `Fₙ` converges to `f` as a sequence in `C(α, β)` iff `Fₙ` converges to `f` uniformly on each compact subset `K` of `α`. 2. Given `Fₙ` and `f` as above and suppose `α` is locally compact, then `Fₙ` converges to `f` iff `Fₙ` converges to `f` locally uniformly. 3. The topology coincides with the compact-open topology. Property 1 is essentially true by definition, 2 follows from basic results about uniform convergence, but 3 requires a little work and uses the Lebesgue number lemma. ## The uniform space structure Given subsets `K ⊆ α` and `V ⊆ β × β`, let `E(K, V) ⊆ C(α, β) × C(α, β)` be the set of pairs of continuous functions `α → β` which are `V`-close on `K`: $$ E(K, V) = \{ (f, g) | ∀ (x ∈ K), (f x, g x) ∈ V \}. $$ Fixing some `f ∈ C(α, β)`, let `N(K, V, f) ⊆ C(α, β)` be the set of continuous functions `α → β` which are `V`-close to `f` on `K`: $$ N(K, V, f) = \{ g | ∀ (x ∈ K), (f x, g x) ∈ V \}. $$ Using this notation we can describe the uniform space structure and the topology it induces. Specifically: * A subset `X ⊆ C(α, β) × C(α, β)` is an entourage for the uniform space structure on `C(α, β)` iff there exists a compact `K` and entourage `V` such that `E(K, V) ⊆ X`. * A subset `Y ⊆ C(α, β)` is a neighbourhood of `f` iff there exists a compact `K` and entourage `V` such that `N(K, V, f) ⊆ Y`. The topology on `C(α, β)` thus has a natural subbasis (the compact-open subbasis) and a natural neighbourhood basis (the compact-convergence neighbourhood basis). ## Main definitions / results * `compact_open_eq_compact_convergence`: the compact-open topology is equal to the compact-convergence topology. * `compact_convergence_uniform_space`: the uniform space structure on `C(α, β)`. * `mem_compact_convergence_entourage_iff`: a characterisation of the entourages of `C(α, β)`. * `tendsto_iff_forall_compact_tendsto_uniformly_on`: a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` uniformly on each compact subset `K` of `α`. * `tendsto_iff_tendsto_locally_uniformly`: on a locally compact space, a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` locally uniformly. * `tendsto_iff_tendsto_uniformly`: on a compact space, a sequence of functions `Fₙ` in `C(α, β)` converges to some `f` iff `Fₙ` converges to `f` uniformly. ## Implementation details We use the forgetful inheritance pattern (see Note [forgetful inheritance]) to make the topology of the uniform space structure on `C(α, β)` definitionally equal to the compact-open topology. ## TODO * When `β` is a metric space, there is natural basis for the compact-convergence topology parameterised by triples `(K, ε, f)` for a real number `ε > 0`. * When `α` is compact and `β` is a metric space, the compact-convergence topology (and thus also the compact-open topology) is metrisable. * Results about uniformly continuous functions `γ → C(α, β)` and uniform limits of sequences `ι → γ → C(α, β)`. -/ universes u₁ u₂ u₃ open_locale filter uniformity topological_space open uniform_space set filter variables {α : Type u₁} {β : Type u₂} [topological_space α] [uniform_space β] variables (K : set α) (V : set (β × β)) (f : C(α, β)) namespace continuous_map /-- Given `K ⊆ α`, `V ⊆ β × β`, and `f : C(α, β)`, we define `compact_conv_nhd K V f` to be the set of `g : C(α, β)` that are `V`-close to `f` on `K`. -/ def compact_conv_nhd : set C(α, β) := { g | ∀ (x ∈ K), (f x, g x) ∈ V } variables {K V} lemma self_mem_compact_conv_nhd (hV : V ∈ 𝓤 β) : f ∈ compact_conv_nhd K V f := λ x hx, refl_mem_uniformity hV @[mono] lemma compact_conv_nhd_mono {V' : set (β × β)} (hV' : V' ⊆ V) : compact_conv_nhd K V' f ⊆ compact_conv_nhd K V f := λ x hx a ha, hV' (hx a ha) lemma compact_conv_nhd_mem_comp {g₁ g₂ : C(α, β)} {V' : set (β × β)} (hg₁ : g₁ ∈ compact_conv_nhd K V f) (hg₂ : g₂ ∈ compact_conv_nhd K V' g₁) : g₂ ∈ compact_conv_nhd K (V ○ V') f := λ x hx, ⟨g₁ x, hg₁ x hx, hg₂ x hx⟩ /-- A key property of `compact_conv_nhd`. It allows us to apply `topological_space.nhds_mk_of_nhds_filter_basis` below. -/ lemma compact_conv_nhd_nhd_basis (hV : V ∈ 𝓤 β) : ∃ (V' ∈ 𝓤 β), V' ⊆ V ∧ ∀ (g ∈ compact_conv_nhd K V' f), compact_conv_nhd K V' g ⊆ compact_conv_nhd K V f := begin obtain ⟨V', h₁, h₂⟩ := comp_mem_uniformity_sets hV, exact ⟨V', h₁, subset.trans (subset_comp_self_of_mem_uniformity h₁) h₂, λ g hg g' hg', compact_conv_nhd_mono f h₂ (compact_conv_nhd_mem_comp f hg hg')⟩, end lemma compact_conv_nhd_subset_inter (K₁ K₂ : set α) (V₁ V₂ : set (β × β)) : compact_conv_nhd (K₁ ∪ K₂) (V₁ ∩ V₂) f ⊆ compact_conv_nhd K₁ V₁ f ∩ compact_conv_nhd K₂ V₂ f := λ g hg, ⟨λ x hx, mem_of_mem_inter_left (hg x (mem_union_left K₂ hx)), λ x hx, mem_of_mem_inter_right (hg x (mem_union_right K₁ hx))⟩ lemma compact_conv_nhd_compact_entourage_nonempty : { KV : set α × set (β × β) | is_compact KV.1 ∧ KV.2 ∈ 𝓤 β }.nonempty := ⟨⟨∅, univ⟩, is_compact_empty, filter.univ_mem⟩ lemma compact_conv_nhd_filter_is_basis : filter.is_basis (λ (KV : set α × set (β × β)), is_compact KV.1 ∧ KV.2 ∈ 𝓤 β) (λ KV, compact_conv_nhd KV.1 KV.2 f) := { nonempty := compact_conv_nhd_compact_entourage_nonempty, inter := begin rintros ⟨K₁, V₁⟩ ⟨K₂, V₂⟩ ⟨hK₁, hV₁⟩ ⟨hK₂, hV₂⟩, exact ⟨⟨K₁ ∪ K₂, V₁ ∩ V₂⟩, ⟨hK₁.union hK₂, filter.inter_mem hV₁ hV₂⟩, compact_conv_nhd_subset_inter f K₁ K₂ V₁ V₂⟩, end, } /-- A filter basis for the neighbourhood filter of a point in the compact-convergence topology. -/ def compact_convergence_filter_basis (f : C(α, β)) : filter_basis C(α, β) := (compact_conv_nhd_filter_is_basis f).filter_basis lemma mem_compact_convergence_nhd_filter (Y : set C(α, β)) : Y ∈ (compact_convergence_filter_basis f).filter ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), compact_conv_nhd K V f ⊆ Y := begin split, { rintros ⟨X, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hY⟩, exact ⟨K, V, hK, hV, hY⟩, }, { rintros ⟨K, V, hK, hV, hY⟩, exact ⟨compact_conv_nhd K V f, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hY⟩, }, end /-- The compact-convergence topology. In fact, see `compact_open_eq_compact_convergence` this is the same as the compact-open topology. This definition is thus an auxiliary convenience definition and is unlikely to be of direct use. -/ def compact_convergence_topology : topological_space C(α, β) := topological_space.mk_of_nhds $ λ f, (compact_convergence_filter_basis f).filter lemma nhds_compact_convergence : @nhds _ compact_convergence_topology f = (compact_convergence_filter_basis f).filter := begin rw topological_space.nhds_mk_of_nhds_filter_basis; rintros g - ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, { exact self_mem_compact_conv_nhd g hV, }, { obtain ⟨V', hV', h₁, h₂⟩ := compact_conv_nhd_nhd_basis g hV, exact ⟨compact_conv_nhd K V' g, ⟨⟨K, V'⟩, ⟨hK, hV'⟩, rfl⟩, compact_conv_nhd_mono g h₁, λ g' hg', ⟨compact_conv_nhd K V' g', ⟨⟨K, V'⟩, ⟨hK, hV'⟩, rfl⟩, h₂ g' hg'⟩⟩, }, end lemma has_basis_nhds_compact_convergence : has_basis (@nhds _ compact_convergence_topology f) (λ (p : set α × set (β × β)), is_compact p.1 ∧ p.2 ∈ 𝓤 β) (λ p, compact_conv_nhd p.1 p.2 f) := (nhds_compact_convergence f).symm ▸ (compact_conv_nhd_filter_is_basis f).has_basis /-- This is an auxiliary lemma and is unlikely to be of direct use outside of this file. See `tendsto_iff_forall_compact_tendsto_uniformly_on` below for the useful version where the topology is picked up via typeclass inference. -/ lemma tendsto_iff_forall_compact_tendsto_uniformly_on' {ι : Type u₃} {p : filter ι} {F : ι → C(α, β)} : filter.tendsto F p (@nhds _ compact_convergence_topology f) ↔ ∀ K, is_compact K → tendsto_uniformly_on (λ i a, F i a) f p K := begin simp only [(has_basis_nhds_compact_convergence f).tendsto_right_iff, tendsto_uniformly_on, and_imp, prod.forall], refine forall_congr (λ K, _), rw forall_swap, exact forall₃_congr (λ hK V hV, iff.rfl), end /-- Any point of `compact_open.gen K U` is also an interior point wrt the topology of compact convergence. The topology of compact convergence is thus at least as fine as the compact-open topology. -/ lemma compact_conv_nhd_subset_compact_open (hK : is_compact K) {U : set β} (hU : is_open U) (hf : f ∈ compact_open.gen K U) : ∃ (V ∈ 𝓤 β), is_open V ∧ compact_conv_nhd K V f ⊆ compact_open.gen K U := begin obtain ⟨V, hV₁, hV₂, hV₃⟩ := lebesgue_number_of_compact_open (hK.image f.continuous) hU hf, refine ⟨V, hV₁, hV₂, _⟩, rintros g hg _ ⟨x, hx, rfl⟩, exact hV₃ (f x) ⟨x, hx, rfl⟩ (hg x hx), end /-- The point `f` in `compact_conv_nhd K V f` is also an interior point wrt the compact-open topology. Since `compact_conv_nhd K V f` are a neighbourhood basis at `f` for each `f`, it follows that the compact-open topology is at least as fine as the topology of compact convergence. -/ lemma Inter_compact_open_gen_subset_compact_conv_nhd (hK : is_compact K) (hV : V ∈ 𝓤 β) : ∃ (ι : Sort (u₁ + 1)) [fintype ι] (C : ι → set α) (hC : ∀ i, is_compact (C i)) (U : ι → set β) (hU : ∀ i, is_open (U i)), (f ∈ ⋂ i, compact_open.gen (C i) (U i)) ∧ (⋂ i, compact_open.gen (C i) (U i)) ⊆ compact_conv_nhd K V f := begin obtain ⟨W, hW₁, hW₄, hW₂, hW₃⟩ := comp_open_symm_mem_uniformity_sets hV, obtain ⟨Z, hZ₁, hZ₄, hZ₂, hZ₃⟩ := comp_open_symm_mem_uniformity_sets hW₁, let U : α → set α := λ x, f⁻¹' (ball (f x) Z), have hU : ∀ x, is_open (U x) := λ x, f.continuous.is_open_preimage _ (is_open_ball _ hZ₄), have hUK : K ⊆ ⋃ (x : K), U (x : K), { intros x hx, simp only [exists_prop, mem_Union, Union_coe_set, mem_preimage], exact ⟨(⟨x, hx⟩ : K), by simp [hx, mem_ball_self (f x) hZ₁]⟩, }, obtain ⟨t, ht⟩ := hK.elim_finite_subcover _ (λ (x : K), hU x.val) hUK, let C : t → set α := λ i, K ∩ closure (U ((i : K) : α)), have hC : K ⊆ ⋃ i, C i, { rw [← K.inter_Union, subset_inter_iff], refine ⟨subset.rfl, ht.trans _⟩, simp only [set_coe.forall, subtype.coe_mk, Union_subset_iff], exact λ x hx₁ hx₂, subset_Union_of_subset (⟨_, hx₂⟩ : t) (by simp [subset_closure]) }, have hfC : ∀ (i : t), C i ⊆ f ⁻¹' ball (f ((i : K) : α)) W, { simp only [← image_subset_iff, ← mem_preimage], rintros ⟨⟨x, hx₁⟩, hx₂⟩, have hZW : closure (ball (f x) Z) ⊆ ball (f x) W, { intros y hy, obtain ⟨z, hz₁, hz₂⟩ := uniform_space.mem_closure_iff_ball.mp hy hZ₁, exact ball_mono hZ₃ _ (mem_ball_comp hz₂ ((mem_ball_symmetry hZ₂).mp hz₁)), }, calc f '' (K ∩ closure (U x)) ⊆ f '' (closure (U x)) : image_subset _ (inter_subset_right _ _) ... ⊆ closure (f '' (U x)) : f.continuous.continuous_on.image_closure ... ⊆ closure (ball (f x) Z) : by { apply closure_mono, simp, } ... ⊆ ball (f x) W : hZW, }, refine ⟨t, t.fintype_coe_sort, C, λ i, hK.inter_right is_closed_closure, λ i, ball (f ((i : K) : α)) W, λ i, is_open_ball _ hW₄, by simp [compact_open.gen, hfC], λ g hg x hx, hW₃ (mem_comp_rel.mpr _)⟩, simp only [mem_Inter, compact_open.gen, mem_set_of_eq, image_subset_iff] at hg, obtain ⟨y, hy⟩ := mem_Union.mp (hC hx), exact ⟨f y, (mem_ball_symmetry hW₂).mp (hfC y hy), mem_preimage.mp (hg y hy)⟩, end /-- The compact-open topology is equal to the compact-convergence topology. -/ lemma compact_open_eq_compact_convergence : continuous_map.compact_open = (compact_convergence_topology : topological_space C(α, β)) := begin rw [compact_convergence_topology, continuous_map.compact_open], refine le_antisymm _ _, { refine λ X hX, is_open_iff_forall_mem_open.mpr (λ f hf, _), have hXf : X ∈ (compact_convergence_filter_basis f).filter, { rw ← nhds_compact_convergence, exact @is_open.mem_nhds C(α, β) compact_convergence_topology _ _ hX hf, }, obtain ⟨-, ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩, hXf⟩ := hXf, obtain ⟨ι, hι, C, hC, U, hU, h₁, h₂⟩ := Inter_compact_open_gen_subset_compact_conv_nhd f hK hV, haveI := hι, exact ⟨⋂ i, compact_open.gen (C i) (U i), h₂.trans hXf, is_open_Inter (λ i, continuous_map.is_open_gen (hC i) (hU i)), h₁⟩, }, { simp only [le_generate_from_iff_subset_is_open, and_imp, exists_prop, forall_exists_index, set_of_subset_set_of], rintros - K hK U hU rfl f hf, obtain ⟨V, hV, hV', hVf⟩ := compact_conv_nhd_subset_compact_open f hK hU hf, exact filter.mem_of_superset (filter_basis.mem_filter_of_mem _ ⟨⟨K, V⟩, ⟨hK, hV⟩, rfl⟩) hVf, }, end /-- The filter on `C(α, β) × C(α, β)` which underlies the uniform space structure on `C(α, β)`. -/ def compact_convergence_uniformity : filter (C(α, β) × C(α, β)) := ⨅ KV ∈ { KV : set α × set (β × β) | is_compact KV.1 ∧ KV.2 ∈ 𝓤 β }, 𝓟 { fg : C(α, β) × C(α, β) | ∀ (x : α), x ∈ KV.1 → (fg.1 x, fg.2 x) ∈ KV.2 } lemma has_basis_compact_convergence_uniformity_aux : has_basis (@compact_convergence_uniformity α β _ _) (λ p : set α × set (β × β), is_compact p.1 ∧ p.2 ∈ 𝓤 β) (λ p, { fg : C(α, β) × C(α, β) | ∀ x ∈ p.1, (fg.1 x, fg.2 x) ∈ p.2 }) := begin refine filter.has_basis_binfi_principal _ compact_conv_nhd_compact_entourage_nonempty, rintros ⟨K₁, V₁⟩ ⟨hK₁, hV₁⟩ ⟨K₂, V₂⟩ ⟨hK₂, hV₂⟩, refine ⟨⟨K₁ ∪ K₂, V₁ ∩ V₂⟩, ⟨hK₁.union hK₂, filter.inter_mem hV₁ hV₂⟩, _⟩, simp only [le_eq_subset, prod.forall, set_of_subset_set_of, ge_iff_le, order.preimage, ← forall_and_distrib, mem_inter_eq, mem_union_eq], exact λ f g, forall_imp (λ x, by tauto!), end /-- An intermediate lemma. Usually `mem_compact_convergence_entourage_iff` is more useful. -/ lemma mem_compact_convergence_uniformity (X : set (C(α, β) × C(α, β))) : X ∈ @compact_convergence_uniformity α β _ _ ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), { fg : C(α, β) × C(α, β) | ∀ x ∈ K, (fg.1 x, fg.2 x) ∈ V } ⊆ X := by simp only [has_basis_compact_convergence_uniformity_aux.mem_iff, exists_prop, prod.exists, and_assoc] /-- Note that we ensure the induced topology is definitionally the compact-open topology. -/ instance compact_convergence_uniform_space : uniform_space C(α, β) := { uniformity := compact_convergence_uniformity, refl := begin simp only [compact_convergence_uniformity, and_imp, filter.le_principal_iff, prod.forall, filter.mem_principal, mem_set_of_eq, le_infi_iff, id_rel_subset], exact λ K V hK hV f x hx, refl_mem_uniformity hV, end, symm := begin simp only [compact_convergence_uniformity, and_imp, prod.forall, mem_set_of_eq, prod.fst_swap, filter.tendsto_principal, prod.snd_swap, filter.tendsto_infi], intros K V hK hV, obtain ⟨V', hV', hsymm, hsub⟩ := symm_of_uniformity hV, let X := { fg : C(α, β) × C(α, β) | ∀ (x : α), x ∈ K → (fg.1 x, fg.2 x) ∈ V' }, have hX : X ∈ compact_convergence_uniformity := (mem_compact_convergence_uniformity X).mpr ⟨K, V', hK, hV', by simp⟩, exact filter.eventually_of_mem hX (λ fg hfg x hx, hsub (hsymm _ _ (hfg x hx))), end, comp := λ X hX, begin obtain ⟨K, V, hK, hV, hX⟩ := (mem_compact_convergence_uniformity X).mp hX, obtain ⟨V', hV', hcomp⟩ := comp_mem_uniformity_sets hV, let h := λ (s : set (C(α, β) × C(α, β))), s ○ s, suffices : h {fg : C(α, β) × C(α, β) | ∀ (x ∈ K), (fg.1 x, fg.2 x) ∈ V'} ∈ compact_convergence_uniformity.lift' h, { apply filter.mem_of_superset this, rintros ⟨f, g⟩ ⟨z, hz₁, hz₂⟩, refine hX (λ x hx, hcomp _), exact ⟨z x, hz₁ x hx, hz₂ x hx⟩, }, apply filter.mem_lift', exact (mem_compact_convergence_uniformity _).mpr ⟨K, V', hK, hV', subset.refl _⟩, end, is_open_uniformity := begin rw compact_open_eq_compact_convergence, refine λ Y, forall₂_congr (λ f hf, _), simp only [mem_compact_convergence_nhd_filter, mem_compact_convergence_uniformity, prod.forall, set_of_subset_set_of, compact_conv_nhd], refine exists₄_congr (λ K V hK hV, ⟨_, λ hY g hg, hY f g hg rfl⟩), rintros hY g₁ g₂ hg₁ rfl, exact hY hg₁, end } lemma mem_compact_convergence_entourage_iff (X : set (C(α, β) × C(α, β))) : X ∈ 𝓤 C(α, β) ↔ ∃ (K : set α) (V : set (β × β)) (hK : is_compact K) (hV : V ∈ 𝓤 β), { fg : C(α, β) × C(α, β) | ∀ x ∈ K, (fg.1 x, fg.2 x) ∈ V } ⊆ X := mem_compact_convergence_uniformity X lemma has_basis_compact_convergence_uniformity : has_basis (𝓤 C(α, β)) (λ p : set α × set (β × β), is_compact p.1 ∧ p.2 ∈ 𝓤 β) (λ p, { fg : C(α, β) × C(α, β) | ∀ x ∈ p.1, (fg.1 x, fg.2 x) ∈ p.2 }) := has_basis_compact_convergence_uniformity_aux lemma _root_.filter.has_basis.compact_convergence_uniformity {ι : Type*} {pi : ι → Prop} {s : ι → set (β × β)} (h : (𝓤 β).has_basis pi s) : has_basis (𝓤 C(α, β)) (λ p : set α × ι, is_compact p.1 ∧ pi p.2) (λ p, { fg : C(α, β) × C(α, β) | ∀ x ∈ p.1, (fg.1 x, fg.2 x) ∈ s p.2 }) := begin refine has_basis_compact_convergence_uniformity.to_has_basis _ _, { rintro ⟨t₁, t₂⟩ ⟨h₁, h₂⟩, rcases h.mem_iff.1 h₂ with ⟨i, hpi, hi⟩, exact ⟨(t₁, i), ⟨h₁, hpi⟩, λ fg hfg x hx, hi (hfg _ hx)⟩ }, { rintro ⟨t, i⟩ ⟨ht, hi⟩, exact ⟨(t, s i), ⟨ht, h.mem_of_mem hi⟩, subset.rfl⟩ } end variables {ι : Type u₃} {p : filter ι} {F : ι → C(α, β)} {f} lemma tendsto_iff_forall_compact_tendsto_uniformly_on : tendsto F p (𝓝 f) ↔ ∀ K, is_compact K → tendsto_uniformly_on (λ i a, F i a) f p K := by rw [compact_open_eq_compact_convergence, tendsto_iff_forall_compact_tendsto_uniformly_on'] /-- Locally uniform convergence implies convergence in the compact-open topology. -/ lemma tendsto_of_tendsto_locally_uniformly (h : tendsto_locally_uniformly (λ i a, F i a) f p) : tendsto F p (𝓝 f) := begin rw tendsto_iff_forall_compact_tendsto_uniformly_on, intros K hK, rw ← tendsto_locally_uniformly_on_iff_tendsto_uniformly_on_of_compact hK, exact h.tendsto_locally_uniformly_on, end /-- If every point has a compact neighbourhood, then convergence in the compact-open topology implies locally uniform convergence. See also `tendsto_iff_tendsto_locally_uniformly`, especially for T2 spaces. -/ lemma tendsto_locally_uniformly_of_tendsto (hα : ∀ x : α, ∃ n, is_compact n ∧ n ∈ 𝓝 x) (h : tendsto F p (𝓝 f)) : tendsto_locally_uniformly (λ i a, F i a) f p := begin rw tendsto_iff_forall_compact_tendsto_uniformly_on at h, intros V hV x, obtain ⟨n, hn₁, hn₂⟩ := hα x, exact ⟨n, hn₂, h n hn₁ V hV⟩, end /-- Convergence in the compact-open topology is the same as locally uniform convergence on a locally compact space. For non-T2 spaces, the assumption `locally_compact_space α` is stronger than we need and in fact the `←` direction is true unconditionally. See `tendsto_locally_uniformly_of_tendsto` and `tendsto_of_tendsto_locally_uniformly` for versions requiring weaker hypotheses. -/ lemma tendsto_iff_tendsto_locally_uniformly [locally_compact_space α] : tendsto F p (𝓝 f) ↔ tendsto_locally_uniformly (λ i a, F i a) f p := ⟨tendsto_locally_uniformly_of_tendsto exists_compact_mem_nhds, tendsto_of_tendsto_locally_uniformly⟩ section compact_domain variables [compact_space α] lemma has_basis_compact_convergence_uniformity_of_compact : has_basis (𝓤 C(α, β)) (λ V : set (β × β), V ∈ 𝓤 β) (λ V, { fg : C(α, β) × C(α, β) | ∀ x, (fg.1 x, fg.2 x) ∈ V }) := has_basis_compact_convergence_uniformity.to_has_basis (λ p hp, ⟨p.2, hp.2, λ fg hfg x hx, hfg x⟩) (λ V hV, ⟨⟨univ, V⟩, ⟨compact_univ, hV⟩, λ fg hfg x, hfg x (mem_univ x)⟩) /-- Convergence in the compact-open topology is the same as uniform convergence for sequences of continuous functions on a compact space. -/ lemma tendsto_iff_tendsto_uniformly : tendsto F p (𝓝 f) ↔ tendsto_uniformly (λ i a, F i a) f p := begin rw [tendsto_iff_forall_compact_tendsto_uniformly_on, ← tendsto_uniformly_on_univ], exact ⟨λ h, h univ compact_univ, λ h K hK, h.mono (subset_univ K)⟩, end end compact_domain end continuous_map
519fbad2b275ddf357ffb83dec3a77a1398b6b94
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Compiler/IR/Checker.lean
f6db9b5d6342a47dd2b3175ecae4c08992232e7e
[ "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
6,620
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.Format namespace Lean namespace IR namespace Checker structure CheckerContext := (env : Environment) (localCtx : LocalContext := {}) (decls : Array Decl) structure CheckerState := (foundVars : IndexSet := {}) abbrev M := ReaderT CheckerContext (ExceptT String (StateT CheckerState Id)) def markIndex (i : Index) : M Unit := do s ← get; when (s.foundVars.contains i) $ throw ("variable / joinpoint index " ++ toString i ++ " has already been used"); modify $ fun s => { s with foundVars := s.foundVars.insert i } def markVar (x : VarId) : M Unit := markIndex x.idx def markJP (j : JoinPointId) : M Unit := markIndex j.idx def getDecl (c : Name) : M Decl := do ctx ← read; match findEnvDecl' ctx.env c ctx.decls with | none => throw ("unknown declaration '" ++ toString c ++ "'") | some d => pure d def checkVar (x : VarId) : M Unit := do ctx ← read; unless (ctx.localCtx.isLocalVar x.idx || ctx.localCtx.isParam x.idx) $ throw ("unknown variable '" ++ toString x ++ "'") def checkJP (j : JoinPointId) : M Unit := do ctx ← read; unless (ctx.localCtx.isJP j.idx) $ throw ("unknown join point '" ++ toString j ++ "'") def checkArg (a : Arg) : M Unit := match a with | Arg.var x => checkVar x | other => pure () def checkArgs (as : Array Arg) : M Unit := as.forM checkArg @[inline] def checkEqTypes (ty₁ ty₂ : IRType) : M Unit := unless (ty₁ == ty₂) $ throw ("unexpected type") @[inline] def checkType (ty : IRType) (p : IRType → Bool) : M Unit := unless (p ty) $ throw ("unexpected type '" ++ toString ty ++ "'") def checkObjType (ty : IRType) : M Unit := checkType ty IRType.isObj def checkScalarType (ty : IRType) : M Unit := checkType ty IRType.isScalar def getType (x : VarId) : M IRType := do ctx ← read; match ctx.localCtx.getType x with | some ty => pure ty | none => throw ("unknown variable '" ++ toString x ++ "'") @[inline] def checkVarType (x : VarId) (p : IRType → Bool) : M Unit := do ty ← getType x; checkType ty p def checkObjVar (x : VarId) : M Unit := checkVarType x IRType.isObj def checkScalarVar (x : VarId) : M Unit := checkVarType x IRType.isScalar def checkFullApp (c : FunId) (ys : Array Arg) : M Unit := do when (c == `hugeFuel) $ throw ("the auxiliary constant `hugeFuel` cannot be used in code, it is used internally for compiling `partial` definitions"); decl ← getDecl c; unless (ys.size == decl.params.size) $ throw ("incorrect number of arguments to '" ++ toString c ++ "', " ++ toString ys.size ++ " provided, " ++ toString decl.params.size ++ " expected"); checkArgs ys def checkPartialApp (c : FunId) (ys : Array Arg) : M Unit := do decl ← getDecl c; unless (ys.size < decl.params.size) $ throw ("too many arguments too partial application '" ++ toString c ++ "', num. args: " ++ toString ys.size ++ ", arity: " ++ toString decl.params.size); checkArgs ys def checkExpr (ty : IRType) : Expr → M Unit | Expr.pap f ys => checkPartialApp f ys *> checkObjType ty -- partial applications should always produce a closure object | Expr.ap x ys => checkObjVar x *> checkArgs ys | Expr.fap f ys => checkFullApp f ys | Expr.ctor c ys => when (!ty.isStruct && !ty.isUnion && c.isRef) (checkObjType ty) *> checkArgs ys | Expr.reset _ x => checkObjVar x *> checkObjType ty | Expr.reuse x i u ys => checkObjVar x *> checkArgs ys *> checkObjType ty | Expr.box xty x => checkObjType ty *> checkScalarVar x *> checkVarType x (fun t => t == xty) | Expr.unbox x => checkScalarType ty *> checkObjVar x | Expr.proj i x => do xType ← getType x; match xType with | IRType.object => checkObjType ty | IRType.tobject => checkObjType ty | IRType.struct _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index" | IRType.union _ tys => if h : i < tys.size then checkEqTypes (tys.get ⟨i,h⟩) ty else throw "invalid proj index" | other => throw ("unexpected IR type '" ++ toString xType ++ "'") | Expr.uproj _ x => checkObjVar x *> checkType ty (fun t => t == IRType.usize) | Expr.sproj _ _ x => checkObjVar x *> checkScalarType ty | Expr.isShared x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8) | Expr.isTaggedPtr x => checkObjVar x *> checkType ty (fun t => t == IRType.uint8) | Expr.lit (LitVal.str _) => checkObjType ty | Expr.lit _ => pure () @[inline] def withParams (ps : Array Param) (k : M Unit) : M Unit := do ctx ← read; localCtx ← ps.foldlM (fun (ctx : LocalContext) p => do markVar p.x; pure $ ctx.addParam p) ctx.localCtx; adaptReader (fun _ => { ctx with localCtx := localCtx }) k partial def checkFnBody : FnBody → M Unit | FnBody.vdecl x t v b => do checkExpr t v; markVar x; ctx ← read; adaptReader (fun (ctx : CheckerContext) => { ctx with localCtx := ctx.localCtx.addLocal x t v }) (checkFnBody b) | FnBody.jdecl j ys v b => do markJP j; withParams ys (checkFnBody v); ctx ← read; adaptReader (fun (ctx : CheckerContext) => { ctx with localCtx := ctx.localCtx.addJP j ys v }) (checkFnBody b) | FnBody.set x _ y b => checkVar x *> checkArg y *> checkFnBody b | FnBody.uset x _ y b => checkVar x *> checkVar y *> checkFnBody b | FnBody.sset x _ _ y _ b => checkVar x *> checkVar y *> checkFnBody b | FnBody.setTag x _ b => checkVar x *> checkFnBody b | FnBody.inc x _ _ _ b => checkVar x *> checkFnBody b | FnBody.dec x _ _ _ b => checkVar x *> checkFnBody b | FnBody.del x b => checkVar x *> checkFnBody b | FnBody.mdata _ b => checkFnBody b | FnBody.jmp j ys => checkJP j *> checkArgs ys | FnBody.ret x => checkArg x | FnBody.case _ x _ alts => checkVar x *> alts.forM (fun alt => checkFnBody alt.body) | FnBody.unreachable => pure () def checkDecl : Decl → M Unit | Decl.fdecl f xs t b => withParams xs (checkFnBody b) | Decl.extern f xs t _ => withParams xs (pure ()) end Checker def checkDecl (decls : Array Decl) (decl : Decl) : CompilerM Unit := do env ← getEnv; match (Checker.checkDecl decl { env := env, decls := decls }).run' {} with | Except.error msg => throw ("IR check failed at '" ++ toString decl.name ++ "', error: " ++ msg) | other => pure () def checkDecls (decls : Array Decl) : CompilerM Unit := decls.forM (checkDecl decls) end IR end Lean
cc2e41011c6c6f607422ce53f934a3c07fc06dc8
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/elab6.lean
84caa3b3dfeebfc39b0db810f7a6299ebcbdbdb7
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
286
lean
constant R : nat → nat → Prop constant H : transitive R set_option pp.all true constant F : ∀ {A : Type*} ⦃a : A⦄ {b : A} (c : A) ⦃e : A⦄, A → A → A check H check F check F tt check F tt tt check F tt tt tt check H check F check F tt check F tt tt check F tt tt tt
b8c464279cd51de8c1fecc043d9401b05028d2b7
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/symm_diff.lean
5ed2553718d3c6328edeba31f8a3a4413432a512
[ "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
9,111
lean
/- Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Bryan Gin-ge Chen -/ import order.boolean_algebra /-! # Symmetric difference The symmetric difference or disjunctive union of sets `A` and `B` is the set of elements that are in either `A` or `B` but not both. Translated into propositions, the symmetric difference is `xor`. The symmetric difference operator (`symm_diff`) is defined in this file for any type with `⊔` and `\` via the formula `(A \ B) ⊔ (B \ A)`, however the theorems proved about it only hold for `generalized_boolean_algebra`s and `boolean_algebra`s. The symmetric difference is the addition operator in the Boolean ring structure on Boolean algebras. ## Main declarations * `symm_diff`: the symmetric difference operator, defined as `(A \ B) ⊔ (B \ A)` In generalized Boolean algebras, the symmetric difference operator is: * `symm_diff_comm`: commutative, and * `symm_diff_assoc`: associative. ## Notations * `a Δ b`: `symm_diff a b` ## References The proof of associativity follows the note "Associativity of the Symmetric Difference of Sets: A Proof from the Book" by John McCuan: * <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf> ## Tags boolean ring, generalized boolean algebra, boolean algebra, symmetric differences -/ /-- The symmetric difference operator on a type with `⊔` and `\` is `(A \ B) ⊔ (B \ A)`. -/ def symm_diff {α : Type*} [has_sup α] [has_sdiff α] (A B : α) : α := (A \ B) ⊔ (B \ A) infix ` Δ `:100 := symm_diff lemma symm_diff_def {α : Type*} [has_sup α] [has_sdiff α] (A B : α) : A Δ B = (A \ B) ⊔ (B \ A) := rfl lemma symm_diff_eq_xor (p q : Prop) : p Δ q = xor p q := rfl section generalized_boolean_algebra variables {α : Type*} [generalized_boolean_algebra α] (a b c : α) lemma symm_diff_comm : a Δ b = b Δ a := by simp only [(Δ), sup_comm] instance symm_diff_is_comm : is_commutative α (Δ) := ⟨symm_diff_comm⟩ @[simp] lemma symm_diff_self : a Δ a = ⊥ := by rw [(Δ), sup_idem, sdiff_self] @[simp] lemma symm_diff_bot : a Δ ⊥ = a := by rw [(Δ), sdiff_bot, bot_sdiff, sup_bot_eq] @[simp] lemma bot_symm_diff : ⊥ Δ a = a := by rw [symm_diff_comm, symm_diff_bot] lemma symm_diff_eq_sup_sdiff_inf : a Δ b = (a ⊔ b) \ (a ⊓ b) := by simp [sup_sdiff, sdiff_inf, sup_comm, (Δ)] lemma disjoint_symm_diff_inf : disjoint (a Δ b) (a ⊓ b) := begin rw [symm_diff_eq_sup_sdiff_inf], exact disjoint_sdiff_self_left, end lemma symm_diff_le_sup : a Δ b ≤ a ⊔ b := by { rw symm_diff_eq_sup_sdiff_inf, exact sdiff_le } lemma sdiff_symm_diff : c \ (a Δ b) = (c ⊓ a ⊓ b) ⊔ ((c \ a) ⊓ (c \ b)) := by simp only [(Δ), sdiff_sdiff_sup_sdiff'] lemma sdiff_symm_diff' : c \ (a Δ b) = (c ⊓ a ⊓ b) ⊔ (c \ (a ⊔ b)) := by rw [sdiff_symm_diff, sdiff_sup, sup_comm] lemma symm_diff_sdiff : (a Δ b) \ c = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) := by rw [symm_diff_def, sup_sdiff, sdiff_sdiff_left, sdiff_sdiff_left] @[simp] lemma symm_diff_sdiff_left : (a Δ b) \ a = b \ a := by rw [symm_diff_def, sup_sdiff, sdiff_idem, sdiff_sdiff_self, bot_sup_eq] @[simp] lemma symm_diff_sdiff_right : (a Δ b) \ b = a \ b := by rw [symm_diff_comm, symm_diff_sdiff_left] @[simp] lemma sdiff_symm_diff_self : a \ (a Δ b) = a ⊓ b := by simp [sdiff_symm_diff] lemma symm_diff_eq_iff_sdiff_eq {a b c : α} (ha : a ≤ c) : a Δ b = c ↔ c \ a = b := begin split; intro h, { have hba : disjoint (a ⊓ b) c := begin rw [←h, disjoint.comm], exact disjoint_symm_diff_inf _ _, end, have hca : _ := congr_arg (\ a) h, rw [symm_diff_sdiff_left] at hca, rw [←hca, sdiff_eq_self_iff_disjoint], exact hba.of_disjoint_inf_of_le ha }, { have hd : disjoint a b := by { rw ←h, exact disjoint_sdiff_self_right }, rw [symm_diff_def, hd.sdiff_eq_left, hd.sdiff_eq_right, ←h, sup_sdiff_cancel_right ha] } end lemma disjoint.symm_diff_eq_sup {a b : α} (h : disjoint a b) : a Δ b = a ⊔ b := by rw [(Δ), h.sdiff_eq_left, h.sdiff_eq_right] lemma symm_diff_eq_sup : a Δ b = a ⊔ b ↔ disjoint a b := begin split; intro h, { rw [symm_diff_eq_sup_sdiff_inf, sdiff_eq_self_iff_disjoint] at h, exact h.of_disjoint_inf_of_le le_sup_left, }, { exact h.symm_diff_eq_sup, }, end lemma symm_diff_symm_diff_left : a Δ b Δ c = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) := calc a Δ b Δ c = ((a Δ b) \ c) ⊔ (c \ (a Δ b)) : symm_diff_def _ _ ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ ((c \ (a ⊔ b)) ⊔ (c ⊓ a ⊓ b)) : by rw [sdiff_symm_diff', @sup_comm _ _ (c ⊓ a ⊓ b), symm_diff_sdiff] ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl lemma symm_diff_symm_diff_right : a Δ (b Δ c) = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) := calc a Δ (b Δ c) = (a \ (b Δ c)) ⊔ ((b Δ c) \ a) : symm_diff_def _ _ ... = (a \ (b ⊔ c)) ⊔ (a ⊓ b ⊓ c) ⊔ (b \ (c ⊔ a) ⊔ c \ (b ⊔ a)) : by rw [sdiff_symm_diff', @sup_comm _ _ (a ⊓ b ⊓ c), symm_diff_sdiff] ... = (a \ (b ⊔ c)) ⊔ (b \ (a ⊔ c)) ⊔ (c \ (a ⊔ b)) ⊔ (a ⊓ b ⊓ c) : by ac_refl lemma symm_diff_assoc : a Δ b Δ c = a Δ (b Δ c) := by rw [symm_diff_symm_diff_left, symm_diff_symm_diff_right] instance symm_diff_is_assoc : is_associative α (Δ) := ⟨symm_diff_assoc⟩ @[simp] lemma symm_diff_symm_diff_self : a Δ (a Δ b) = b := by simp [←symm_diff_assoc] @[simp] lemma symm_diff_symm_diff_self' : a Δ b Δ a = b := by rw [symm_diff_comm, ←symm_diff_assoc, symm_diff_self, bot_symm_diff] @[simp] lemma symm_diff_right_inj : a Δ b = a Δ c ↔ b = c := begin split; intro h, { have H1 := congr_arg ((Δ) a) h, rwa [symm_diff_symm_diff_self, symm_diff_symm_diff_self] at H1, }, { rw h, }, end @[simp] lemma symm_diff_left_inj : a Δ b = c Δ b ↔ a = c := by rw [symm_diff_comm a b, symm_diff_comm c b, symm_diff_right_inj] @[simp] lemma symm_diff_eq_left : a Δ b = a ↔ b = ⊥ := calc a Δ b = a ↔ a Δ b = a Δ ⊥ : by rw symm_diff_bot ... ↔ b = ⊥ : by rw symm_diff_right_inj @[simp] lemma symm_diff_eq_right : a Δ b = b ↔ a = ⊥ := by rw [symm_diff_comm, symm_diff_eq_left] @[simp] lemma symm_diff_eq_bot : a Δ b = ⊥ ↔ a = b := calc a Δ b = ⊥ ↔ a Δ b = a Δ a : by rw symm_diff_self ... ↔ a = b : by rw [symm_diff_right_inj, eq_comm] lemma disjoint.disjoint_symm_diff_of_disjoint {a b c : α} (ha : disjoint a c) (hb : disjoint b c) : disjoint (a Δ b) c := begin rw symm_diff_eq_sup_sdiff_inf, exact (ha.sup_left hb).disjoint_sdiff_left, end end generalized_boolean_algebra section boolean_algebra variables {α : Type*} [boolean_algebra α] (a b c : α) lemma symm_diff_eq : a Δ b = (a ⊓ bᶜ) ⊔ (b ⊓ aᶜ) := by simp only [(Δ), sdiff_eq] @[simp] lemma symm_diff_top : a Δ ⊤ = aᶜ := by simp [symm_diff_eq] @[simp] lemma top_symm_diff : ⊤ Δ a = aᶜ := by rw [symm_diff_comm, symm_diff_top] lemma compl_symm_diff : (a Δ b)ᶜ = (a ⊓ b) ⊔ (aᶜ ⊓ bᶜ) := by simp only [←top_sdiff, sdiff_symm_diff, top_inf_eq] lemma symm_diff_eq_top_iff : a Δ b = ⊤ ↔ is_compl a b := by rw [symm_diff_eq_iff_sdiff_eq le_top, top_sdiff, compl_eq_iff_is_compl] lemma is_compl.symm_diff_eq_top (h : is_compl a b) : a Δ b = ⊤ := (symm_diff_eq_top_iff a b).2 h @[simp] lemma compl_symm_diff_self : aᶜ Δ a = ⊤ := by simp only [symm_diff_eq, compl_compl, inf_idem, compl_sup_eq_top] @[simp] lemma symm_diff_compl_self : a Δ aᶜ = ⊤ := by rw [symm_diff_comm, compl_symm_diff_self] lemma symm_diff_symm_diff_right' : a Δ (b Δ c) = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) := calc a Δ (b Δ c) = (a ⊓ ((b ⊓ c) ⊔ (bᶜ ⊓ cᶜ))) ⊔ (((b ⊓ cᶜ) ⊔ (c ⊓ bᶜ)) ⊓ aᶜ) : by rw [symm_diff_eq, compl_symm_diff, symm_diff_eq] ... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (b ⊓ cᶜ ⊓ aᶜ) ⊔ (c ⊓ bᶜ ⊓ aᶜ) : by rw [inf_sup_left, inf_sup_right, ←sup_assoc, ←inf_assoc, ←inf_assoc] ... = (a ⊓ b ⊓ c) ⊔ (a ⊓ bᶜ ⊓ cᶜ) ⊔ (aᶜ ⊓ b ⊓ cᶜ) ⊔ (aᶜ ⊓ bᶜ ⊓ c) : begin congr' 1, { congr' 1, rw [inf_comm, inf_assoc], }, { apply inf_left_right_swap } end end boolean_algebra
90d3ef18f8dfee1d89cabdeb58564427c05330bd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/InternalExceptionId.lean
0b72bad7ed75f4720820d040a36b5d91d7ea4325
[ "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,506
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 -/ namespace Lean /-- Internal exception identifier -/ structure InternalExceptionId where idx : Nat := 0 deriving Inhabited, BEq /-- Internal exceptions registered in the system. -/ builtin_initialize internalExceptionsRef : IO.Ref (Array Name) ← IO.mkRef #[] /-- Register a new internal exception in the system. Each internal exception has a unique index. Throw an exception if the given name is not unique. This method is usually invoked using the `initialize` command. -/ def registerInternalExceptionId (name : Name) : IO InternalExceptionId := do let exs ← internalExceptionsRef.get if exs.contains name then throw <| IO.userError s!"invalid internal exception id, '{name}' has already been used" let nextIdx := exs.size internalExceptionsRef.modify fun a => a.push name pure { idx := nextIdx } /-- Convert internal exception id into the message "internal exception #<idx>"-/ def InternalExceptionId.toString (id : InternalExceptionId) : String := s!"internal exception #{id.idx}" /-- Retrieve the name used to register the internal exception. -/ def InternalExceptionId.getName (id : InternalExceptionId) : IO Name := do let exs ← internalExceptionsRef.get let i := id.idx; if h : i < exs.size then return exs.get ⟨i, h⟩ else throw <| IO.userError "invalid internal exception id" end Lean
c2864d23374d583f678fdea161cd7c23fb474e4d
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0603.lean
d01ac2028e81af1595b301d8c6a1c473b5430899
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
394
lean
variables (men : Type) (barber : men) variable (shaves : men → men → Prop) example (h : ∀ x : men, shaves barber x ↔ ¬ shaves x x) : false := have hb : shaves barber barber ↔ ¬ shaves barber barber, from h barber, have ¬ shaves barber barber, from assume : shaves barber barber, hb.mp this this, ‹¬ shaves barber barber› (hb.mpr ‹¬ shaves barber barber›)
092bb91756cfd85124e07ce1200f8ffc11ea78a5
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/topology/continuity.lean
492b7f56abea9d95846ada3bf65be19c63344607
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,339
lean
import data.real.basic import topology.basic namespace xena -- hide open function open real open set /- Classic eps-delta definition of continuity equivalent to topological definition. Work in progress. -/ notation `|` x `|` := abs x def continuous_at_x (f : ℝ → ℝ) (x : ℝ) := ∀ ε : ℝ, 0 < ε → ∃ δ : ℝ, 0 < δ ∧ ∀ y : ℝ, |x - y| < δ → |f x - f y| < ε def continuous_on_set (f : ℝ → ℝ) (X : set ℝ) := ∀ x ∈ X, continuous_at_x f x def open_in_R (Y : set ℝ) := ∀ x ∈ Y, ∃ ε : ℝ, 0 < ε ∧ { y | |x-y| < ε } ⊂ Y def open_in_X (S : set ℝ) (X : set ℝ) (hS : S ⊂ X) := ∃ Y : set ℝ, S = Y ∩ X ∧ open_in_R Y def preimage_in_X (f : ℝ → ℝ) (X : set ℝ) (T : set ℝ) := { x | x ∈ X ∧ ∃ t ∈ T, f x = t} def continuous_on_topo_def (f : ℝ → ℝ) (X : set ℝ) := ∀ T : set ℝ, open_in_R T → open_in_R (preimage_in_X f X T) /- theorem continuous_on_topo_def2 (f : ℝ → ℝ) (X : set ℝ) : ∀ x ∈ X, ∀ t : set ℝ, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ X ⊆ f ⁻¹' t := -/ /- Lemma Equivalent definitions of continuity. -/ lemma continuity_topological (f : ℝ → ℝ) (X : set ℝ) : continuous_on_set f X ↔ continuous_on_topo_def f X := begin sorry, end end xena
dd181b070aef01307e680d326f35699c81ec05b6
4a092885406df4e441e9bb9065d9405dacb94cd8
/src/valuation/field.lean
0c781cd5366aa7d54aae86ce99cf0647f9d48b1b
[ "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
3,902
lean
import for_mathlib.topological_field import for_mathlib.topology import for_mathlib.division_ring import valuation.topology local attribute [instance, priority 0] classical.decidable_linear_order variables {Γ : Type*} [linear_ordered_comm_group Γ] def valued_ring (R : Type*) [ring R] (v : valuation R Γ) := R namespace valued_ring variables {R : Type*} [ring R] variables (v : valuation R Γ) instance : ring (valued_ring R v) := ‹ring R› instance : ring_with_zero_nhd (valued_ring R v) := valuation.ring_with_zero_nhd v variables {K : Type*} [division_ring K] (ν : valuation K Γ) instance : division_ring (valued_ring K ν) := ‹division_ring K› end valued_ring variables {K : Type*} [division_ring K] (v : valuation K Γ) variables x y : units K -- The following is meant to be the main technical lemma ensuring that inversion is continuous -- in the topology induced by a valuation on a division ring (ie the next instance) lemma top_div_ring_aux {x y : units K} {γ : Γ} (h : v (x - y) < min (γ*((v y)*(v y))) (v y)) : v (x⁻¹.val - y⁻¹.val) < γ := begin have hyp1 : v (x - y) < γ*((v y)*(v y)), from lt_of_lt_of_le h (min_le_left _ _), have hyp1' : v (x - y)*((v y)*(v y))⁻¹ < γ, from with_zero.mul_inv_lt_of_lt_mul hyp1, have hyp2 : v (x - y) < v y, from lt_of_lt_of_le h (min_le_right _ _), have key : v x = v y, { have := valuation.map_add_of_distinct_val v (ne_of_gt hyp2), rw max_eq_left (le_of_lt hyp2) at this, simpa using this }, have decomp : x⁻¹.val - y⁻¹.val = x⁻¹.val*(y.val-x.val)*y⁻¹.val, by rw [mul_sub_left_distrib, sub_mul, mul_assoc, show y.val * y⁻¹.val = 1, from y.val_inv, show x⁻¹.val * x.val = 1, from x.inv_val, mul_one, one_mul], calc v (x⁻¹.val - y⁻¹.val) = v (x⁻¹.val*(y.val-x.val)*y⁻¹.val) : by rw decomp ... = (v x⁻¹.val)*(v $ y.val-x.val)*(v y⁻¹.val) : by repeat { rw valuation.map_mul } ... = (v x)⁻¹*(v $ y.val-x.val)*(v y)⁻¹ : by repeat { rw valuation.map_inv } ... = (v $ y.val-x.val)*((v y)*(v y))⁻¹ : by rw [mul_assoc,mul_comm, key, mul_assoc, ← with_zero.mul_inv_rev] ... = (v $ y - x)*((v y)*(v y))⁻¹ : rfl ... = (v $ x - y)*((v y)*(v y))⁻¹ : by rw valuation.map_sub_swap ... < γ : hyp1', end instance valuation.topological_division_ring : topological_division_ring (valued_ring K v) := { continuous_inv := begin let Kv := valued_ring K v, have H : units.val ∘ (λ x : units Kv, x⁻¹) = (λ x : Kv, x⁻¹) ∘ units.val, by ext ;simp, rw continuous_iff_continuous_at, intro x, let emb := topological_ring.units_embedding Kv, apply emb.tendsto_iff emb H, unfold continuous_at, rw topological_add_group.tendsto_nhds_nhds_iff (λ (x : Kv), x⁻¹) x.val x.val⁻¹, intros V V_in, cases (of_subgroups.nhds_zero _).1 V_in with γ Hγ, let x' : units K := units.mk (x.val : K) (x.inv : K) x.val_inv x.inv_val, use { k : Kv | v k < min (γ*((v x')*(v x'))) (v x')}, split, { refine (of_subgroups.nhds_zero _).2 _, cases valuation.unit_is_some v x' with γ' hγ', use min (γ * γ' * γ') γ', intro k, simp only [hγ'], intro h, convert h, ext, convert iff.rfl, rw [with_zero.coe_min, mul_assoc], refl }, { intros y ineq, apply Hγ, rw set.mem_set_of_eq, -- I sort of lost that y is a unit, but fortunately, it is easy to prove it's not zero have : y ≠ 0, { intro hy, simp [hy] at ineq, exact lt_irrefl _ ineq.2 }, let yu := units.mk' this, change v ((yu : Kv) - (x : Kv)) < _ at ineq, convert top_div_ring_aux v ineq, apply congr_arg, congr, simp }, end, ..(by apply_instance : topological_ring (valued_ring K v)) }
1bb4604178911bbcbe1589435e530c898b1ed7d9
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/set/intervals.lean
61814df6b8de9a1ff1a334cc4c0335220acfcf92
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
11,989
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 Intervals Naming conventions: `i`: infinite `o`: open `c`: closed Each interval has the name `I` + letter for left side + letter for right side TODO: This is just the beginning; a lot of rules are missing -/ import algebra.order algebra.order_functions import tactic.tauto namespace set open set section intervals variables {α : Type*} [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} @[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 := ⟨λ h, lt_irrefl a h.1, λ h, false.elim h⟩ @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := ⟨λ h, h.2, λ h, ⟨le_refl _, h⟩⟩ @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := ⟨λ h, h.2, λ h, ⟨le_refl _, h⟩⟩ @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := ⟨λ h, lt_irrefl a h.1, λ h, false.elim h⟩ @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := ⟨λ h, lt_irrefl b h.2, λ h, false.elim h⟩ @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := ⟨λ h, lt_irrefl b h.2, λ h, false.elim h⟩ @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := ⟨λ h, h.1, λ h, ⟨h, le_refl _⟩⟩ @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := ⟨λ h, h.1, λ h, ⟨h, le_refl _⟩⟩ @[simp] lemma Ioo_eq_empty (h : b ≤ a) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_trans h₁ h₂) h @[simp] lemma Ico_eq_empty (h : b ≤ a) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_le_of_lt (lt_of_le_of_lt h₁ h₂) h @[simp] lemma Icc_eq_empty (h : b < a) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₁ h₂) h @[simp] lemma Ioc_eq_empty (h : b ≤ a) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨h₁, h₂⟩, not_lt_of_le (le_trans h₂ h) h₁ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ le_refl _ @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ le_refl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ le_refl _ lemma Iio_ne_empty [no_bot_order α] (a : α) : Iio a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_bot a) lemma Ioi_ne_empty [no_top_order α] (a : α) : Ioi a ≠ ∅ := ne_empty_iff_exists_mem.2 (no_top a) lemma Iic_ne_empty (b : α) : Iic b ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨b, le_refl b⟩ lemma Ici_ne_empty (a : α) : Ici a ≠ ∅ := ne_empty_iff_exists_mem.2 ⟨a, le_refl a⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h (le_refl _) lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo (le_refl _) h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, lt_of_lt_of_le hx₂ h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h (le_refl _) lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico (le_refl _) h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨le_trans h₁ hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h (le_refl _) lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc (le_refl _) h lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨lt_of_le_of_lt h₁ hx₁, le_trans hx₂ h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h (le_refl _) lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc (le_refl _) h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left $ lt_of_lt_of_le h₁ lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, lt_of_le_of_lt h₂ h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right 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 : Ioo a b ⊆ Iio b := λ x, and.right lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨le_trans h hx, lt_of_le_of_lt hx' h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_refl _, h₁⟩).1, (h ⟨h₁, le_refl _⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨lt_of_lt_of_le h hx, le_trans hx' h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, lt_of_le_of_lt hx' h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, lt_of_lt_of_le h hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_refl _⟩, λ h x ⟨hx, hx'⟩, le_trans hx' h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_refl _, h₁⟩, λ h x ⟨hx, hx'⟩, le_trans h hx⟩ end intervals section partial_order variables {α : Type*} [partial_order α] {a b : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] lemma Ico_diff_Ioo_eq_singleton (h : a < b) : Ico a b \ Ioo a b = {a} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact eq.symm (classical.by_contradiction (λ ne, h (lt_of_le_of_ne ax ne) xb)) }, { rintro rfl, exact ⟨⟨le_refl _, h⟩, (lt_irrefl x).elim⟩ } end lemma Icc_diff_Ico_eq_singleton (h : a ≤ b) : Icc a b \ Ico a b = {b} := set.ext $ λ x, begin simp, split, { rintro ⟨⟨ax, xb⟩, h⟩, exact classical.by_contradiction (λ ne, h ax (lt_of_le_of_ne xb ne)) }, { rintro rfl, exact ⟨⟨h, le_refl _⟩, λ _, lt_irrefl x⟩ } end end partial_order section linear_order variables {α : Type*} [linear_order α] {a a₁ a₂ b b₁ b₂ : α} lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, let ⟨x, h₁, h₂⟩ := dense h in eq_empty_iff_forall_not_mem.1 eq x ⟨h₁, h₂⟩, Ioo_eq_empty⟩ lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ b ≤ a := ⟨λ eq, le_of_not_lt $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Ico_eq_empty⟩ lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ b < a := ⟨λ eq, lt_of_not_ge $ λ h, eq_empty_iff_forall_not_mem.1 eq a ⟨le_refl _, h⟩, Icc_eq_empty⟩ 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_refl _, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨le_of_lt this.2, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases dense h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := lt_trans (h ⟨xa, xb⟩).1 xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := lt_trans xa (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 (lt_of_le_of_lt h₁ $ lt_of_lt_of_le h h₂)).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ end linear_order section decidable_linear_order variables {α : Type*} [decidable_linear_order α] {a a₁ a₂ b b₁ b₂ : α} @[simp] lemma Ico_diff_Iio {a b c : α} : Ico a b \ Iio c = Ico (max a c) b := set.ext $ by simp [Ico, Iio, iff_def, max_le_iff] {contextual:=tt} @[simp] lemma Ico_inter_Iio {a b c : α} : Ico a b ∩ Iio c = Ico a (min b c) := set.ext $ by simp [Ico, Iio, iff_def, lt_min_iff] {contextual:=tt} lemma Ioo_inter_Ioo {a b c d : α} : Ioo a b ∩ Ioo c d = Ioo (max a c) (min b d) := set.ext $ by simp [iff_def, Ioo, lt_min_iff, max_lt_iff] {contextual := tt} end decidable_linear_order section ordered_comm_group variables {α : Type*} [ordered_comm_group α] lemma image_neg_Iio (r : α) : image (λz, -z) (Iio r) = Ioi (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [mem_Ioi, neg_lt_neg_iff], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iio], use -z, simp [hz], exact neg_lt.1 hz } end lemma image_neg_Iic (r : α) : image (λz, -z) (Iic r) = Ici (-r) := begin apply set.ext, intros z, apply iff.intro, { intros hz, apply exists.elim hz, intros z' hz', rw [←hz'.2], simp only [neg_le_neg_iff, mem_Ici], exact hz'.1 }, { intros hz, simp only [mem_image, mem_Iic], use -z, simp [hz], exact neg_le.1 hz } end end ordered_comm_group end set
74be7e3d3e362a00ef4d268d80fc6a0773c25794
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/algebra/category/CommRing/basic.lean
1952cb6b49545bb6e2fdf8246a0066394598d207
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
6,001
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov -/ import algebra.category.Group import category_theory.fully_faithful import algebra.ring import data.int.basic /-! # Category instances for semiring, ring, comm_semiring, and comm_ring. We introduce the bundled categories: * `SemiRing` * `Ring` * `CommSemiRing` * `CommRing` along with the relevant forgetful functors between them. ## Implementation notes See the note [locally reducible category instances]. -/ universes u v open category_theory /-- The category of semirings. -/ def SemiRing : Type (u+1) := bundled semiring namespace SemiRing /-- Construct a bundled SemiRing from the underlying type and typeclass. -/ def of (R : Type u) [semiring R] : SemiRing := bundled.of R local attribute [reducible] SemiRing instance : has_coe_to_sort SemiRing := infer_instance instance (R : SemiRing) : semiring R := R.str instance bundled_hom : bundled_hom @ring_hom := ⟨@ring_hom.to_fun, @ring_hom.id, @ring_hom.comp, @ring_hom.coe_inj⟩ instance : concrete_category SemiRing := infer_instance instance has_forget_to_Mon : has_forget₂ SemiRing Mon := bundled_hom.mk_has_forget₂ @semiring.to_monoid (λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl) instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon := -- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category { forget₂ := { obj := λ R, AddCommMon.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end SemiRing /-- The category of rings. -/ def Ring : Type (u+1) := induced_category SemiRing (bundled.map @ring.to_semiring) namespace Ring /-- Construct a bundled Ring from the underlying type and typeclass. -/ def of (R : Type u) [ring R] : Ring := bundled.of R local attribute [reducible] Ring instance : has_coe_to_sort Ring := infer_instance instance (R : Ring) : ring R := R.str instance : concrete_category Ring := infer_instance instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := infer_instance instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup := -- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category { forget₂ := { obj := λ R, AddCommGroup.of R, map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } } end Ring /-- The category of commutative semirings. -/ def CommSemiRing : Type (u+1) := induced_category SemiRing (bundled.map comm_semiring.to_semiring) namespace CommSemiRing /-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R local attribute [reducible] CommSemiRing instance : has_coe_to_sort CommSemiRing := infer_instance instance (R : CommSemiRing) : comm_semiring R := R.str instance : concrete_category CommSemiRing := infer_instance instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := infer_instance /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon := has_forget₂.mk' (λ R : CommSemiRing, CommMon.of R) (λ R, rfl) (λ R₁ R₂ f, f.to_monoid_hom) (by tidy) end CommSemiRing /-- The category of commutative rings. -/ def CommRing : Type (u+1) := induced_category Ring (bundled.map comm_ring.to_ring) namespace CommRing /-- Construct a bundled CommRing from the underlying type and typeclass. -/ def of (R : Type u) [comm_ring R] : CommRing := bundled.of R local attribute [reducible] CommRing instance : has_coe_to_sort CommRing := infer_instance instance (R : CommRing) : comm_ring R := R.str instance : concrete_category CommRing := infer_instance instance has_forget_to_Ring : has_forget₂ CommRing Ring := infer_instance /-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/ instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing := has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy) end CommRing namespace ring_equiv variables {X Y : Type u} /-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/ @[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } /-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/ @[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) : CommRing.of X ≅ CommRing.of Y := { hom := e.to_ring_hom, inv := e.symm.to_ring_hom } end ring_equiv namespace category_theory.iso /-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/ def Ring_iso_to_ring_equiv {X Y : Ring.{u}} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. /-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/ def CommRing_iso_to_ring_equiv {X Y : CommRing.{u}} (i : X ≅ Y) : X ≃+* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy }. end category_theory.iso /-- ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/ def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] : (X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) := { hom := λ e, e.to_Ring_iso, inv := λ i, i.Ring_iso_to_ring_equiv, } /-- ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms in `CommRing`. -/ def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] : (X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) := { hom := λ e, e.to_CommRing_iso, inv := λ i, i.CommRing_iso_to_ring_equiv, }
945fe11de788a11f27cb50308e2f423e6812caae
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/aevb/mnist.lean
66edba159e12b91e3d83c51354396084b2279cbf
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
2,892
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Script to run AEVB on MNIST. -/ import system.io ..program ..prove_model_ok .util .prog ..run_utils namespace certigrad namespace aevb open io meta def load_mnist_dataset [io.interface] (mnist_dir : string) (a : arch) : io (T [a^.n_in, 60000] × T [60000]) := if H : 784 = a^.n_in then do (x, y) ← T.read_mnist mnist_dir, return $ eq.rec_on H (x^.transpose, y) else io.fail "architecture not compatible with mnist" meta def train_aevb_on_mnist [io.interface] (a : arch) (num_iters seed : ℕ) (mnist_dir run_dir : string) : io unit := do put_str_ln ("reading mnist data from '" ++ mnist_dir ++ "' ..."), (train_data, train_labels) ← load_mnist_dataset mnist_dir a, x_data ← return $ T.get_col_range a^.n_x train_data 0, put_str_ln ("creating directory to store run data at '" ++ run_dir ++ "' ..."), mkdir run_dir, put_str_ln "building graph...", g ← return $ reparam (integrate_kl $ naive_aevb a x_data), put_str_ln "initializing the weights...", (ws, rng₁) ← return $ sample_initial_weights g^.targets (RNG.mk seed), put_str_ln "training...", num_batches ← return (a.n_x / a.bs), (θ, astate, rng₂) ← run.run_iters run_dir g train_data a^.bs num_iters ws optim.adam.init_state rng₁, put_str_ln "writing results...", tvec.write_all run_dir "params_" ".ssv" g^.targets θ, put_str_ln "(done)" def mk_run_dir_name (dir : string) (a : arch) (num_iters seed : ℕ) : string := dir ++ "/run_bs=" ++ to_string a^.bs ++ "_nz=" ++ to_string a^.nz ++ "_nh=" ++ to_string a^.nd ++ "_iters=" ++ to_string num_iters ++ "_seed=" ++ to_string seed set_option profiler true ------------------------------------ -- Script to train an AEVB on MNIST. ------------------------------------ -- 1. Create a directory 'mnist_dir' -- 2. Download, uncompress, and put in 'mnist_dir': -- http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz -- http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz -- 3. Create a directory for 'run_dir' to store data from different runs. -- 4. Change 'mnist_dir' and 'run_dir' below accordingly. -- 5. Uncomment the 'run_cmd tactic.run_io @train' command below to run it. meta def train_core [io.interface] (a : arch) (num_iters seed : ℕ) : io unit := let mnist_dir : string := "/home/dselsam/projects/mnist" in let run_dir : string := mk_run_dir_name "/home/dselsam/projects/mnist/runs" a num_iters seed in train_aevb_on_mnist a num_iters seed mnist_dir run_dir meta def train [io.interface] : io unit := let a : arch := {bs := 250, n_x := 55000, n_in := 784, nz := 30, ne := 1000, nd := 1000} in let num_iters : ℕ := 100 in let seed : ℕ := 100 in train_core a num_iters seed -- run_cmd tactic.run_io @train end aevb end certigrad
51cf6d125ebdc1e2ef1ba57e00b85e151fca718b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Notation.lean
4771a3e138ef87036e678c16db1469f6eee1371e
[ "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
7,774
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Syntax import Lean.Elab.AuxDef import Lean.Elab.BuiltinNotation namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command /-- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id (kind := `term) (isPseudoKind := true) else stx | _ => match stx with | Syntax.node i k args => Syntax.node i k (args.map (antiquote vars)) | stx => stx def addInheritDocDefault (rhs : Term) (attrs? : Option (TSepArray ``attrInstance ",")) : Option (TSepArray ``attrInstance ",") := attrs?.map fun attrs => match rhs with | `($f:ident $_args*) | `($f:ident) => attrs.getElems.map fun stx => Unhygienic.run do if let `(attrInstance| $attr:ident) := stx then if attr.getId.eraseMacroScopes == `inherit_doc then return ← `(attrInstance| $attr:ident $f:ident) pure ⟨stx⟩ | _ => attrs /-- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem : TSyntax ``notationItem → MacroM (TSyntax `stx) | `(notationItem| $_:ident$[:$prec?]?) => `(stx| term $[:$prec?]?) | `(notationItem| $s:str) => `(stx| $s:str) | _ => Macro.throwUnsupported /-- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then return mkAntiquotNode stx[0] (kind := `term) (isPseudoKind := true) else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported def removeParenthesesAux (parens body : Syntax) : Syntax := match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with | .original lead _ _ _, .original _ pos trail pos', .original endLead endPos _ endPos', .original _ _ endTrail _ => body.setHeadInfo (.original lead pos trail pos') |>.setTailInfo (.original endLead endPos endTrail endPos') | _, _, _, _ => body partial def removeParentheses (stx : Syntax) : MacroM Syntax := do match stx with | `(($e)) => pure $ removeParenthesesAux stx (←removeParentheses $ (←Term.expandCDot? e).getD e) | _ => match stx with | .node info kind args => pure $ .node info kind (←args.mapM removeParentheses) | _ => pure stx partial def hasDuplicateAntiquot (stxs : Array Syntax) : Bool := Id.run do let mut seen := NameSet.empty for stx in stxs do for node in Syntax.topDown stx true do if node.isAntiquot then let ident := node.getAntiquotTerm.getId if seen.contains ident then return true else seen := seen.insert ident pure false /-- Try to derive an unexpander from a notation. The notation must be of the form `notation ... => c body` where `c` is a declaration in the current scope and `body` any syntax that contains each variable from the LHS at most once. -/ def mkUnexpander (attrKind : TSyntax ``attrKind) (pat qrhs : Term) : OptionT MacroM Syntax := do let (c, args) ← match qrhs with | `($c:ident $args*) => pure (c, args) | `($c:ident) => pure (c, #[]) | _ => failure let [(c, [])] ← Macro.resolveGlobalName c.getId | failure /- Try to remove all non semantic parenthesis. Since the parenthesizer runs after appUnexpanders we should not match on parenthesis that the user syntax inserted here for example the right hand side of: notation "{" x "|" p "}" => setOf (fun x => p) Should be matched as: setOf fun x => p -/ let args ← liftM <| args.mapM removeParentheses /- The user could mention the same antiquotation from the lhs multiple times on the rhs, this heuristic does not support this. -/ guard !hasDuplicateAntiquot args -- replace head constant with antiquotation so we're not dependent on the exact pretty printing of the head -- The reference is attached to the syntactic representation of the called function itself, not the entire function application let lhs ← `($$f:ident) let lhs := Syntax.mkApp lhs (.mk args) -- allow over-application, avoiding nested `app` nodes let lhsWithMoreArgs := flattenApp (← `($lhs $$moreArgs*)) let patWithMoreArgs := flattenApp (← `($pat $$moreArgs*)) `(@[$attrKind app_unexpander $(mkIdent c)] aux_def unexpand $(mkIdent c) : Lean.PrettyPrinter.Unexpander := fun | `($lhs) => withRef f `($pat) -- must be a separate case as the LHS and RHS above might not be `app` nodes | `($lhsWithMoreArgs) => withRef f `($patWithMoreArgs) | _ => throw ()) where -- NOTE: we consider only one nesting level here flattenApp : Term → Term | stx@`($f $xs*) => match f with | `($f' $xs'*) => Syntax.mkApp f' (xs' ++ xs) | _ => stx | stx => stx private def expandNotationAux (ref : Syntax) (currNamespace : Name) (doc? : Option (TSyntax ``docComment)) (attrs? : Option (TSepArray ``attrInstance ",")) (attrKind : TSyntax ``attrKind) (prec? : Option Prec) (name? : Option Ident) (prio? : Option Prio) (items : Array (TSyntax ``notationItem)) (rhs : Term) : MacroM Syntax := do let prio ← evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => addMacroScopeIfLocal (← mkNameFromParserSyntax `term (mkNullNode syntaxParts)) attrKind -- build macro rules let vars := items.filter fun item => item.raw.getKind == ``identPrec let vars := vars.map fun var => var.raw[0] let qrhs := ⟨antiquote vars rhs⟩ let attrs? := addInheritDocDefault rhs attrs? let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat : Term := ⟨mkNode fullName patArgs⟩ let stxDecl ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind syntax $[: $prec?]? (name := $(name?.getD (mkIdent name))) (priority := $(quote prio)) $[$syntaxParts]* : $cat) let macroDecl ← `(macro_rules | `($pat) => ``($qrhs)) let macroDecls ← if isLocalAttrKind attrKind then -- Make sure the quotation pre-checker takes section variables into account for local notation. `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) else pure ⟨mkNullNode #[macroDecl]⟩ match (← mkUnexpander attrKind pat qrhs |>.run) with | some delabDecl => return mkNullNode #[stxDecl, macroDecls, delabDecl] | none => return mkNullNode #[stxDecl, macroDecls] @[builtin_macro Lean.Parser.Command.notation] def expandNotation : Macro | stx@`($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind notation $[: $prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx (← Macro.getCurrNamespace) doc? attrs? attrKind prec? name? prio? items rhs | _ => Macro.throwUnsupported end Lean.Elab.Command
53b2e99225c4465c4673f5f51c479fb259245004
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/opposites.lean
f77dd3381a0d1cc2271405f151e595ac99c0afb6
[ "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
9,650
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.types import category_theory.equivalence import data.opposite universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open opposite variables {C : Type u₁} section has_hom variables [has_hom.{v₁} C] /-- The hom types of the opposite of a category (or graph). As with the objects, we'll make this irreducible below. Use `f.op` and `f.unop` to convert between morphisms of C and morphisms of Cᵒᵖ. -/ instance has_hom.opposite : has_hom Cᵒᵖ := { hom := λ X Y, unop Y ⟶ unop X } def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f attribute [irreducible] has_hom.opposite lemma has_hom.hom.op_inj {X Y : C} : function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg has_hom.hom.unop H lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg has_hom.hom.op H @[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end has_hom variables [category.{v₁} C] instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl /-- The functor from the double-opposite of a category to the underlying category. -/ @[simps] def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } /-- The functor from a category to its double-opposite. -/ @[simps] def unop_unop : C ⥤ Cᵒᵖᵒᵖ := { obj := λ X, op (op X), map := λ X Y f, f.op.op } /-- The double opposite category is equivalent to the original. -/ @[simps] def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C := { functor := op_op, inverse := unop_unop, unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ), counit_iso := iso.refl (unop_unop ⋙ op_op) } def is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f := { inv := (inv (f.op)).unop, hom_inv_id' := has_hom.hom.op_inj (by simp), inv_hom_id' := has_hom.hom.op_inj (by simp) } namespace functor section variables {D : Type u₂} [category.{v₂} D] variables {C D} @[simps] protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } @[simps] protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } /-- The isomorphism between `F.op.unop` and `F`. -/ def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.unop.op` and `F`. -/ def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) variables (C D) @[simps] definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, has_hom.hom.unop_inj (α.unop.naturality f.unop).symm } } @[simps] definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, has_hom.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, has_hom.hom.op_inj $ (α.naturality f.op).symm } } -- TODO show these form an equivalence variables {C D} @[simps] protected definition left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D := { obj := λ X, unop (F.obj (unop X)), map := λ X Y f, (F.map f.unop).unop } @[simps] protected definition right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (op X)), map := λ X Y f, (F.map f.op).op } -- TODO show these form an equivalence instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj $ by simpa using map_injective F (has_hom.hom.op_inj h) } /-- If F is faithful then the right_op of F is also faithful. -/ instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op := { map_injective' := λ X Y f g h, has_hom.hom.op_inj (map_injective F (has_hom.hom.op_inj h)) } /-- If F is faithful then the left_op of F is also faithful. -/ instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op := { map_injective' := λ X Y f g h, has_hom.hom.unop_inj (map_injective F (has_hom.hom.unop_inj h)) } end end functor namespace nat_trans variables {D : Type u₂} [category.{v₂} D] section variables {F G : C ⥤ D} local attribute [semireducible] has_hom.opposite @[simps] protected definition op (α : F ⟶ G) : G.op ⟶ F.op := { app := λ X, (α.app (unop X)).op, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl @[simps] protected definition unop (α : F.op ⟶ G.op) : G ⟶ F := { app := λ X, (α.app (op X)).unop, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this, refl, end } @[simp] lemma unop_id (F : C ⥤ D) : nat_trans.unop (𝟙 F.op) = 𝟙 F := rfl end section variables {F G : C ⥤ Dᵒᵖ} local attribute [semireducible] has_hom.opposite protected definition left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op := { app := λ X, (α.app (unop X)).unop, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma left_op_app (α : F ⟶ G) (X) : (nat_trans.left_op α).app X = (α.app (unop X)).unop := rfl protected definition right_op (α : F.left_op ⟶ G.left_op) : G ⟶ F := { app := λ X, (α.app (op X)).op, naturality' := begin intros X Y f, have := congr_arg has_hom.hom.op (α.naturality f.op), dsimp at this, erw this end } @[simp] lemma right_op_app (α : F.left_op ⟶ G.left_op) (X) : (nat_trans.right_op α).app X = (α.app (op X)).op := rfl end end nat_trans namespace iso variables {X Y : C} protected definition op (α : X ≅ Y) : op Y ≅ op X := { hom := α.hom.op, inv := α.inv.op, hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id, inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id } @[simp] lemma op_hom {α : X ≅ Y} : α.op.hom = α.hom.op := rfl @[simp] lemma op_inv {α : X ≅ Y} : α.op.inv = α.inv.op := rfl end iso namespace nat_iso variables {D : Type u₂} [category.{v₂} D] variables {F G : C ⥤ D} /-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural isomorphism between the original functors `F ≅ G`. -/ protected definition op (α : F ≅ G) : G.op ≅ F.op := { hom := nat_trans.op α.hom, inv := nat_trans.op α.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end } @[simp] lemma op_hom (α : F ≅ G) : (nat_iso.op α).hom = nat_trans.op α.hom := rfl @[simp] lemma op_inv (α : F ≅ G) : (nat_iso.op α).inv = nat_trans.op α.inv := rfl /-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism between the opposite functors `F.op ≅ G.op`. -/ protected definition unop (α : F.op ≅ G.op) : G ≅ F := { hom := nat_trans.unop α.hom, inv := nat_trans.unop α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } @[simp] lemma unop_hom (α : F.op ≅ G.op) : (nat_iso.unop α).hom = nat_trans.unop α.hom := rfl @[simp] lemma unop_inv (α : F.op ≅ G.op) : (nat_iso.unop α).inv = nat_trans.unop α.inv := rfl end nat_iso /-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building adjunctions. Note that this (definitionally) gives variants ``` def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) := op_equiv _ _ def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) := op_equiv _ _ def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) := op_equiv _ _ ``` -/ def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) := { to_fun := λ f, f.unop, inv_fun := λ g, g.op, left_inv := λ _, rfl, right_inv := λ _, rfl } -- These two are made by hand rather than by simps because simps generates -- `(op_equiv _ _).to_fun f = ...` rather than the coercion version. @[simp] lemma op_equiv_apply (A B : Cᵒᵖ) (f : A ⟶ B) : op_equiv _ _ f = f.unop := rfl @[simp] lemma op_equiv_symm_apply (A B : Cᵒᵖ) (f : B.unop ⟶ A.unop) : (op_equiv _ _).symm f = f.op := rfl end category_theory
b00efc60088bf16ad7f278f26a1337115e505ca0
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/omega/lin_comb.lean
b263c71427841488d29a293e852d01e4b11fa7be
[ "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,161
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Linear combination of constraints. -/ import tactic.omega.clause namespace omega /-- Linear combination of constraints. The second argument is the list of constraints, and the first argument is the list of conefficients by which the constraints are multiplied -/ @[simp] def lin_comb : list nat → list term → term | [] [] := ⟨0,[]⟩ | [] (_::_) := ⟨0,[]⟩ | (_::_) [] := ⟨0,[]⟩ | (n::ns) (t::ts) := term.add (t.mul ↑n) (lin_comb ns ts) lemma lin_comb_holds {v : nat → int} : ∀ {ts} ns, (∀ t ∈ ts, 0 ≤ term.val v t) → (0 ≤ (lin_comb ns ts).val v) | [] [] h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | [] (_::_) h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | (_::_) [] h := by simp only [add_zero, term.val, lin_comb, coeffs.val_nil] | (t::ts) (n::ns) h := begin have : 0 ≤ ↑n * term.val v t + term.val v (lin_comb ns ts), { apply add_nonneg, { apply mul_nonneg, apply int.coe_nat_nonneg, apply h _ (or.inl rfl) }, { apply lin_comb_holds, apply list.forall_mem_of_forall_mem_cons h } }, simpa only [lin_comb, term.val_mul, term.val_add], end /-- `unsat_lin_comb ns ts` asserts that the linear combination `lin_comb ns ts` is unsatisfiable -/ def unsat_lin_comb (ns : list nat) (ts : list term) : Prop := (lin_comb ns ts).fst < 0 ∧ ∀ x ∈ (lin_comb ns ts).snd, x = (0 : int) lemma unsat_lin_comb_of (ns : list nat) (ts : list term) : (lin_comb ns ts).fst < 0 → (∀ x ∈ (lin_comb ns ts).snd, x = (0 : int)) → unsat_lin_comb ns ts := by {intros h1 h2, exact ⟨h1,h2⟩} lemma unsat_of_unsat_lin_comb (ns : list nat) (ts : list term) : (unsat_lin_comb ns ts) → clause.unsat ([], ts) := begin intros h1 h2, cases h2 with v h2, have h3 := lin_comb_holds ns h2.right, cases h1 with hl hr, cases (lin_comb ns ts) with b as, unfold term.val at h3, rw [coeffs.val_eq_zero hr, add_zero, ← not_lt] at h3, apply h3 hl end end omega
f430d3728aaddb8b6be8cba21cabb26195eaad2c
ddac945a109b79a5c5b9b3b94ecd42f87d9a8e00
/lean/leftpad.lean
8bb8f9c00b448fd36d2c54197931ffde11fa35c6
[ "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
cipher1024/lets-prove-leftpad
f21a2caa0d7d7c7881ebab9e8a8d281e01e2f2f0
a79d7f5c01817ab519f9b489436667d526e5a968
refs/heads/master
1,584,568,854,244
1,527,612,383,000
1,527,612,383,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,632
lean
import data.list.basic section left_pad variables {α : Type*} open nat lemma list.cons_repeat (c : α) : Π (n : ℕ), c :: list.repeat c n = list.repeat c n ++ [c] := by { intro, symmetry, induction n ; simp *, } lemma list.take_append (xs ys : list α) (n : ℕ) (h : xs.length = n) : (xs ++ ys).take n = xs := by { subst n, induction xs ; simp! [add_one,*], } lemma list.drop_append (xs ys : list α) (n : ℕ) (h : xs.length = n) : (xs ++ ys).drop n = ys := by { subst n, induction xs ; simp! [add_one,*], } def left_pad_aux (c : α) : ℕ → list α → list α | 0 xs := xs | (succ n) xs := left_pad_aux n (c :: xs) def left_pad (c : α) (n : ℕ) (x : list α) : list α := left_pad_aux c (n - x.length) x variables (c : α) (n : ℕ) (x : list α) lemma left_pad_def : left_pad c n x = list.repeat c (n - x.length) ++ x := begin simp [left_pad], generalize : (n - list.length x) = k, induction k generalizing x ; simp! [add_one,add_succ,succ_add,list.cons_repeat,*], end lemma length_left_pad : (left_pad c n x).length = max n x.length := begin simp [left_pad_def], cases le_total n x.length with Hk Hk, { rw max_eq_right Hk, rw ← nat.sub_eq_zero_iff_le at Hk, simp *, }, { simp [max_eq_left Hk], rw [← nat.add_sub_assoc Hk,nat.add_sub_cancel_left] }, end lemma left_pad_prefix : ∀ c' ∈ (left_pad c n x).take (n - x.length), c' = c := by { rw [left_pad_def,list.take_append] , { intro, apply list.eq_of_mem_repeat }, simp! , } lemma left_pad_suffix : (left_pad c n x).drop (n - x.length) = x := by simp [left_pad_def,list.drop_append] end left_pad
2e3432fbed4ffaa09dfa8dfab81a9d6eb2160aec
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/System/ST.lean
cad11f39bff651af421893e3ca6c3f5e45accbc8
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,435
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Classical import Init.Control.EState import Init.Control.Reader def EST (ε : Type) (σ : Type) : Type → Type := EStateM ε σ abbrev ST (σ : Type) := EST Empty σ instance (ε σ : Type) : Monad (EST ε σ) := inferInstanceAs (Monad (EStateM _ _)) instance (ε σ : Type) : MonadExceptOf ε (EST ε σ) := inferInstanceAs (MonadExceptOf ε (EStateM _ _)) instance {ε σ : Type} {α : Type} [Inhabited ε] : Inhabited (EST ε σ α) := inferInstanceAs (Inhabited (EStateM _ _ _)) instance (σ : Type) : Monad (ST σ) := inferInstanceAs (Monad (EST _ _)) -- Auxiliary class for inferring the "state" of `EST` and `ST` monads class STWorld (σ : outParam Type) (m : Type → Type) instance {σ m n} [MonadLift m n] [STWorld σ m] : STWorld σ n := ⟨⟩ instance {ε σ} : STWorld σ (EST ε σ) := ⟨⟩ @[noinline, nospecialize] def runEST {ε α : Type} (x : forall (σ : Type), EST ε σ α) : Except ε α := match x Unit () with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex @[noinline, nospecialize] def runST {α : Type} (x : forall (σ : Type), ST σ α) : α := match x Unit () with | EStateM.Result.ok a _ => a | EStateM.Result.error ex _ => nomatch ex instance {ε σ} : MonadLift (ST σ) (EST ε σ) := ⟨fun x s => match x s with | EStateM.Result.ok a s => EStateM.Result.ok a s | EStateM.Result.error ex _ => nomatch ex⟩ namespace ST /- References -/ constant RefPointed : PointedType.{0} structure Ref (σ : Type) (α : Type) : Type where ref : RefPointed.type h : Nonempty α instance {σ α} [Inhabited α] : Inhabited (Ref σ α) where default := { ref := RefPointed.val, h := Nonempty.intro arbitrary } namespace Prim set_option pp.all true /- Auxiliary definition for showing that `ST σ α` is inhabited when we have a `Ref σ α` -/ private noncomputable def inhabitedFromRef {σ α} (r : Ref σ α) : ST σ α := let inh : Inhabited α := Classical.inhabitedOfNonempty r.h pure arbitrary @[extern "lean_st_mk_ref"] constant mkRef {σ α} (a : α) : ST σ (Ref σ α) := pure { ref := RefPointed.val, h := Nonempty.intro a } @[extern "lean_st_ref_get"] constant Ref.get {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_set"] constant Ref.set {σ α} (r : @& Ref σ α) (a : α) : ST σ Unit @[extern "lean_st_ref_swap"] constant Ref.swap {σ α} (r : @& Ref σ α) (a : α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_take"] unsafe constant Ref.take {σ α} (r : @& Ref σ α) : ST σ α := inhabitedFromRef r @[extern "lean_st_ref_ptr_eq"] constant Ref.ptrEq {σ α} (r1 r2 : @& Ref σ α) : ST σ Bool @[inline] unsafe def Ref.modifyUnsafe {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.take r Ref.set r (f v) @[inline] unsafe def Ref.modifyGetUnsafe {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.take r let (b, a) := f v Ref.set r a pure b @[implementedBy Ref.modifyUnsafe] def Ref.modify {σ α : Type} (r : Ref σ α) (f : α → α) : ST σ Unit := do let v ← Ref.get r Ref.set r (f v) @[implementedBy Ref.modifyGetUnsafe] def Ref.modifyGet {σ α β : Type} (r : Ref σ α) (f : α → β × α) : ST σ β := do let v ← Ref.get r let (b, a) := f v Ref.set r a pure b end Prim section variables {σ : Type} {m : Type → Type} [Monad m] [MonadLiftT (ST σ) m] @[inline] def mkRef {α : Type} (a : α) : m (Ref σ α) := liftM <| Prim.mkRef a @[inline] def Ref.get {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.get r @[inline] def Ref.set {α : Type} (r : Ref σ α) (a : α) : m Unit := liftM <| Prim.Ref.set r a @[inline] def Ref.swap {α : Type} (r : Ref σ α) (a : α) : m α := liftM <| Prim.Ref.swap r a @[inline] unsafe def Ref.take {α : Type} (r : Ref σ α) : m α := liftM <| Prim.Ref.take r @[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref σ α) : m Bool := liftM <| Prim.Ref.ptrEq r1 r2 @[inline] def Ref.modify {α : Type} (r : Ref σ α) (f : α → α) : m Unit := liftM <| Prim.Ref.modify r f @[inline] def Ref.modifyGet {α : Type} {β : Type} (r : Ref σ α) (f : α → β × α) : m β := liftM <| Prim.Ref.modifyGet r f end end ST
8d1d2500a01a91f683fd16f444db061c9a8bcb21
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/sqrt.lean
1be8fc95f22910920197b5137a31a114219adc50
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
7,196
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import data.int.basic /-! # Square root of natural numbers An efficient binary implementation of a (`sqrt n`) function that returns `s` such that ``` s*s ≤ n ≤ s*s + s + s ``` -/ namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp only [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end /-- Auxiliary function for `nat.sqrt`. See e.g. <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> -/ def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ @[pp_nodot] def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 := have b0:_, from ne_of_gt (pow_pos (show 0 < 2, from dec_trivial) m), nat.mul_ne_zero b0 b0, have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [nat.sub_lt_right_iff_lt_add h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_assoc, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply nat.sub_eq_of_eq_add, rw [← add_assoc, (_ : r*r + _ = _)], exact (nat.add_sub_cancel' hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intro h; simp; [exact ⟨h₁, h⟩, exact ⟨h, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intro h, { have := sqrt_aux_is_sqrt m r h₁ h, simpa [pow_succ, mul_comm, mul_assoc] }, { rw [pow_succ', mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) h h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, λ e, e.symm ▸ rfl⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (mul_le_mul_right _ _) _; exact le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ end nat
fdd3bc32c9c93d08c19ef0ac950dde75cbf4b226
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/ramification_inertia.lean
25762372a3867e05ed81fa168ffe5631cc18a14a
[ "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
7,504
lean
/- Copyright (c) 2022 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.is_prime_pow import field_theory.separable import linear_algebra.free_module.finite.rank import linear_algebra.free_module.pid import linear_algebra.matrix.nonsingular_inverse import ring_theory.dedekind_domain.ideal import ring_theory.localization.module /-! # Ramification index and inertia degree Given `P : ideal S` lying over `p : ideal R` for the ring extension `f : R →+* S` (assuming `P` and `p` are prime or maximal where needed), the **ramification index** `ideal.ramification_idx f p P` is the multiplicity of `P` in `map f p`, and the **inertia degree** `ideal.inertia_deg f p P` is the degree of the field extension `(S / P) : (R / p)`. ## TODO (#12287) The main theorem `ideal.sum_ramification_inertia` states that for all coprime `P` lying over `p`, `Σ P, ramification_idx f p P * inertia_deg f p P` equals the degree of the field extension `Frac(S) : Frac(R)`. ## Implementation notes Often the above theory is set up in the case where: * `R` is the ring of integers of a number field `K`, * `L` is a finite separable extension of `K`, * `S` is the integral closure of `R` in `L`, * `p` and `P` are maximal ideals, * `P` is an ideal lying over `p` We will try to relax the above hypotheses as much as possible. -/ namespace ideal universes u v variables {R : Type u} [comm_ring R] variables {S : Type v} [comm_ring S] (f : R →+* S) variables (p : ideal R) (P : ideal S) open finite_dimensional open unique_factorization_monoid section dec_eq open_locale classical /-- The ramification index of `P` over `p` is the largest exponent `n` such that `p` is contained in `P^n`. In particular, if `p` is not contained in `P^n`, then the ramification index is 0. If there is no largest such `n` (e.g. because `p = ⊥`), then `ramification_idx` is defined to be 0. -/ noncomputable def ramification_idx : ℕ := Sup {n | map f p ≤ P ^ n} variables {f p P} lemma ramification_idx_eq_find (h : ∃ n, ∀ k, map f p ≤ P ^ k → k ≤ n) : ramification_idx f p P = nat.find h := nat.Sup_def h lemma ramification_idx_eq_zero (h : ∀ n : ℕ, ∃ k, map f p ≤ P ^ k ∧ n < k) : ramification_idx f p P = 0 := dif_neg (by push_neg; exact h) lemma ramification_idx_spec {n : ℕ} (hle : map f p ≤ P ^ n) (hgt : ¬ map f p ≤ P ^ (n + 1)) : ramification_idx f p P = n := begin have : ∀ (k : ℕ), map f p ≤ P ^ k → k ≤ n, { intros k hk, refine le_of_not_lt (λ hnk, _), exact hgt (hk.trans (ideal.pow_le_pow hnk)) }, rw ramification_idx_eq_find ⟨n, this⟩, { refine le_antisymm (nat.find_min' _ this) (le_of_not_gt (λ (h : nat.find _ < n), _)), obtain this' := nat.find_spec ⟨n, this⟩, exact h.not_le (this' _ hle) }, end lemma ramification_idx_lt {n : ℕ} (hgt : ¬ (map f p ≤ P ^ n)) : ramification_idx f p P < n := begin cases n, { simpa using hgt }, rw nat.lt_succ_iff, have : ∀ k, map f p ≤ P ^ k → k ≤ n, { refine λ k hk, le_of_not_lt (λ hnk, _), exact hgt (hk.trans (ideal.pow_le_pow hnk)) }, rw ramification_idx_eq_find ⟨n, this⟩, exact nat.find_min' ⟨n, this⟩ this end @[simp] lemma ramification_idx_bot : ramification_idx f ⊥ P = 0 := dif_neg $ not_exists.mpr $ λ n hn, n.lt_succ_self.not_le (hn _ (by simp)) @[simp] lemma ramification_idx_of_not_le (h : ¬ map f p ≤ P) : ramification_idx f p P = 0 := ramification_idx_spec (by simp) (by simpa using h) lemma ramification_idx_ne_zero {e : ℕ} (he : e ≠ 0) (hle : map f p ≤ P ^ e) (hnle : ¬ map f p ≤ P ^ (e + 1)): ramification_idx f p P ≠ 0 := by rwa ramification_idx_spec hle hnle lemma le_pow_of_le_ramification_idx {n : ℕ} (hn : n ≤ ramification_idx f p P) : map f p ≤ P ^ n := begin contrapose! hn, exact ramification_idx_lt hn end lemma le_pow_ramification_idx : map f p ≤ P ^ ramification_idx f p P := le_pow_of_le_ramification_idx (le_refl _) namespace is_dedekind_domain variables [is_domain S] [is_dedekind_domain S] lemma ramification_idx_eq_normalized_factors_count (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (hP0 : P ≠ ⊥) : ramification_idx f p P = (normalized_factors (map f p)).count P := begin have hPirr := (ideal.prime_of_is_prime hP0 hP).irreducible, refine ramification_idx_spec (ideal.le_of_dvd _) (mt ideal.dvd_iff_le.mpr _); rw [dvd_iff_normalized_factors_le_normalized_factors (pow_ne_zero _ hP0) hp0, normalized_factors_pow, normalized_factors_irreducible hPirr, normalize_eq, multiset.nsmul_singleton, ← multiset.le_count_iff_repeat_le], { exact (nat.lt_succ_self _).not_le }, end lemma ramification_idx_eq_factors_count (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (hP0 : P ≠ ⊥) : ramification_idx f p P = (factors (map f p)).count P := by rw [is_dedekind_domain.ramification_idx_eq_normalized_factors_count hp0 hP hP0, factors_eq_normalized_factors] lemma ramification_idx_ne_zero (hp0 : map f p ≠ ⊥) (hP : P.is_prime) (le : map f p ≤ P) : ramification_idx f p P ≠ 0 := begin have hP0 : P ≠ ⊥, { unfreezingI { rintro rfl }, have := le_bot_iff.mp le, contradiction }, have hPirr := (ideal.prime_of_is_prime hP0 hP).irreducible, rw is_dedekind_domain.ramification_idx_eq_normalized_factors_count hp0 hP hP0, obtain ⟨P', hP', P'_eq⟩ := exists_mem_normalized_factors_of_dvd hp0 hPirr (ideal.dvd_iff_le.mpr le), rwa [multiset.count_ne_zero, associated_iff_eq.mp P'_eq], end end is_dedekind_domain variables (f p P) local attribute [instance] ideal.quotient.field /-- The inertia degree of `P : ideal S` lying over `p : ideal R` is the degree of the extension `(S / P) : (R / p)`. We do not assume `P` lies over `p` in the definition; we return `0` instead. See `inertia_deg_algebra_map` for the common case where `f = algebra_map R S` and there is an algebra structure `R / p → S / P`. -/ noncomputable def inertia_deg [hp : p.is_maximal] : ℕ := if hPp : comap f P = p then @finrank (R ⧸ p) (S ⧸ P) _ _ $ @algebra.to_module _ _ _ _ $ ring_hom.to_algebra $ ideal.quotient.lift p (P^.quotient.mk^.comp f) $ λ a ha, quotient.eq_zero_iff_mem.mpr $ mem_comap.mp $ hPp.symm ▸ ha else 0 -- Useful for the `nontriviality` tactic using `comap_eq_of_scalar_tower_quotient`. @[simp] lemma inertia_deg_of_subsingleton [hp : p.is_maximal] [hQ : subsingleton (S ⧸ P)] : inertia_deg f p P = 0 := begin have := ideal.quotient.subsingleton_iff.mp hQ, unfreezingI { subst this }, exact dif_neg (λ h, hp.ne_top $ h.symm.trans comap_top) end @[simp] lemma inertia_deg_algebra_map [algebra R S] [algebra (R ⧸ p) (S ⧸ P)] [is_scalar_tower R (R ⧸ p) (S ⧸ P)] [hp : p.is_maximal] : inertia_deg (algebra_map R S) p P = finrank (R ⧸ p) (S ⧸ P) := begin nontriviality (S ⧸ P) using [inertia_deg_of_subsingleton, finrank_zero_of_subsingleton], have := comap_eq_of_scalar_tower_quotient (algebra_map (R ⧸ p) (S ⧸ P)).injective, rw [inertia_deg, dif_pos this], congr, refine algebra.algebra_ext _ _ (λ x', quotient.induction_on' x' $ λ x, _), change ideal.quotient.lift p _ _ (ideal.quotient.mk p x) = algebra_map _ _ (ideal.quotient.mk p x), rw [ideal.quotient.lift_mk, ← ideal.quotient.algebra_map_eq, ← is_scalar_tower.algebra_map_eq, ← ideal.quotient.algebra_map_eq, ← is_scalar_tower.algebra_map_apply] end end dec_eq end ideal
bfa0ef5bcad85a4619ae6bc72b71008aaf436785
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/interactive/hover.lean
cc9e69cac5be8bb8299d5e0275a334161bc3a1cc
[ "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
6,060
lean
import Lean example : True := by apply True.intro --^ textDocument/hover example : True := by simp [True.intro] --^ textDocument/hover example (n : Nat) : True := by match n with | Nat.zero => _ --^ textDocument/hover | n + 1 => _ /-- My tactic -/ macro "mytac" o:"only"? e:term : tactic => `(tactic| exact $e) example : True := by mytac only True.intro --^ textDocument/hover --^ textDocument/hover --^ textDocument/hover /-- My way better tactic -/ macro_rules | `(tactic| mytac $[only]? $e:term) => --^ textDocument/hover --^ textDocument/hover `(tactic| apply $e:term) --^ textDocument/hover --^ textDocument/hover example : True := by mytac only True.intro --^ textDocument/hover /-- My ultimate tactic -/ elab_rules : tactic | `(tactic| mytac $[only]? $e) => do Lean.Elab.Tactic.evalTactic (← `(tactic| refine $e)) example : True := by mytac only True.intro --^ textDocument/hover /-- My notation -/ macro (name := myNota) "mynota" e:term : term => pure e --^ textDocument/hover #check mynota 1 --^ textDocument/hover /-- My way better notation -/ macro_rules | `(mynota $e) => `(2 * $e) #check mynota 1 --^ textDocument/hover -- macro_rules take precedence over elab_rules for term/command, so use new syntax syntax "mynota'" term : term /-- My ultimate notation -/ elab_rules : term | `(mynota' $e) => `($e * $e) >>= (Lean.Elab.Term.elabTerm · none) #check mynota' 1 --^ textDocument/hover @[inherit_doc] infix:65 (name := myInfix) " >+< " => Nat.add --^ textDocument/hover --^ textDocument/hover #check 1 >+< 2 --^ textDocument/hover @[inherit_doc] notation "ℕ" => Nat #check ℕ --^ textDocument/hover /-- My command -/ macro "mycmd" e:term : command => do let seq ← `(Lean.Parser.Term.doSeq| $e:term) --^ textDocument/hover `(def hi := Id.run do $seq:doSeq) --^ textDocument/hover mycmd 1 --^ textDocument/hover /-- My way better command -/ macro_rules | `(mycmd $e) => `(@[inline] def hi := $e) mycmd 1 --^ textDocument/hover syntax "mycmd'" ppSpace sepBy1(term, " + ") : command --^ textDocument/hover --^ textDocument/hover --^ textDocument/hover /-- My ultimate command -/ elab_rules : command | `(mycmd' $e) => do Lean.Elab.Command.elabCommand (← `(/-- hi -/ @[inline] def hi := $e)) mycmd' 1 --^ textDocument/hover #check ({ a := }) -- should not show `sorry` --^ textDocument/hover example : True := by simp [id True.intro] --^ textDocument/hover --^ textDocument/hover example : Id Nat := do let mut n := 1 n := 2 --^ textDocument/hover n opaque foo : Nat #check _root_.foo --^ textDocument/hover namespace Bar opaque foo : Nat --^ textDocument/hover #check _root_.foo --^ textDocument/hover def bar := 1 --^ textDocument/hover structure Foo := mk :: --^ textDocument/hover --^ textDocument/hover hi : Nat --^ textDocument/hover inductive Bar --^ textDocument/hover | mk : Bar --^ textDocument/hover instance : ToString Nat := ⟨toString⟩ --^ textDocument/hover instance f : ToString Nat := ⟨toString⟩ --^ textDocument/hover example : Type 0 := Nat --^ textDocument/hover def foo.bar : Nat := 1 --^ textDocument/hover --^ textDocument/hover example : Nat → Nat → Nat := fun x y => --^ textDocument/hover --v textDocument/definition x --^ textDocument/hover -- textDocument/definition -- removed because the result is platform-dependent set_option linter.unusedVariables false in --^ textDocument/hover example : Nat → Nat → Nat := by intro x y --^ textDocument/hover --v textDocument/definition exact x --^ textDocument/hover def g (n : Nat) : Nat := g 0 termination_by g n => n decreasing_by have n' := n; admit --^ textDocument/hover @[inline] --^ textDocument/hover def one := 1 example : True ∧ False := by constructor · constructor --^ textDocument/hover example : Nat := Id.run do (← 1) --^ textDocument/hover #check (· + ·) --^ textDocument/hover --^ textDocument/hover macro "my_intro" x:(ident <|> "_") : tactic => match x with | `($x:ident) => `(tactic| intro $x:ident) | _ => `(tactic| intro _%$x) example : α → α := by intro x; assumption --^ textDocument/hover example : α → α := by intro _; assumption --^ textDocument/hover example : α → α := by my_intro x; assumption --^ textDocument/hover example : α → α := by my_intro _; assumption --^ textDocument/hover example : Nat → True := by intro x --^ textDocument/hover cases x with | zero => trivial --^ textDocument/hover --v textDocument/hover | succ x => trivial --^ textDocument/hover example : Nat → True := by intro x --^ textDocument/hover induction x with --^ textDocument/hover | zero => trivial --^ textDocument/hover --v textDocument/hover | succ _ ih => exact ih --^ textDocument/hover example : Nat → Nat --v textDocument/hover | .zero => .zero --^ textDocument/hover --v textDocument/hover | .succ x => .succ x --^ textDocument/hover example : Inhabited Nat := ⟨Nat.zero⟩ --^ textDocument/hover --^ textDocument/hover example : Nat := let x := match 0 with | _ => 0 _ --^ textDocument/hover def auto (o : Nat := by exact 1) : Nat := o --^ textDocument/hover example : 1 = 1 := by --v textDocument/hover generalize _e : 1 = x --^ textDocument/hover exact Eq.refl x
b8d152ec6f16559e1a3d9965263a4e7a8aa5b2c5
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/rigid_monoidal_category.lean
8157c4b949e5035ac4096e2b16a21d5290566281
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
2,492
lean
-- Copyright (c) 2018 Michael Jendrusch. All rights reserved. import .braided_monoidal_category universes v u namespace category_theory open monoidal_category class right_duality {C : Sort u} (A A' : C) [monoidal_category.{v} C] := (right_unit : tensor_unit C ⟶ A ⊗ A') (right_counit : A' ⊗ A ⟶ tensor_unit C) (triangle_right_1' : ((𝟙 A') ⊗ right_unit) ≫ (associator A' A A').inv ≫ (right_counit ⊗ (𝟙 A')) = (right_unitor A').hom ≫ (left_unitor A').inv . obviously) (triangle_right_2' : (right_unit ⊗ (𝟙 A)) ≫ (associator A A' A).hom ≫ ((𝟙 A) ⊗ right_counit) = (left_unitor A).hom ≫ (right_unitor A).inv . obviously) class left_duality {C : Sort u} (A A' : C) [monoidal_category.{v} C] := (left_unit : tensor_unit C ⟶ A' ⊗ A) (left_counit : A ⊗ A' ⟶ tensor_unit C) (triangle_left_1' : ((𝟙 A) ⊗ left_unit) ≫ (associator A A' A).inv ≫ (left_counit ⊗ (𝟙 A)) = (right_unitor A).hom ≫ (left_unitor A).inv . obviously) (triangle_left_2' : (left_unit ⊗ (𝟙 A')) ≫ (associator A' A A').hom ≫ ((𝟙 A') ⊗ left_counit) = (left_unitor A').hom ≫ (right_unitor A').inv . obviously) class duality {C : Sort u} (A A' : C) [braided_monoidal_category.{v} C] extends right_duality.{v} A A', left_duality.{v} A A' def self_duality {C : Sort u} (A : C) [braided_monoidal_category.{v} C] := duality A A -- Hmmm, constructivity/universe issues here: class right_rigid (C : Type u) [monoidal_category.{v+1} C] := (right_rigidity' : Π X : C, Σ X' : C, right_duality X X') class left_rigid (C : Type u) [monoidal_category.{v+1} C] := (left_rigidity' : Π X : C, Σ X' : C, left_duality X X') class rigid (C : Type u) [monoidal_category.{v+1} C] extends right_rigid.{v} C, left_rigid.{v} C class self_dual (C : Sort u) [braided_monoidal_category.{v} C] := (self_duality' : Π X : C, self_duality X) def compact_closed (C : Type u) [symmetric_monoidal_category.{v+1} C] := rigid.{v} C section open self_dual open left_duality instance rigid_of_self_dual (C : Type u) [braided_monoidal_category.{v+1} C] [𝒟 : self_dual.{v+1} C] : rigid.{v} C := { left_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_left_duality, right_rigidity' := λ X : C, sigma.mk X (self_duality' X).to_right_duality } end end category_theory.monoidal
f4b223e852393a85616718a7474b13b020147bf3
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/sheaves/sheaf_condition/equalizer_products.lean
e47dd295feb3cbbae53ebf58daba9903dcbb62b4
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,454
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf import category_theory.limits.punit import category_theory.limits.shapes.products import category_theory.limits.shapes.equalizers import category_theory.full_subcategory /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ F.obj (U i)` and `∏ F.obj (U i) ⊓ (U j)`. -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] [has_products C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf namespace sheaf_condition_equalizer_products /-- The product of the sections of a presheaf over a family of open sets. -/ def pi_opens : C := ∏ (λ i : ι, F.obj (op (U i))) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def pi_inters : C := ∏ (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def left_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.1 ≫ F.map (inf_le_left (U p.1) (U p.2)).op) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def right_res : pi_opens F U ⟶ pi_inters F U := pi.lift (λ p : ι × ι, pi.π _ p.2 ≫ F.map (inf_le_right (U p.1) (U p.2)).op) /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (supr U)) ⟶ pi_opens F U := pi.lift (λ i : ι, F.map (topological_space.opens.le_supr U i).op) lemma w : res F U ≫ left_res F U = res F U ≫ right_res F U := begin dsimp [res, left_res, right_res], ext, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw [←F.map_comp], rw [←F.map_comp], congr, end /-- The equalizer diagram for the sheaf condition. -/ @[reducible] def diagram : walking_parallel_pair.{v} ⥤ C := parallel_pair (left_res F U) (right_res F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : fork.{v} (left_res F U) (right_res F U) := fork.of_ι _ (w F U) @[simp] lemma fork_X : (fork F U).X = F.obj (op (supr U)) := rfl @[simp] lemma fork_ι : (fork F U).ι = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_zero : (fork F U).π.app walking_parallel_pair.zero = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_one : (fork F U).π.app walking_parallel_pair.one = res F U ≫ left_res F U := rfl variables {F} {G : presheaf C X} /-- Isomorphic presheaves have isomorphic `pi_opens` for any cover `U`. -/ @[simp] def pi_opens.iso_of_iso (α : F ≅ G) : pi_opens F U ≅ pi_opens G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic `pi_inters` for any cover `U`. -/ @[simp] def pi_inters.iso_of_iso (α : F ≅ G) : pi_inters F U ≅ pi_inters G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.iso_of_iso (α : F ≅ G) : diagram F U ≅ diagram G U := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_iso U α, exact pi_inters.iso_of_iso U α end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, simp [left_res], }, { ext, simp [right_res], }, { simp, }, end. /-- If `F G : presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.iso_of_iso (α : F ≅ G) : fork F U ≅ (cones.postcompose (diagram.iso_of_iso U α).inv).obj (fork G U) := begin fapply fork.ext, { apply α.app, }, { ext, dunfold fork.ι, -- Ugh, `simp` can't unfold abbreviations. simp [res, diagram.iso_of_iso], } end section open_embedding variables {V : Top.{v}} {j : V ⟶ X} (oe : open_embedding j) variables (𝒰 : ι → opens V) /-- Push forward a cover along an open embedding. -/ @[simp] def cover.of_open_embedding : ι → opens X := (λ i, oe.is_open_map.functor.obj (𝒰 i)) /-- The isomorphism between `pi_opens` corresponding to an open embedding. -/ @[simp] def pi_opens.iso_of_open_embedding : pi_opens (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_opens F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso (iso.refl _)) /-- The isomorphism between `pi_inters` corresponding to an open embedding. -/ @[simp] def pi_inters.iso_of_open_embedding : pi_inters (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ pi_inters F (cover.of_open_embedding oe 𝒰) := pi.map_iso (λ X, F.map_iso begin dsimp [is_open_map.functor], exact iso.op { hom := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], apply le_refl _, }), inv := hom_of_le (by { simp only [oe.to_embedding.inj, set.image_inter], apply le_refl _, }), }, end) /-- The isomorphism of sheaf condition diagrams corresponding to an open embedding. -/ def diagram.iso_of_open_embedding : diagram (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ diagram F (cover.of_open_embedding oe 𝒰) := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_open_embedding oe 𝒰, exact pi_inters.iso_of_open_embedding oe 𝒰 end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, dsimp [left_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { ext, dsimp [right_res, is_open_map.functor], simp only [limit.lift_π, cones.postcompose_obj_π, iso.op_hom, discrete.nat_iso_hom_app, functor.map_iso_refl, functor.map_iso_hom, lim_map_π_assoc, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, category.assoc], dsimp, rw [category.id_comp, ←F.map_comp], refl, }, { simp, }, end. /-- If `F : presheaf C X` is a presheaf, and `oe : U ⟶ X` is an open embedding, then the sheaf condition fork for a cover `𝒰` in `U` for the composition of `oe` and `F` is isomorphic to sheaf condition fork for `oe '' 𝒰`, precomposed with the isomorphism of indexing diagrams `diagram.iso_of_open_embedding`. We use this to show that the restriction of sheaf along an open embedding is still a sheaf. -/ def fork.iso_of_open_embedding : fork (oe.is_open_map.functor.op ⋙ F) 𝒰 ≅ (cones.postcompose (diagram.iso_of_open_embedding oe 𝒰).inv).obj (fork F (cover.of_open_embedding oe 𝒰)) := begin fapply fork.ext, { dsimp [is_open_map.functor], exact F.map_iso (iso.op { hom := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]), inv := hom_of_le (by simp only [supr_s, supr_mk, le_def, subtype.coe_mk, set.le_eq_subset, set.image_Union]), }), }, { ext, dunfold fork.ι, -- Ugh, it is unpleasant that we need this. simp only [res, diagram.iso_of_open_embedding, discrete.nat_iso_inv_app, functor.map_iso_inv, limit.lift_π, cones.postcompose_obj_π, functor.comp_map, fork_π_app_walking_parallel_pair_zero, pi_opens.iso_of_open_embedding, nat_iso.of_components.inv_app, functor.map_iso_refl, functor.op_map, limit.lift_map, fan.mk_π_app, nat_trans.comp_app, has_hom.hom.unop_op, category.assoc, lim_map_eq_lim_map], dsimp, rw [category.comp_id, ←F.map_comp], refl, }, end end open_embedding end sheaf_condition_equalizer_products end presheaf end Top
41f5cb9487d456e3693b130df108f32261322961
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/lst64.lean
e5736b60ebf43c951c30f80654fa3691825656d4
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
2,817
lean
def mylist : list ℕ := #[ 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 ]
8f948211fe34efc19949a5f2c537ee6558b4a450
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/syntaxInNamespacesAndPP.lean
0bce0325fe0f3e9a674627015688bce8e1055d2c
[ "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
278
lean
namespace Foo syntax "foo" term : term macro_rules | `(foo $x) => x set_option trace.Elab true in #check foo true end Foo namespace Bla syntax[bla] "bla" term : term macro_rules | `(bla $x) => x set_option trace.Elab true in #check bla true #print Bla.bla end Bla
5c02012d4a3a56aaa3df76c34172d373c4c8e3cc
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/lsemidirect_product.lean
cbb23fa4751c591a8cb793ea8d0c05ed01bffd0e
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
7,225
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.mul_add logic.function.basic group_theory.subgroup /-! # Semidirect product This file defines semidirect products of groups, and the canonical maps in and out of the semidirect product. The semidirect product of `N` and `G` given a hom `φ` from `φ` from `G` to the automorphism group of `N` is the product of sets with the group `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` ## Key definitions There are two homs into the semidirect product `inl : N →* G ⋉[φ] N` and `inr : G →* G ⋉[φ] N`, and `lift` can be used to define maps `G ⋉[φ] N →* H` out of the semidirect product given maps `f₁ : N →* H` and `f₂ : G →* H` that satisfy the condition `∀ n g, f₁ (φ g n) = f₂ g * f₁ n * f₂ g⁻¹` ## Notation This file introduces the global notation `G ⋉[φ] N` for `semidirect_product N G φ` ## Tags group, semidirect product -/ variables (G : Type*) (N : Type*) {H : Type*} [group N] [group G] [group H] /-- The semidirect product of groups `N` and `G`, given a map `φ` from `G` to the automorphism group of `N`. It the product of sets with the group operation `⟨n₁, g₁⟩ * ⟨n₂, g₂⟩ = ⟨n₁ * φ g₁ n₂, g₁ * g₂⟩` -/ @[ext, derive decidable_eq] structure lsemidirect_product (φ : G →* mul_aut N) := (left : G) (right : N) attribute [pp_using_anonymous_constructor] lsemidirect_product notation G` ⋉[`:35 φ:35`] `:0 N :35 := lsemidirect_product G N φ namespace lsemidirect_product variables {N G} {φ : G →* mul_aut N} private def one_aux : G ⋉[φ] N := ⟨1, 1⟩ private def mul_aux (a b : G ⋉[φ] N) : G ⋉[φ] N := ⟨a.left * b.left, φ b.1⁻¹ a.2 * b.2⟩ private def inv_aux (a : G ⋉[φ] N) : G ⋉[φ] N := ⟨a.1⁻¹, φ a.1 a.2⁻¹⟩ private lemma mul_assoc_aux (a b c : G ⋉[φ] N) : mul_aux (mul_aux a b) c = mul_aux a (mul_aux b c) := by simp [mul_aux, mul_assoc, mul_equiv.map_mul] private lemma mul_one_aux (a : G ⋉[φ] N) : mul_aux a one_aux = a := by cases a; simp [mul_aux, one_aux] private lemma one_mul_aux (a : G ⋉[φ] N) : mul_aux one_aux a = a := by cases a; simp [mul_aux, one_aux] private lemma mul_left_inv_aux (a : G ⋉[φ] N) : mul_aux (inv_aux a) a = one_aux := by simp only [mul_aux, inv_aux, one_aux, ← mul_equiv.map_mul, mul_left_inv]; simp; admit instance : group (G ⋉[φ] N) := { one := one_aux, inv := inv_aux, mul := mul_aux, mul_assoc := mul_assoc_aux, one_mul := one_mul_aux, mul_one := mul_one_aux, mul_left_inv := mul_left_inv_aux } instance : inhabited (G ⋉[φ] N) := ⟨1⟩ @[simp] lemma one_left : (1 : G ⋉[φ] N).left = 1 := rfl @[simp] lemma one_right : (1 : G ⋉[φ] N).right = 1 := rfl @[simp] lemma inv_left (a : G ⋉[φ] N) : (a⁻¹).left = a.left⁻¹ := rfl @[simp] lemma inv_right (a : G ⋉[φ] N) : (a⁻¹).right = φ a.left a.right⁻¹ := rfl @[simp] lemma mul_left (a b : G ⋉[φ] N) : (a * b).left = a.left * b.left := rfl @[simp] lemma mul_right (a b : G ⋉[φ] N) : (a * b).right = φ b.left⁻¹ a.right * b.right := rfl /-- The canonical map `N →* G ⋉[φ] N` sending `n` to `⟨n, 1⟩` -/ def inl : G →* G ⋉[φ] N := { to_fun := λ g, ⟨g, 1⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inl (g : G) : (inl g : G ⋉[φ] N).left = g := rfl @[simp] lemma right_inl (g : G) : (inl g : G ⋉[φ] N).right = 1 := rfl lemma inl_injective : function.injective (inl : G → G ⋉[φ] N) := function.injective_iff_has_left_inverse.2 ⟨left, left_inl⟩ @[simp] lemma inl_inj {g₁ g₂ : G} : (inl g₁ : G ⋉[φ] N) = inl g₂ ↔ g₁ = g₂ := inl_injective.eq_iff /-- The canonical map `G →* G ⋉[φ] N` sending `g` to `⟨1, g⟩` -/ def inr : N →* G ⋉[φ] N := { to_fun := λ n, ⟨1, n⟩, map_one' := rfl, map_mul' := by intros; ext; simp } @[simp] lemma left_inr (n : N) : (inr n : G ⋉[φ] N).left = 1 := rfl @[simp] lemma right_inr (n : N) : (inr n : G ⋉[φ] N).right = n := rfl lemma inr_injective : function.injective (inr : N → G ⋉[φ] N) := function.injective_iff_has_left_inverse.2 ⟨right, right_inr⟩ @[simp] lemma inr_inj {n₁ n₂ : N} : (inr n₁ : G ⋉[φ] N) = inr n₂ ↔ n₁ = n₂ := inr_injective.eq_iff lemma inr_aut (g : G) (n : N) : (inr (φ g n) : G ⋉[φ] N) = inl g * inr n * inl g⁻¹ := by ext; simp lemma inl_aut_inv (g : G) (n : N) : (inr ((φ g)⁻¹ n) : G ⋉[φ] N) = inl g⁻¹ * inr n * inl g := by rw [← monoid_hom.map_inv, inr_aut, inv_inv] lemma inl_left_mul_inr_right (x : G ⋉[φ] N) : inl x.left * inr x.right = x := by ext; simp /-- The canonical projection map `G ⋉[φ] N →* G`, as a group hom. -/ def left_hom : G ⋉[φ] N →* G := { to_fun := lsemidirect_product.left, map_one' := rfl, map_mul' := λ _ _, rfl } @[simp] lemma left_hom_eq_left : (left_hom : G ⋉[φ] N → G) = left := rfl @[simp] lemma left_hom_comp_inr : (left_hom : G ⋉[φ] N →* G).comp inr = 1 := by ext; simp [left_hom] @[simp] lemma right_hom_comp_inl : (left_hom : G ⋉[φ] N →* G).comp inl = monoid_hom.id _ := by ext; simp [left_hom] @[simp] lemma left_hom_inr (n : N) : left_hom (inr n : G ⋉[φ] N) = 1 := by simp [left_hom] @[simp] lemma left_hom_inl (g : G) : left_hom (inl g : G ⋉[φ] N) = g := by simp [left_hom] lemma left_hom_surjective : function.surjective (left_hom : G ⋉[φ] N → G) := function.surjective_iff_has_right_inverse.2 ⟨inl, left_hom_inl⟩ lemma range_inr_eq_ker_left_hom : (inr : N →* G ⋉[φ] N).range = left_hom.ker := le_antisymm (λ _, by simp [monoid_hom.mem_ker, eq_comm] {contextual := tt}) (λ x hx, ⟨x.right, by ext; simp [*, monoid_hom.mem_ker] at *⟩) section lift variables (f₁ : N →* H) (f₂ : G →* H) (h : ∀ g, f₁.comp (φ g).to_monoid_hom = (mul_aut.conj (f₂ g)).to_monoid_hom.comp f₁) /-- Define a group hom `G ⋉[φ] N →* H`, by defining maps `N →* H` and `G →* H` -/ def lift (f₁ : G →* H) (f₂ : N →* H) (h : ∀ g, f₂.comp (φ g).to_monoid_hom = (mul_aut.conj (f₁ g)).to_monoid_hom.comp f₂) : G ⋉[φ] N →* H := { to_fun := λ a, f₁ a.1 * f₂ a.2, map_one' := by simp, map_mul' := λ a b, begin have := λ n g, monoid_hom.ext_iff.1 (h n) g, simp only [mul_aut.conj_apply, monoid_hom.comp_apply, mul_equiv.to_monoid_hom_apply] at this, simp [this, mul_assoc], end } @[simp] lemma lift_inl (n : N) : lift f₁ f₂ h (inl n) = f₁ n := by simp [lift] @[simp] lemma lift_comp_inl : (lift f₁ f₂ h).comp inl = f₁ := by ext; simp @[simp] lemma lift_inr (g : G) : lift f₁ f₂ h (inr g) = f₂ g := by simp [lift] @[simp] lemma lift_comp_inr : (lift f₁ f₂ h).comp inr = f₂ := by ext; simp lemma left_mul_right (x : G ⋉[φ] N) : inl x.left * inr x.right = x := by ext; simp lemma lift_unique (F : G ⋉[φ] N →* H) : F = lift (F.comp inl) (F.comp inr) (λ _, by ext; simp [inl_aut]) := begin ext, simp only [lift, monoid_hom.comp_apply, monoid_hom.coe_mk], rw [← F.map_mul, inl_left_mul_inr_right], end end lift end lsemidirect_product
bba2dbe2eb3f72066f5b4ddc06a66f071a2c4ccd
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/448.lean
aefaf7c764bbd74a0cc20802c0e7d643a475861d
[ "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
901
lean
namespace TryCatchWithAutolift structure M (α : Type) where σ : ExceptT String IO α instance : Monad M where pure x := { σ := pure x } bind x f := { σ := do (f (← x.σ)).σ } map f x := { σ := do f (← x.σ) } instance : MonadLiftT IO M where monadLift {α : Type} (act : IO α) : M α := { σ := monadLift act } instance : MonadFinally M where tryFinally' := fun x h => M.mk do tryFinally' x.σ fun e => (h e).σ def t : M Unit := do liftM $ IO.println "bad" try do pure () -- Error catch ex : IO.Error => do pure () finally do pure () instance : MonadExceptOf IO.Error M where throw e := { σ := throwThe IO.Error e } tryCatch x handle := { σ := tryCatchThe IO.Error x.σ fun e => handle e |>.σ } def t2 : M Unit := do liftM $ IO.println "bad" try do pure () catch ex : IO.Error => do pure () finally do pure () end TryCatchWithAutolift
7fcf17fa81499fd88d2cf83d8381af165c0162c4
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/predicate_logic/induction.lean
c21d02f087c7222e1b522b317e93d1e9aced280e
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
4,500
lean
/- Proof strategies. - direct proof: use established facts - by negation: to prove ¬ P, assume P; show that this yields a contradiction, from which a proof of false can then be derived. This shows P → false, and that is the definition of ¬ P. Prove that the square root of two is irrational. Prove that the square root two is NOT rational. Prove ¬ sqrt(2) is rational. Proof: assume sqrt(2) is rational. In this case, we can write sqrt(2) as some fraction, a/b. We now want to show that this leads to a contradiction. ... - by contradiction : to prove P, assume ¬ P and show that this leads to a contradiction, from which a proof of false can be derived. This proves ¬ P → false, which is equivalent to ¬ ¬ P. The apply the *classical* rule of negation elimination to deduce P. Classical rule of negation elimination: ∀ (P : Prop), ¬ ¬ P → P. Prove 0 = 0 by contradiction. We want to prove P (0 = 0). Assume ¬ (0 = 0), and show that this leads to a contradiction. But by the reflexive property of equality, which says everything is equal to itself, we know immediate that 0 = 0. That gives us a direct contradiction, between ¬ (0=0) and (0=0). From such a contradiction we can derive a proof of false, showing that ¬ (0=0) → false. And this just means ¬ (¬ 0=0). The by classical negation elimination, this implies 0 = 0. - Today: proof by induction. -/ -- Answer to question about why contradictions imply false axiom P : Prop axiom p : P axiom np : ¬ P /- P → false -/ #check (np p) /- Prove this: ∀ (m : ℕ), my_add 0 m = m -/ def my_add : ℕ → ℕ → ℕ | nat.zero m := m | (nat.succ n') m := nat.succ (my_add n' m) -- 0 + m = m -- (1 + n') + m = 1 + (n' + m) /- Proof: By the definition of addition, and specifically by the first of the two cases, which tells us that for any m, 0 + m = m. -/ /- Many proofs are accomplished by mere simplification of both sides of some equation *using function definitions* that are already known. -/ /- If one is being precise, however, there are some unexpected consequences. One is that sometimes something that looks easy turns out to be a bit more complicated. For example, try to prove this (using) only what we know so far. -/ example : ∀ (n : ℕ), my_add n 0 = n := _ /- We have no rule (yet) for adding zero on the right, so simplifying using the definition of my_add doesn't work. Instead, we need to try a whole different proof strategy. -/ /- Here's the idea: - every inductively defined type has a corresponding induction rule - It's a rule for showing that some proposition is true for *every* value of the given type - The induction principle for ℕ is this: ∀ P : (ℕ → Prop), P 0 → ((∀ n' : ℕ), P n' → P (nat.succ n')) → ∀ n, P n In other words, for any predicate/property P, to show ∀ (n : ℕ), P n, it *suffices* to show the following: (1) P 0, (2) (∀ n' : ℕ), P n' → P (nat.succ n') -/ /- Example: We want to prove ∀ n, n + 0 = n. Proof by induction. If suffices to show that (1) Case: n = 0. By first rule of my_add. (2) Case: n = nat.succ n': Show P n' → P (nat.succ n'). Assume P n'? my_add n' 0 = n' Wow show P (nat.succ n'), (nat.succ n') + 0 = (nat.succ n'). *** simp: nat.succ (my_add n' 0) = nat.succ n' --do some algebra! *** apply induction hypothesis: nat.succ n' = nat.succ n' Finish by reflexive property of equality. def my_add : ℕ → ℕ → ℕ | nat.zero m := m | (nat.succ n') m := nat.succ (my_add n' m) -/ /- ∀ n, Sum numbers from 0 to n = n * (succ n) / 2. Proof by induction. We will apply the principle of induction for the natural numbers to two smaller proofs: one for n = 0, and one that shows that if the formula is true for some n' > 0, then it must also be true succ n'. Base case: prove (P 0): show sum from 0 to 0 = (0 * 1)/2 = 0. Inductive case: Show P n' → P (n' + 1) Assume P n'. The sum from 0 to n' = n' * (n' + 1) / 2. Show (P (n' + 1)): The sum from 0 to n'+1 = (n'+1)((n'+1)+1)/2. Do some algebra! --- intuition 1+2+3+4+5 if we assume this is 5*6/2 (1+2+3+4+5)+6 show this is 6*7/2 sum 0 to 5 + 6! = 5*6/2 + 6 The sum from 0 to (n' + 1) = sum from 0 to n' + (n' + 1) = (n'*(n'+1)/2) + (n' + 1) ... = (n'+1)((n'+1)+1)/2. -/
64d448f802cfd5288f6fdf16f19381f6130fd947
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/class_number/admissible_card_pow_degree.lean
f654d2a66f7c00a4e8df45ccc0619af799eba1b4
[ "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
13,910
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import number_theory.class_number.admissible_absolute_value import analysis.special_functions.pow import ring_theory.ideal.local_ring import data.polynomial.degree.card_pow_degree /-! # Admissible absolute values on polynomials This file defines an admissible absolute value `polynomial.card_pow_degree_is_admissible` which we use to show the class number of the ring of integers of a function field is finite. ## Main results * `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`, mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible -/ namespace polynomial open absolute_value real variables {Fq : Type*} [field Fq] [fintype Fq] /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of equal elements in `A`. -/ lemma exists_eq_polynomial {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (hb : nat_degree b ≤ d) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ A i₁ = A i₀ := begin -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `0`, ... `degree b - 1` ≤ `d - 1`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff j, have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], ext j, -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { rw [coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj), coeff_eq_zero_of_degree_lt (lt_of_lt_of_le (hA _) hbj)] }, -- So we only need to look for the coefficients between `0` and `deg b`. rw not_le at hbj, apply congr_fun i_eq.symm ⟨j, _⟩, exact lt_of_lt_of_le (coe_lt_degree.mp hbj) hb end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that their difference has small degree. -/ lemma exists_approx_polynomial_aux {d : ℕ} {m : ℕ} (hm : fintype.card Fq ^ d ≤ m) (b : polynomial Fq) (A : fin m.succ → polynomial Fq) (hA : ∀ i, degree (A i) < degree b) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ degree (A i₁ - A i₀) < ↑(nat_degree b - d) := begin have hb : b ≠ 0, { rintro rfl, specialize hA 0, rw degree_zero at hA, exact not_lt_of_le bot_le hA }, -- Since there are > q^d elements of A, and only q^d choices for the highest `d` coefficients, -- there must be two elements of A with the same coefficients at -- `degree b - 1`, ... `degree b - d`. -- In other words, the following map is not injective: set f : fin m.succ → (fin d → Fq) := λ i j, (A i).coeff (nat_degree b - j.succ), have : fintype.card (fin d → Fq) < fintype.card (fin m.succ), { simpa using lt_of_le_of_lt hm (nat.lt_succ_self m) }, -- Therefore, the differences have all coefficients higher than `deg b - d` equal. obtain ⟨i₀, i₁, i_ne, i_eq⟩ := fintype.exists_ne_map_eq_of_card_lt f this, use [i₀, i₁, i_ne], refine (degree_lt_iff_coeff_zero _ _).mpr (λ j hj, _), -- The coefficients higher than `deg b` are the same because they are equal to 0. by_cases hbj : degree b ≤ j, { refine coeff_eq_zero_of_degree_lt (lt_of_lt_of_le _ hbj), exact lt_of_le_of_lt (degree_sub_le _ _) (max_lt (hA _) (hA _)) }, -- So we only need to look for the coefficients between `deg b - d` and `deg b`. rw [coeff_sub, sub_eq_zero], rw [not_le, degree_eq_nat_degree hb, with_bot.coe_lt_coe] at hbj, have hj : nat_degree b - j.succ < d, { by_cases hd : nat_degree b < d, { exact lt_of_le_of_lt tsub_le_self hd }, { rw not_lt at hd, have := lt_of_le_of_lt hj (nat.lt_succ_self j), rwa [tsub_lt_iff_tsub_lt hd hbj] at this } }, have : j = b.nat_degree - (nat_degree b - j.succ).succ, { rw [← nat.succ_sub hbj, nat.succ_sub_succ, tsub_tsub_cancel_of_le hbj.le] }, convert congr_fun i_eq.symm ⟨nat_degree b - j.succ, hj⟩ end /-- If `A` is a family of enough low-degree polynomials over a finite field, there is a pair of elements in `A` (with different indices but not necessarily distinct), such that the difference of their remainders is close together. -/ lemma exists_approx_polynomial {b : polynomial Fq} (hb : b ≠ 0) {ε : ℝ} (hε : 0 < ε) (A : fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊).succ → polynomial Fq) : ∃ i₀ i₁, i₀ ≠ i₁ ∧ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, have one_lt_q : 1 < fintype.card Fq := fintype.one_lt_card, have one_lt_q' : (1 : ℝ) < fintype.card Fq, { assumption_mod_cast }, have q_pos : 0 < fintype.card Fq, { linarith }, have q_pos' : (0 : ℝ) < fintype.card Fq, { assumption_mod_cast }, -- If `b` is already small enough, then the remainders are equal and we are done. by_cases le_b : b.nat_degree ≤ ⌈- log ε / log (fintype.card Fq)⌉₊, { obtain ⟨i₀, i₁, i_ne, mod_eq⟩ := exists_eq_polynomial le_rfl b le_b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), refine ⟨i₀, i₁, i_ne, _⟩, simp only at mod_eq, rwa [mod_eq, sub_self, absolute_value.map_zero, int.cast_zero] }, -- Otherwise, it suffices to choose two elements whose difference is of small enough degree. rw not_le at le_b, obtain ⟨i₀, i₁, i_ne, deg_lt⟩ := exists_approx_polynomial_aux le_rfl b (λ i, A i % b) (λ i, euclidean_domain.mod_lt (A i) hb), simp only at deg_lt, use [i₀, i₁, i_ne], -- Again, if the remainders are equal we are done. by_cases h : A i₁ % b = A i₀ % b, { rwa [h, sub_self, absolute_value.map_zero, int.cast_zero] }, have h' : A i₁ % b - A i₀ % b ≠ 0 := mt sub_eq_zero.mp h, -- If the remainders are not equal, we'll show their difference is of small degree. -- In particular, we'll show the degree is less than the following: suffices : (nat_degree (A i₁ % b - A i₀ % b) : ℝ) < b.nat_degree + log ε / log (fintype.card Fq), { rwa [← real.log_lt_log_iff (int.cast_pos.mpr (card_pow_degree.pos h')) hbε, card_pow_degree_nonzero _ h', card_pow_degree_nonzero _ hb, algebra.smul_def, ring_hom.eq_int_cast, int.cast_pow, int.cast_coe_nat, int.cast_pow, int.cast_coe_nat, log_mul (pow_ne_zero _ q_pos'.ne') hε.ne', ← rpow_nat_cast, ← rpow_nat_cast, log_rpow q_pos', log_rpow q_pos', ← lt_div_iff (log_pos one_lt_q'), add_div, mul_div_cancel _ (log_pos one_lt_q').ne'] }, -- And that result follows from manipulating the result from `exists_approx_polynomial_aux` -- to turn the `-⌈-stuff⌉₊` into `+ stuff`. refine lt_of_lt_of_le (nat.cast_lt.mpr (with_bot.coe_lt_coe.mp _)) _, swap, { convert deg_lt, rw degree_eq_nat_degree h' }, rw [← sub_neg_eq_add, neg_div], refine le_trans _ (sub_le_sub_left (nat.le_ceil _) (b.nat_degree : ℝ)), rw ← neg_div, exact le_of_eq (nat.cast_sub le_b.le) end /-- If `x` is close to `y` and `y` is close to `z`, then `x` and `z` are at least as close. -/ lemma card_pow_degree_anti_archimedean {x y z : polynomial Fq} {a : ℤ} (hxy : card_pow_degree (x - y) < a) (hyz : card_pow_degree (y - z) < a) : card_pow_degree (x - z) < a := begin have ha : 0 < a := lt_of_le_of_lt (absolute_value.nonneg _ _) hxy, by_cases hxy' : x = y, { rwa hxy' }, by_cases hyz' : y = z, { rwa ← hyz' }, by_cases hxz' : x = z, { rwa [hxz', sub_self, absolute_value.map_zero] }, rw [← ne.def, ← sub_ne_zero] at hxy' hyz' hxz', refine lt_of_le_of_lt _ (max_lt hxy hyz), rw [card_pow_degree_nonzero _ hxz', card_pow_degree_nonzero _ hxy', card_pow_degree_nonzero _ hyz'], have : (1 : ℤ) ≤ fintype.card Fq, { exact_mod_cast (@fintype.one_lt_card Fq _ _).le }, simp only [int.cast_pow, int.cast_coe_nat, le_max_iff], refine or.imp (pow_le_pow this) (pow_le_pow this) _, rw [nat_degree_le_iff_degree_le, nat_degree_le_iff_degree_le, ← le_max_iff, ← degree_eq_nat_degree hxy', ← degree_eq_nat_degree hyz'], convert degree_add_le (x - y) (y - z) using 2, exact (sub_add_sub_cancel _ _ _).symm end /-- A slightly stronger version of `exists_partition` on which we perform induction on `n`: for all `ε > 0`, we can partition the remainders of any family of polynomials `A` into equivalence classes, where the equivalence(!) relation is "closer than `ε`". -/ lemma exists_partition_polynomial_aux (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ ↔ (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin have hbε : 0 < card_pow_degree b • ε, { rw [algebra.smul_def, ring_hom.eq_int_cast], exact mul_pos (int.cast_pos.mpr (absolute_value.pos _ hb)) hε }, -- We go by induction on the size `A`. induction n with n ih, { refine ⟨fin_zero_elim, fin_zero_elim⟩ }, -- Show `anti_archimedean` also holds for real distances. have anti_archim' : ∀ {i j k} {ε : ℝ}, (card_pow_degree (A i % b - A j % b) : ℝ) < ε → (card_pow_degree (A j % b - A k % b) : ℝ) < ε → (card_pow_degree (A i % b - A k % b) : ℝ) < ε, { intros i j k ε, simp_rw [← int.lt_ceil], exact card_pow_degree_anti_archimedean }, obtain ⟨t', ht'⟩ := ih (fin.tail A), -- We got rid of `A 0`, so determine the index `j` of the partition we'll re-add it to. suffices : ∃ j, ∀ i, t' i = j ↔ (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, hj⟩ := this, refine ⟨fin.cons j t', λ i₀ i₁, _⟩, refine fin.cases _ (λ i₀, _) i₀; refine fin.cases _ (λ i₁, _) i₁, { simpa using hbε }, { rw [fin.cons_succ, fin.cons_zero, eq_comm, absolute_value.map_sub], exact hj i₁ }, { rw [fin.cons_succ, fin.cons_zero], exact hj i₀ }, { rw [fin.cons_succ, fin.cons_succ], exact ht' i₀ i₁ } }, -- `exists_approx_polynomial` guarantees that we can insert `A 0` into some partition `j`, -- but not that `j` is uniquely defined (which is needed to keep the induction going). obtain ⟨j, hj⟩ : ∃ j, ∀ (i : fin n), t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { by_contra this, push_neg at this, obtain ⟨j₀, j₁, j_ne, approx⟩ := exists_approx_polynomial hb hε (fin.cons (A 0) (λ j, A (fin.succ (classical.some (this j))))), revert j_ne approx, refine fin.cases _ (λ j₀, _) j₀; refine fin.cases (λ j_ne approx, _) (λ j₁ j_ne approx, _) j₁, { exact absurd rfl j_ne }, { rw [fin.cons_succ, fin.cons_zero, ← not_le, absolute_value.map_sub] at approx, have := (classical.some_spec (this j₁)).2, contradiction }, { rw [fin.cons_succ, fin.cons_zero, ← not_le] at approx, have := (classical.some_spec (this j₀)).2, contradiction }, { rw [fin.cons_succ, fin.cons_succ] at approx, rw [ne.def, fin.succ_inj] at j_ne, have : j₀ = j₁ := (classical.some_spec (this j₀)).1.symm.trans (((ht' (classical.some (this j₀)) (classical.some (this j₁))).mpr approx).trans (classical.some_spec (this j₁)).1), contradiction } }, -- However, if one of those partitions `j` is inhabited by some `i`, then this `j` works. by_cases exists_nonempty_j : ∃ j, (∃ i, t' i = j) ∧ ∀ i, t' i = j → (card_pow_degree (A 0 % b - A i.succ % b) : ℝ) < card_pow_degree b • ε, { obtain ⟨j, ⟨i, hi⟩, hj⟩ := exists_nonempty_j, refine ⟨j, λ i', ⟨hj i', λ hi', trans ((ht' _ _).mpr _) hi⟩⟩, apply anti_archim' _ hi', rw absolute_value.map_sub, exact hj _ hi }, -- And otherwise, we can just take any `j`, since those are empty. refine ⟨j, λ i, ⟨hj i, λ hi, _⟩⟩, have := exists_nonempty_j ⟨t' i, ⟨i, rfl⟩, λ i' hi', anti_archim' hi ((ht' _ _).mp hi')⟩, contradiction end /-- For all `ε > 0`, we can partition the remainders of any family of polynomials `A` into classes, where all remainders in a class are close together. -/ lemma exists_partition_polynomial (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : polynomial Fq} (hb : b ≠ 0) (A : fin n → polynomial Fq) : ∃ (t : fin n → fin (fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊)), ∀ (i₀ i₁ : fin n), t i₀ = t i₁ → (card_pow_degree (A i₁ % b - A i₀ % b) : ℝ) < card_pow_degree b • ε := begin obtain ⟨t, ht⟩ := exists_partition_polynomial_aux n hε hb A, exact ⟨t, λ i₀ i₁ hi, (ht i₀ i₁).mp hi⟩ end /-- `λ p, fintype.card Fq ^ degree p` is an admissible absolute value. We set `q ^ degree 0 = 0`. -/ noncomputable def card_pow_degree_is_admissible : is_admissible (card_pow_degree : absolute_value (polynomial Fq) ℤ) := { card := λ ε, fintype.card Fq ^ ⌈- log ε / log (fintype.card Fq)⌉₊, exists_partition' := λ n ε hε b hb, exists_partition_polynomial n hε hb, .. @card_pow_degree_is_euclidean Fq _ _ } end polynomial
f2aa9aa134740044532a9c3e2976a2a11c7a2c58
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/char_p/quotient.lean
82a92b2177d803182d5620451852228561f395ec
[ "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
1,451
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Eric Wieser -/ import algebra.char_p.basic import algebra.ring_quot /-! # Characteristic of quotients rings -/ universes u v namespace char_p theorem quotient (R : Type u) [comm_ring R] (p : ℕ) [hp1 : fact p.prime] (hp2 : ↑p ∈ nonunits R) : char_p (ideal.span {p} : ideal R).quotient p := have hp0 : (p : (ideal.span {p} : ideal R).quotient) = 0, from (ideal.quotient.mk (ideal.span {p} : ideal R)).map_nat_cast p ▸ ideal.quotient.eq_zero_iff_mem.2 (ideal.subset_span $ set.mem_singleton _), ring_char.of_eq $ or.resolve_left ((nat.dvd_prime hp1.1).1 $ ring_char.dvd hp0) $ λ h1, hp2 $ is_unit_iff_dvd_one.2 $ ideal.mem_span_singleton.1 $ ideal.quotient.eq_zero_iff_mem.1 $ @@subsingleton.elim (@@char_p.subsingleton _ $ ring_char.of_eq h1) _ _ /-- If an ideal does not contain any coercions of natural numbers other than zero, then its quotient inherits the characteristic of the underlying ring. -/ lemma quotient' {R : Type*} [comm_ring R] (p : ℕ) [char_p R p] (I : ideal R) (h : ∀ x : ℕ, (x : R) ∈ I → (x : R) = 0) : char_p I.quotient p := ⟨λ x, begin rw [←cast_eq_zero_iff R p x, ←(ideal.quotient.mk I).map_nat_cast], refine quotient.eq'.trans (_ : ↑x - 0 ∈ I ↔ _), rw sub_zero, exact ⟨h x, λ h', h'.symm ▸ I.zero_mem⟩, end⟩ end char_p
284f262de3aacf87821130cde9f295fd79b3b435
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/vector2.lean
103b302bec083bc60745fcf25126537d8437861c
[ "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
10,717
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Additional theorems about the `vector` type. -/ import data.vector import data.list.nodup import data.list.of_fn import control.applicative universes u variables {n : ℕ} namespace vector variables {α : Type*} attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective @[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a :: v).val = a :: v.val | ⟨_, _⟩ := rfl @[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a :: v).head = a | ⟨_, _⟩ := rfl @[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a :: v).tail = v | ⟨_, _⟩ := rfl @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simp [nth, list.of_fn_nth_le] end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail | ⟨a::l, e⟩ := rfl @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a := by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le]; exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩, λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩ lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, simp [nth_eq_nth_le] at *, tauto }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end @[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list := by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _ theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a :: v) 0 = a := by simp [nth_zero] @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i := by rw [← nth_tail, tail_cons] def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a::v) = do h' ← f a, t' ← mmap f v, pure (h' :: t') | _ ⟨l, rfl⟩ := rfl @[ext] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i.1 a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i.1 | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth_ne {v : vector α (n+1)} : ∀{i j : fin (n+2)} (h : i ≠ j), remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v) | ⟨i, hi⟩ ⟨j, hj⟩ ne := begin have : i ≠ j := fin.vne_of_ne ne, refine subtype.eq _, dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt, -subtype.val_eq_coe], rcases lt_trichotomy i j with h | h | h, { have h_nji : ¬ j < i := lt_asymm h, have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h, simp [h, h_nji, fin.lt_iff_val_lt_val, -subtype.val_eq_coe], rw [show j.pred = j - 1, from rfl, list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos], { rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) }, { exact nat.le_sub_right_of_add_le h } }, { exact (this h).elim }, { have h_nij : ¬ i < j := lt_asymm h, have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h, simp [h, h_nij, fin.lt_iff_val_lt_val], rw [show i.pred = i - 1, from rfl, list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos], { show i - 1 + 1 ≤ v.val.length, rw [v.2, nat.sub_add_cancel i_pos], exact nat.le_of_lt_succ hi }, { exact nat.le_sub_right_of_add_le h } } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp [insert_nth_val, fin.succ_val, fin.cast_succ], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x :: xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
4bc5e9df06586a2109d98871155b29117b2fde0c
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/whnf_core1.lean
c83718c611e812be709223f643404397977064af
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
337
lean
open tactic definition f (a : nat) := a + 2 attribute [reducible] definition g (a : nat) := a + 2 example (a : nat) : true := by do to_expr `(f a) >>= whnf >>= trace, to_expr `(g a) >>= whnf >>= trace, to_expr `(f a) >>= (λ e, whnf e reducible) >>= trace, to_expr `(g a) >>= (λ e, whnf e reducible) >>= trace, constructor
4fbf73e4fc63a843a973912ceb60d0f20582db05
94637389e03c919023691dcd05bd4411b1034aa5
/src/zzz_junk/04_type_library/03_typeUniverses.lean
8fde435cc2108d111343b3d6d2158c5352a4b248
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
2,948
lean
/- Lean's type hierarchy -/ namespace hidden1 structure box (α : Type) : Type := (val : α) def b3 : box nat := box.mk 3 /- Every term has a type. Types are terms, too. The type of 3 is ℕ. ℕ is a type, so it has a type. The type of ℕ (#check) is Type. So here's a picture so far. Type (aka Type 0) / | \ ..... \ bool nat string (box nat) ... / \ | | | tt ff 3 "Hi!" (box.mk 3) We can pass 3 to box'.mk because its type, nat, "belongs to" Type. Can we pass nat to box'.mk? -/ def bn := box.mk nat -- No! /- A picture tells us what went wrong. ??? | Type 0 (α := Type : ???) / | \ bool nat string (a := nat : Type) / \ | | tt ff 3 "Hi!" Above Type 0 is an infinite stack of higher type universes, Type 1, Type 2, etc. -/ #check Type 0 #check Type 1 #check Type 2 -- etc /- In the earlier example, we declared the type of α to be Type, but if we bind a := (nat : Type), the Lean will infer that α := (Type : Type 1). So we get a type error. Now if we change the type of α from Type to Type 1, we'll have a different problem. THINK TIME: What is it? -/ end hidden1 /- The solution is to make our box type builder generic with respect to the "type universe" in which α lives. We do this by declaring an identifier to be a universe variable, and then add it after "Type" in our type declaration. -/ universe u structure box (α : Type u) : Type u := (val : α) def b3 : box nat := box.mk 3 def bt : box Type := box.mk nat /- Think time: What are the types of b3, box nat, bt, and box Type? -/ #check b3 #check box nat #check bt #check box Type -- Yay! /- Why so complex? To avoids logical inconsistency. Russell's Paradox. Consider the set, S, of all sets that do not contain themselves. Does it contain itself? If the answer is yes, then the answer must be no, and if it's no, it must be yes, so there is a contradiction in either case. A logic in which it's possible to derive a contradiction is of no use at all because in such a logic true = false so anything that can be proved to be true can also be proved to be false, and vice versa. Suppose doesn't contain itself. Well, then it must be in S because S is the set of all such sets.#check Now suppose it does contain itself then it must not contain itself, because contains only sets that don't contain themselves. This insight evolved out of work to place all of mathematics on a logical foundation. The attempt to place it on a foundation of naive set theory failed. This failure led to changes in set theory and also to the emergence of an early form of set theory. The key idea there was to rule out the very idea of a set that contains itself, as being non-sense. What you see in Lean's type system is a modern instantiation of the idea of stratified type universes in which no type can have itself as a value. -/
5dbaed00e7b8478bdd13c8e35ca547cca733eac1
367134ba5a65885e863bdc4507601606690974c1
/src/data/finset/sort.lean
7ce7a0e0508f8c1b6573bbb3957c96ddb5861c8c
[ "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
8,350
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.lattice import data.multiset.sort import data.list.nodup_equiv_fin /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h` is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o (s : set α) := order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $ (s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $ set.ext $ λ x, mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α := (order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _) @[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : ↑(order_iso_of_fin s h i) = order_emb_of_fin s h i := rfl lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : (s : set α)) : ↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x := rfl lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) := rfl @[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i ∈ s := (s.order_iso_of_fin h i).2 @[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.range (s.order_emb_of_fin h) = s := by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)] /-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/ lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min'] /-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h] /-- `order_emb_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) : order_emb_of_fin {a} (card_singleton a) i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton] /-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h := begin apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono, rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj], refine eq_of_subset_of_card_le (λ x hx, _) _, { rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x }, { rw [h, card_image_of_injective _ hmono.injective, fin_range_card] } end /-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h := rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono /-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin substs k l, exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _) end end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
e3b31b2d2ca4cd02ebb2d62b2af8d4f0adc0af81
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/finite.lean
d52c32394fa31f41a793ec50cf123e3a4528b5bd
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
51,031
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, Kyle Miller -/ import data.finset.sort import data.set.functor import data.finite.basic /-! # Finite sets This file defines predicates for finite and infinite sets and provides `fintype` instances for many set constructions. It also proves basic facts about finite sets and gives ways to manipulate `set.finite` expressions. ## Main definitions * `set.finite : set α → Prop` * `set.infinite : set α → Prop` * `set.to_finite` to prove `set.finite` for a `set` from a `finite` instance. * `set.finite.to_finset` to noncomputably produce a `finset` from a `set.finite` proof. (See `set.to_finset` for a computable version.) ## Implementation A finite set is defined to be a set whose coercion to a type has a `fintype` instance. Since `set.finite` is `Prop`-valued, this is the mere fact that the `fintype` instance exists. There are two components to finiteness constructions. The first is `fintype` instances for each construction. This gives a way to actually compute a `finset` that represents the set, and these may be accessed using `set.to_finset`. This gets the `finset` in the correct form, since otherwise `finset.univ : finset s` is a `finset` for the subtype for `s`. The second component is "constructors" for `set.finite` that give proofs that `fintype` instances exist classically given other `set.finite` proofs. Unlike the `fintype` instances, these *do not* use any decidability instances since they do not compute anything. ## Tags finite sets -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if there is a `finset` with the same elements. This is represented as there being a `fintype` instance for the set coerced to a type. Note: this is a custom inductive type rather than `nonempty (fintype s)` so that it won't be frozen as a local instance. -/ @[protected] inductive finite (s : set α) : Prop | intro : fintype s → finite -- The `protected` attribute does not take effect within the same namespace block. end set namespace set lemma finite_def {s : set α} : s.finite ↔ nonempty (fintype s) := ⟨λ ⟨h⟩, ⟨h⟩, λ ⟨h⟩, ⟨h⟩⟩ alias finite_def ↔ finite.nonempty_fintype _ lemma finite_coe_iff {s : set α} : finite s ↔ s.finite := by rw [finite_iff_nonempty_fintype, finite_def] /-- Constructor for `set.finite` using a `finite` instance. -/ theorem to_finite (s : set α) [finite s] : s.finite := finite_coe_iff.mp ‹_› /-- Construct a `finite` instance for a `set` from a `finset` with the same elements. -/ protected lemma finite.of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : p.finite := ⟨fintype.of_finset s H⟩ /-- Projection of `set.finite` to its `finite` instance. This is intended to be used with dot notation. See also `set.finite.fintype` and `set.finite.nonempty_fintype`. -/ protected lemma finite.to_subtype {s : set α} (h : s.finite) : finite s := finite_coe_iff.mpr h /-- A finite set coerced to a type is a `fintype`. This is the `fintype` projection for a `set.finite`. Note that because `finite` isn't a typeclass, this definition will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : s.finite) : fintype s := h.nonempty_fintype.some /-- Using choice, get the `finset` that represents this `set.` -/ noncomputable def finite.to_finset {s : set α} (h : s.finite) : finset α := @set.to_finset _ _ h.fintype theorem finite.exists_finset {s : set α} (h : s.finite) : ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s := by { casesI h, exact ⟨s.to_finset, λ _, mem_to_finset⟩ } theorem finite.exists_finset_coe {s : set α} (h : s.finite) : ∃ s' : finset α, ↑s' = s := by { casesI h, exact ⟨s.to_finset, s.coe_to_finset⟩ } /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) coe set.finite := { prf := λ s hs, hs.exists_finset_coe } /-- A set is infinite if it is not finite. This is protected so that it does not conflict with global `infinite`. -/ protected def infinite (s : set α) : Prop := ¬ s.finite @[simp] lemma not_infinite {s : set α} : ¬ s.infinite ↔ s.finite := not_not /-- See also `fintype_or_infinite`. -/ lemma finite_or_infinite {s : set α} : s.finite ∨ s.infinite := em _ /-! ### Basic properties of `set.finite.to_finset` -/ section finite_to_finset variables {s t : set α} @[simp] lemma finite.coe_to_finset {s : set α} (h : s.finite) : (h.to_finset : set α) = s := @set.coe_to_finset _ s h.fintype @[simp] theorem finite.mem_to_finset {s : set α} (h : s.finite) {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.nonempty_to_finset {s : set α} (h : s.finite) : h.to_finset.nonempty ↔ s.nonempty := by rw [← finset.coe_nonempty, finite.coe_to_finset] @[simp] lemma finite.coe_sort_to_finset {s : set α} (h : s.finite) : (h.to_finset : Type*) = s := by rw [← finset.coe_sort_coe _, h.coe_to_finset] @[simp] lemma finite_empty_to_finset (h : (∅ : set α).finite) : h.to_finset = ∅ := by rw [← finset.coe_inj, h.coe_to_finset, finset.coe_empty] @[simp] lemma finite_univ_to_finset [fintype α] (h : (set.univ : set α).finite) : h.to_finset = finset.univ := finset.ext $ by simp @[simp] lemma finite.to_finset_inj {s t : set α} {hs : s.finite} {ht : t.finite} : hs.to_finset = ht.to_finset ↔ s = t := by simp only [←finset.coe_inj, finite.coe_to_finset] lemma subset_to_finset_iff {s : finset α} {t : set α} (ht : t.finite) : s ⊆ ht.to_finset ↔ ↑s ⊆ t := by rw [← finset.coe_subset, ht.coe_to_finset] @[simp] lemma finite_to_finset_eq_empty_iff {s : set α} {h : s.finite} : h.to_finset = ∅ ↔ s = ∅ := by simp only [←finset.coe_inj, finite.coe_to_finset, finset.coe_empty] @[simp, mono] lemma finite.to_finset_subset {hs : s.finite} {ht : t.finite} : hs.to_finset ⊆ ht.to_finset ↔ s ⊆ t := by simp only [← finset.coe_subset, finite.coe_to_finset] @[simp, mono] lemma finite.to_finset_ssubset {hs : s.finite} {ht : t.finite} : hs.to_finset ⊂ ht.to_finset ↔ s ⊂ t := by simp only [← finset.coe_ssubset, finite.coe_to_finset] end finite_to_finset /-! ### Fintype instances Every instance here should have a corresponding `set.finite` constructor in the next section. -/ section fintype_instances instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α (equiv.set.univ α).symm /-- If `(set.univ : set α)` is finite then `α` is a finite type. -/ noncomputable def fintype_of_finite_univ (H : (univ : set α).finite) : fintype α := @fintype.of_equiv _ (univ : set α) H.fintype (equiv.set.univ _) instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [decidable_eq α] [fintype s] [fintype t] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset ∩ t.to_finset) $ by simp /-- A `fintype` instance for set intersection where the left set has a `fintype` instance. -/ instance fintype_inter_of_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s ∩ t : set α) := fintype.of_finset (s.to_finset.filter (∈ t)) $ by simp /-- A `fintype` instance for set intersection where the right set has a `fintype` instance. -/ instance fintype_inter_of_right (s t : set α) [fintype t] [decidable_pred (∈ s)] : fintype (s ∩ t : set α) := fintype.of_finset (t.to_finset.filter (∈ s)) $ by simp [and_comm] /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred (∈ t)] (h : t ⊆ s) : fintype t := by { rw ← inter_eq_self_of_subset_right h, apply set.fintype_inter_of_left } instance fintype_diff [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s \ t : set α) := fintype.of_finset (s.to_finset \ t.to_finset) $ by simp instance fintype_diff_left (s t : set α) [fintype s] [decidable_pred (∈ t)] : fintype (s \ t : set α) := set.fintype_sep s (∈ tᶜ) instance fintype_Union [decidable_eq α] [fintype (plift ι)] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bUnion (λ i : plift ι, (f i.down).to_finset)) $ by simp instance fintype_sUnion [decidable_eq α] {s : set (set α)} [fintype s] [H : ∀ (t : s), fintype (t : set α)] : fintype (⋃₀ s) := by { rw sUnion_eq_Union, exact @set.fintype_Union _ _ _ _ _ H } /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) (H : ∀ i ∈ s, fintype (t i)) : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.attach.bUnion (λ x, by { haveI := H x (by simpa using x.property), exact (t x).to_finset })) $ by simp instance fintype_bUnion' [decidable_eq α] {ι : Type*} (s : set ι) [fintype s] (t : ι → set α) [∀ i, fintype (t i)] : fintype (⋃(x ∈ s), t x) := fintype.of_finset (s.to_finset.bUnion (λ x, (t x).to_finset)) $ by simp /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion s f H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := set.fintype_bUnion' s f instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype.of_finset {a} $ by simp instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton /-- A `fintype` instance for inserting an element into a `set` using the corresponding `insert` function on `finset`. This requires `decidable_eq α`. There is also `set.fintype_insert'` when `a ∈ s` is decidable. -/ instance fintype_insert (a : α) (s : set α) [decidable_eq α] [fintype s] : fintype (insert a s : set α) := fintype.of_finset (insert a s.to_finset) $ by simp /-- A `fintype` structure on `insert a s` when inserting a new element. -/ def fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, s.to_finset.nodup.cons (by simp [h]) ⟩ $ by simp /-- A `fintype` structure on `insert a s` when inserting a pre-existing element. -/ def fintype_insert_of_mem {a : α} (s : set α) [fintype s] (h : a ∈ s) : fintype (insert a s : set α) := fintype.of_finset s.to_finset $ by simp [h] /-- The `set.fintype_insert` instance requires decidable equality, but when `a ∈ s` is decidable for this particular `a` we can still get a `fintype` instance by using `set.fintype_insert_of_not_mem` or `set.fintype_insert_of_mem`. This instance pre-dates `set.fintype_insert`, and it is less efficient. When `decidable_mem_of_fintype` is made a local instance, then this instance would override `set.fintype_insert` if not for the fact that its priority has been adjusted. See Note [lower instance priority]. -/ @[priority 100] instance fintype_insert' (a : α) (s : set α) [decidable $ a ∈ s] [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then fintype_insert_of_mem s h else fintype_insert_of_not_mem s h instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, (f '' s).to_finset.2.filter_map g $ injective_of_partial_inv_right I⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end instance fintype_range [decidable_eq α] (f : ι → α) [fintype (plift ι)] : fintype (range f) := fintype.of_finset (finset.univ.image $ f ∘ plift.down) $ by simp [equiv.plift.exists_congr_left] instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) /-- This is not an instance so that it does not conflict with the one in src/order/locally_finite. -/ def nat.fintype_Iio (n : ℕ) : fintype (Iio n) := set.fintype_lt_nat n instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (s ×ˢ t : set (α × β)) := fintype.of_finset (s.to_finset ×ˢ t.to_finset) $ by simp instance fintype_off_diag [decidable_eq α] (s : set α) [fintype s] : fintype s.off_diag := fintype.of_finset s.to_finset.off_diag $ by simp /-- `image2 f s t` is `fintype` if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } instance fintype_seq [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f.seq s) := by { rw seq_def, apply set.fintype_bUnion' } instance fintype_seq' {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := set.fintype_seq f s instance fintype_mem_finset (s : finset α) : fintype {a | a ∈ s} := finset.fintype_coe_sort s end fintype_instances end set /-! ### Finset -/ namespace finset /-- Gives a `set.finite` for the `finset` coerced to a `set`. This is a wrapper around `set.to_finite`. -/ lemma finite_to_set (s : finset α) : (s : set α).finite := set.to_finite _ @[simp] lemma finite_to_set_to_finset (s : finset α) : s.finite_to_set.to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace multiset lemma finite_to_set (s : multiset α) : {x | x ∈ s}.finite := by { classical, simpa only [← multiset.mem_to_finset] using s.to_finset.finite_to_set } @[simp] lemma finite_to_set_to_finset [decidable_eq α] (s : multiset α) : s.finite_to_set.to_finset = s.to_finset := by { ext x, simp } end multiset lemma list.finite_to_set (l : list α) : {x | x ∈ l}.finite := (show multiset α, from ⟦l⟧).finite_to_set /-! ### Finite instances There is seemingly some overlap between the following instances and the `fintype` instances in `data.set.finite`. While every `fintype` instance gives a `finite` instance, those instances that depend on `fintype` or `decidable` instances need an additional `finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `subtype.finite` for subsets of a finite type. -/ namespace finite.set open_locale classical example {s : set α} [finite α] : finite s := infer_instance example : finite (∅ : set α) := infer_instance example (a : α) : finite ({a} : set α) := infer_instance instance finite_union (s t : set α) [finite s] [finite t] : finite (s ∪ t : set α) := by { casesI nonempty_fintype s, casesI nonempty_fintype t, apply_instance } instance finite_sep (s : set α) (p : α → Prop) [finite s] : finite ({a ∈ s | p a} : set α) := by { casesI nonempty_fintype s, apply_instance } protected lemma subset (s : set α) {t : set α} [finite s] (h : t ⊆ s) : finite t := by { rw ←sep_eq_of_subset h, apply_instance } instance finite_inter_of_right (s t : set α) [finite t] : finite (s ∩ t : set α) := finite.set.subset t (inter_subset_right s t) instance finite_inter_of_left (s t : set α) [finite s] : finite (s ∩ t : set α) := finite.set.subset s (inter_subset_left s t) instance finite_diff (s t : set α) [finite s] : finite (s \ t : set α) := finite.set.subset s (diff_subset s t) instance finite_range (f : ι → α) [finite ι] : finite (range f) := by { haveI := fintype.of_finite (plift ι), apply_instance } instance finite_Union [finite ι] (f : ι → set α) [∀ i, finite (f i)] : finite (⋃ i, f i) := begin rw [Union_eq_range_psigma], apply set.finite_range end instance finite_sUnion {s : set (set α)} [finite s] [H : ∀ (t : s), finite (t : set α)] : finite (⋃₀ s) := by { rw sUnion_eq_Union, exact @finite.set.finite_Union _ _ _ _ H } lemma finite_bUnion {ι : Type*} (s : set ι) [finite s] (t : ι → set α) (H : ∀ i ∈ s, finite (t i)) : finite (⋃(x ∈ s), t x) := begin rw [bUnion_eq_Union], haveI : ∀ (i : s), finite (t i) := λ i, H i i.property, apply_instance, end instance finite_bUnion' {ι : Type*} (s : set ι) [finite s] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃(x ∈ s), t x) := finite_bUnion s t (λ i h, infer_instance) /-- Example: `finite (⋃ (i < n), f i)` where `f : ℕ → set α` and `[∀ i, finite (f i)]` (when given instances from `data.nat.interval`). -/ instance finite_bUnion'' {ι : Type*} (p : ι → Prop) [h : finite {x | p x}] (t : ι → set α) [∀ i, finite (t i)] : finite (⋃ x (h : p x), t x) := @finite.set.finite_bUnion' _ _ (set_of p) h t _ instance finite_Inter {ι : Sort*} [nonempty ι] (t : ι → set α) [∀ i, finite (t i)] : finite (⋂ i, t i) := finite.set.subset (t $ classical.arbitrary ι) (Inter_subset _ _) instance finite_insert (a : α) (s : set α) [finite s] : finite (insert a s : set α) := finite.set.finite_union {a} s instance finite_image (s : set α) (f : α → β) [finite s] : finite (f '' s) := by { casesI nonempty_fintype s, apply_instance } instance finite_replacement [finite α] (f : α → β) : finite {(f x) | (x : α)} := finite.set.finite_range f instance finite_prod (s : set α) (t : set β) [finite s] [finite t] : finite (s ×ˢ t : set (α × β)) := finite.of_equiv _ (equiv.set.prod s t).symm instance finite_image2 (f : α → β → γ) (s : set α) (t : set β) [finite s] [finite t] : finite (image2 f s t : set γ) := by { rw ← image_prod, apply_instance } instance finite_seq (f : set (α → β)) (s : set α) [finite f] [finite s] : finite (f.seq s) := by { rw seq_def, apply_instance } end finite.set namespace set /-! ### Constructors for `set.finite` Every constructor here should have a corresponding `fintype` instance in the previous section (or in the `fintype` module). The implementation of these constructors ideally should be no more than `set.to_finite`, after possibly setting up some `fintype` and classical `decidable` instances. -/ section set_finite_constructors @[nontriviality] lemma finite.of_subsingleton [subsingleton α] (s : set α) : s.finite := s.to_finite theorem finite_univ [finite α] : (@univ α).finite := set.to_finite _ theorem finite_univ_iff : (@univ α).finite ↔ finite α := finite_coe_iff.symm.trans (equiv.set.univ α).finite_iff alias finite_univ_iff ↔ _root_.finite.of_finite_univ _ theorem finite.union {s t : set α} (hs : s.finite) (ht : t.finite) : (s ∪ t).finite := by { casesI hs, casesI ht, apply to_finite } theorem finite.finite_of_compl {s : set α} (hs : s.finite) (hsc : sᶜ.finite) : finite α := by { rw [← finite_univ_iff, ← union_compl_self s], exact hs.union hsc } lemma finite.sup {s t : set α} : s.finite → t.finite → (s ⊔ t).finite := finite.union theorem finite.sep {s : set α} (hs : s.finite) (p : α → Prop) : {a ∈ s | p a}.finite := by { casesI hs, apply to_finite } theorem finite.inter_of_left {s : set α} (hs : s.finite) (t : set α) : (s ∩ t).finite := by { casesI hs, apply to_finite } theorem finite.inter_of_right {s : set α} (hs : s.finite) (t : set α) : (t ∩ s).finite := by { casesI hs, apply to_finite } theorem finite.inf_of_left {s : set α} (h : s.finite) (t : set α) : (s ⊓ t).finite := h.inter_of_left t theorem finite.inf_of_right {s : set α} (h : s.finite) (t : set α) : (t ⊓ s).finite := h.inter_of_right t theorem finite.subset {s : set α} (hs : s.finite) {t : set α} (ht : t ⊆ s) : t.finite := by { casesI hs, haveI := finite.set.subset _ ht, apply to_finite } theorem finite.diff {s : set α} (hs : s.finite) (t : set α) : (s \ t).finite := by { casesI hs, apply to_finite } theorem finite.of_diff {s t : set α} (hd : (s \ t).finite) (ht : t.finite) : s.finite := (hd.union ht).subset $ subset_diff_union _ _ theorem finite_Union [finite ι] {f : ι → set α} (H : ∀ i, (f i).finite) : (⋃ i, f i).finite := by { haveI := λ i, (H i).fintype, apply to_finite } theorem finite.sUnion {s : set (set α)} (hs : s.finite) (H : ∀ t ∈ s, set.finite t) : (⋃₀ s).finite := by { casesI hs, haveI := λ (i : s), (H i i.2).to_subtype, apply to_finite } theorem finite.bUnion {ι} {s : set ι} (hs : s.finite) {t : ι → set α} (ht : ∀ i ∈ s, (t i).finite) : (⋃(i ∈ s), t i).finite := by { classical, casesI hs, haveI := fintype_bUnion s t (λ i hi, (ht i hi).fintype), apply to_finite } /-- Dependent version of `finite.bUnion`. -/ theorem finite.bUnion' {ι} {s : set ι} (hs : s.finite) {t : Π (i ∈ s), set α} (ht : ∀ i ∈ s, (t i ‹_›).finite) : (⋃(i ∈ s), t i ‹_›).finite := by { casesI hs, rw [bUnion_eq_Union], apply finite_Union (λ (i : s), ht i.1 i.2), } theorem finite.sInter {α : Type*} {s : set (set α)} {t : set α} (ht : t ∈ s) (hf : t.finite) : (⋂₀ s).finite := hf.subset (sInter_subset_of_mem ht) theorem finite.bind {α β} {s : set α} {f : α → set β} (h : s.finite) (hf : ∀ a ∈ s, (f a).finite) : (s >>= f).finite := h.bUnion hf @[simp] theorem finite_empty : (∅ : set α).finite := to_finite _ @[simp] theorem finite_singleton (a : α) : ({a} : set α).finite := to_finite _ theorem finite_pure (a : α) : (pure a : set α).finite := to_finite _ @[simp] theorem finite.insert (a : α) {s : set α} (hs : s.finite) : (insert a s).finite := by { casesI hs, apply to_finite } theorem finite.image {s : set α} (f : α → β) (hs : s.finite) : (f '' s).finite := by { casesI hs, apply to_finite } theorem finite_range (f : ι → α) [finite ι] : (range f).finite := to_finite _ lemma finite.dependent_image {s : set α} (hs : s.finite) (F : Π i ∈ s, β) : {y : β | ∃ x (hx : x ∈ s), y = F x hx}.finite := by { casesI hs, simpa [range, eq_comm] using finite_range (λ x : s, F x x.2) } theorem finite.map {α β} {s : set α} : ∀ (f : α → β), s.finite → (f <$> s).finite := finite.image theorem finite.of_finite_image {s : set α} {f : α → β} (h : (f '' s).finite) (hi : set.inj_on f s) : s.finite := by { casesI h, exact ⟨fintype.of_injective (λ a, (⟨f a.1, mem_image_of_mem f a.2⟩ : f '' s)) (λ a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq)⟩ } lemma finite_of_finite_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hs : s ⊆ range f) : s.finite := by { rw [← image_preimage_eq_of_subset hs], exact finite.image f h } theorem finite.of_preimage {f : α → β} {s : set β} (h : (f ⁻¹' s).finite) (hf : surjective f) : s.finite := hf.image_preimage s ▸ h.image _ theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : s.finite) : (f ⁻¹' s).finite := (h.subset (image_preimage_subset f s)).of_finite_image I theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := h.preimage (λ _ _ _ _ h', f.injective h') lemma finite_lt_nat (n : ℕ) : set.finite {i | i < n} := to_finite _ lemma finite_le_nat (n : ℕ) : set.finite {i | i ≤ n} := to_finite _ lemma finite.prod {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : (s ×ˢ t : set (α × β)).finite := by { casesI hs, casesI ht, apply to_finite } lemma finite.off_diag {s : set α} (hs : s.finite) : s.off_diag.finite := by { classical, casesI hs, apply set.to_finite } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : (image2 f s t).finite := by { casesI hs, casesI ht, apply to_finite } theorem finite.seq {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f.seq s).finite := by { classical, casesI hf, casesI hs, apply to_finite } theorem finite.seq' {α β : Type u} {f : set (α → β)} {s : set α} (hf : f.finite) (hs : s.finite) : (f <*> s).finite := hf.seq hs theorem finite_mem_finset (s : finset α) : {a | a ∈ s}.finite := to_finite _ lemma subsingleton.finite {s : set α} (h : s.subsingleton) : s.finite := h.induction_on finite_empty finite_singleton lemma finite_preimage_inl_and_inr {s : set (α ⊕ β)} : (sum.inl ⁻¹' s).finite ∧ (sum.inr ⁻¹' s).finite ↔ s.finite := ⟨λ h, image_preimage_inl_union_image_preimage_inr s ▸ (h.1.image _).union (h.2.image _), λ h, ⟨h.preimage (sum.inl_injective.inj_on _), h.preimage (sum.inr_injective.inj_on _)⟩⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s : set α, s.finite ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨s, s.finite_to_set, hs⟩⟩ /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : a.finite) : {b | b ⊆ a}.finite := ⟨fintype.of_finset ((finset.powerset h.to_finset).map finset.coe_emb.1) $ λ s, by simpa [← @exists_finite_iff_finset α (λ t, t ⊆ a ∧ t = s), subset_to_finset_iff, ← and.assoc] using h.subset⟩ /-- Finite product of finite sets is finite -/ lemma finite.pi {δ : Type*} [finite δ] {κ : δ → Type*} {t : Π d, set (κ d)} (ht : ∀ d, (t d).finite) : (pi univ t).finite := begin casesI nonempty_fintype δ, lift t to Π d, finset (κ d) using ht, classical, rw ← fintype.coe_pi_finset, apply finset.finite_to_set end /-- A finite union of finsets is finite. -/ lemma union_finset_finite_of_range_finite (f : α → finset β) (h : (range f).finite) : (⋃ a, (f a : set β)).finite := by { rw ← bUnion_range, exact h.bUnion (λ y hy, y.finite_to_set) } lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : (range f).finite) (hg : (range g).finite) : (range (λ x, if p x then f x else g x)).finite := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : (range (λ x : α, c)).finite := (finite_singleton c).subset range_const_subset end set_finite_constructors /-! ### Properties -/ instance finite.inhabited : inhabited {s : set α // s.finite} := ⟨⟨∅, finite_empty⟩⟩ @[simp] lemma finite_union {s t : set α} : (s ∪ t).finite ↔ s.finite ∧ t.finite := ⟨λ h, ⟨h.subset (subset_union_left _ _), h.subset (subset_union_right _ _)⟩, λ ⟨hs, ht⟩, hs.union ht⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).finite ↔ s.finite := ⟨λ h, h.of_finite_image hi, finite.image _⟩ lemma univ_finite_iff_nonempty_fintype : (univ : set α).finite ↔ nonempty (fintype α) := ⟨λ h, ⟨fintype_of_finite_univ h⟩, λ ⟨_i⟩, by exactI finite_univ⟩ @[simp] lemma finite.to_finset_singleton {a : α} (ha : ({a} : set α).finite := finite_singleton _) : ha.to_finset = {a} := finset.ext $ by simp @[simp] lemma finite.to_finset_insert [decidable_eq α] {s : set α} {a : α} (hs : (insert a s).finite) : hs.to_finset = insert a (hs.subset $ subset_insert _ _).to_finset := finset.ext $ by simp lemma finite.to_finset_insert' [decidable_eq α] {a : α} {s : set α} (hs : s.finite) : (hs.insert a).to_finset = insert a hs.to_finset := finite.to_finset_insert _ lemma finite.to_finset_prod {s : set α} {t : set β} (hs : s.finite) (ht : t.finite) : hs.to_finset ×ˢ ht.to_finset = (hs.prod ht).to_finset := finset.ext $ by simp lemma finite.to_finset_off_diag {s : set α} [decidable_eq α] (hs : s.finite) : hs.off_diag.to_finset = hs.to_finset.off_diag := finset.ext $ by simp lemma finite.fin_embedding {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n ↪ α), range f = s := ⟨_, (fintype.equiv_fin (h.to_finset : set α)).symm.as_embedding, by simp⟩ lemma finite.fin_param {s : set α} (h : s.finite) : ∃ (n : ℕ) (f : fin n → α), injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding in ⟨n, f, f.injective, hf⟩ lemma finite_option {s : set (option α)} : s.finite ↔ {x : α | some x ∈ s}.finite := ⟨λ h, h.preimage_embedding embedding.some, λ h, ((h.image some).insert none).subset $ λ x, option.cases_on x (λ _, or.inl rfl) (λ x hx, or.inr $ mem_image_of_mem _ hx)⟩ lemma finite_image_fst_and_snd_iff {s : set (α × β)} : (prod.fst '' s).finite ∧ (prod.snd '' s).finite ↔ s.finite := ⟨λ h, (h.1.prod h.2).subset $ λ x h, ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, λ h, ⟨h.image _, h.image _⟩⟩ lemma forall_finite_image_eval_iff {δ : Type*} [finite δ] {κ : δ → Type*} {s : set (Π d, κ d)} : (∀ d, (eval d '' s).finite) ↔ s.finite := ⟨λ h, (finite.pi h).subset $ subset_pi_eval_image _ _, λ h d, h.image _⟩ lemma finite_subset_Union {s : set α} (hs : s.finite) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, I.finite ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, λ x hx, _⟩, rw [bUnion_range, mem_Union], exact ⟨⟨x, hx⟩, hf _⟩ end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : t.finite) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, I.finite ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, (σ i).finite) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : s.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → set.finite s → C s → C (insert a s)) : C s := begin lift s to finset α using h, induction s using finset.cons_induction_on with a s ha hs, { rwa [finset.coe_empty] }, { rw [finset.coe_cons], exact @H1 a s ha (set.to_finite _) hs } end /-- Analogous to `finset.induction_on'`. -/ @[elab_as_eliminator] theorem finite.induction_on' {C : set α → Prop} {S : set α} (h : S.finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → C s → C (insert a s)) : C S := begin refine @set.finite.induction_on α (λ s, s ⊆ S → C s) S h (λ _, H0) _ subset.rfl, intros a s has hsf hCs haS, rw insert_subset at haS, exact H1 haS.1 haS.2 has (hCs haS.2) end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀ (s : set α), s.finite → Prop} {s : set α} (h : s.finite) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀ h : set.finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀ h : s.finite, C s h, from finite.induction_on h (λ h, H0) (λ a s has hs ih h, H1 has hs (ih _)), this h section local attribute [instance] nat.fintype_Iio /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t : set γ, t.finite → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ end /-! ### Cardinality -/ theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card theorem card_fintype_insert_of_not_mem {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert_of_not_mem s h) = fintype.card s + 1 := by rw [fintype_insert_of_not_mem, fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert_of_not_mem s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := fintype.card_lt_of_injective_not_surjective (set.inclusion h.1) (set.inclusion_injective h.1) $ λ hst, (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := fintype.card_le_of_injective (set.inclusion hsub) (set.inclusion_injective hsub) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.of_injective f hf lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := begin rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], refine fintype.card_congr (equiv.set_congr _), ext x, show x ∈ h.to_finset ↔ x ∈ s, simp, end lemma card_ne_eq [fintype α] (a : α) [fintype {x : α | x ≠ a}] : fintype.card {x : α | x ≠ a} = fintype.card α - 1 := begin haveI := classical.dec_eq α, rw [←to_finset_card, to_finset_ne_eq_erase, finset.card_erase_of_mem (finset.mem_univ _), finset.card_univ], end /-! ### Infinite sets -/ theorem infinite_univ_iff : (@univ α).infinite ↔ infinite α := by rw [set.infinite, finite_univ_iff, not_finite_iff_infinite] theorem infinite_univ [h : infinite α] : (@univ α).infinite := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : infinite s ↔ s.infinite := not_finite_iff_infinite.symm.trans finite_coe_iff.not alias infinite_coe_iff ↔ _ infinite.to_subtype /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : s.infinite) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : s.infinite) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ lemma infinite.nonempty {s : set α} (h : s.infinite) : s.nonempty := let a := infinite.nat_embedding s h 37 in ⟨a.1, a.2⟩ lemma infinite_of_finite_compl [infinite α] {s : set α} (hs : sᶜ.finite) : s.infinite := λ h, set.infinite_univ (by simpa using hs.union h) lemma finite.infinite_compl [infinite α] {s : set α} (hs : s.finite) : sᶜ.infinite := λ h, set.infinite_univ (by simpa using hs.union h) protected theorem infinite.mono {s t : set α} (h : s ⊆ t) : s.infinite → t.infinite := mt (λ ht, ht.subset h) lemma infinite.diff {s t : set α} (hs : s.infinite) (ht : t.finite) : (s \ t).infinite := λ h, hs $ h.of_diff ht @[simp] lemma infinite_union {s t : set α} : (s ∪ t).infinite ↔ s.infinite ∨ t.infinite := by simp only [set.infinite, finite_union, not_and_distrib] theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : (f '' s).infinite ↔ s.infinite := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : s.infinite) : t.infinite := ((infinite_image_iff hi).2 hs).mono (maps_to'.mp hm) theorem infinite.exists_ne_map_eq_of_maps_to {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin contrapose! ht, exact infinite_of_inj_on_maps_to (λ x hx y hy, not_imp_not.1 (ht x hx y hy)) hf hs end theorem infinite_range_of_injective [infinite α] {f : α → β} (hi : injective f) : (range f).infinite := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : s.infinite := by { rw ←range_subset_iff at hf, exact (infinite_range_of_injective hi).mono hf } lemma infinite.exists_nat_lt {s : set ℕ} (hs : s.infinite) (n : ℕ) : ∃ m ∈ s, n < m := let ⟨m, hm⟩ := (hs.diff $ set.finite_le_nat n).nonempty in ⟨m, by simpa using hm⟩ lemma infinite.exists_not_mem_finset {s : set α} (hs : s.infinite) (f : finset α) : ∃ a ∈ s, a ∉ f := let ⟨a, has, haf⟩ := (hs.diff (to_finite f)).nonempty in ⟨a, has, λ h, haf $ finset.mem_coe.1 h⟩ /-! ### Order properties -/ lemma finite_is_top (α : Type*) [partial_order α] : {x : α | is_top x}.finite := (subsingleton_is_top α).finite lemma finite_is_bot (α : Type*) [partial_order α] : {x : α | is_bot x}.finite := (subsingleton_is_bot α).finite theorem infinite.exists_lt_map_eq_of_maps_to [linear_order α] {s : set α} {t : set β} {f : α → β} (hs : s.infinite) (hf : maps_to f s t) (ht : t.finite) : ∃ (x ∈ s) (y ∈ s), x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_maps_to hf ht in hxy.lt_or_lt.elim (λ hxy, ⟨x, hx, y, hy, hxy, hf⟩) (λ hyx, ⟨y, hy, x, hx, hyx, hf.symm⟩) lemma finite.exists_lt_map_eq_of_forall_mem [linear_order α] [infinite α] {t : set β} {f : α → β} (hf : ∀ a, f a ∈ t) (ht : t.finite) : ∃ a b, a < b ∧ f a = f b := begin rw ←maps_univ_to at hf, obtain ⟨a, -, b, -, h⟩ := (@infinite_univ α _).exists_lt_map_eq_of_maps_to hf ht, exact ⟨a, b, h⟩, end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_min_image f ⟨x, h1.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : s.finite) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using h1.to_finset.exists_max_image f ⟨x, h1.mem_to_finset.2 hx⟩ theorem exists_lower_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f a ≤ f b := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_min_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end theorem exists_upper_bound_image [hα : nonempty α] [linear_order β] (s : set α) (f : α → β) (h : s.finite) : ∃ (a : α), ∀ b ∈ s, f b ≤ f a := begin by_cases hs : set.nonempty s, { exact let ⟨x₀, H, hx₀⟩ := set.exists_max_image s f h hs in ⟨x₀, λ x hx, hx₀ x hx⟩ }, { exact nonempty.elim hα (λ a, ⟨a, λ x hx, absurd (set.nonempty_of_mem hx) hs⟩) } end lemma finite.supr_binfi_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := begin revert hf, refine hs.induction_on _ _, { intro hf, simp [supr_const] }, { intros a s has hs ihs hf, rw [ball_insert_iff] at hf, simp only [infi_insert, ← ihs hf.2], exact supr_inf_of_monotone hf.1 (λ j₁ j₂ hj, infi₂_mono $ λ i hi, hf.2 i hi hj) } end lemma finite.supr_binfi_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨆ j, ⨅ i ∈ s, f i j) = ⨅ i ∈ s, ⨆ j, f i j := @finite.supr_binfi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ hs _ (λ i hi, (hf i hi).dual_left) lemma finite.infi_bsupr_of_monotone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, monotone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_antitone (λ i hi, (hf i hi).dual_right) lemma finite.infi_bsupr_of_antitone {ι ι' α : Type*} [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {s : set ι} (hs : s.finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, antitone (f i)) : (⨅ j, ⨆ i ∈ s, f i j) = ⨆ i ∈ s, ⨅ j, f i j := hs.supr_binfi_of_monotone (λ i hi, (hf i hi).dual_right) lemma _root_.supr_infi_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := by simpa only [infi_univ] using finite_univ.supr_binfi_of_monotone (λ i hi, hf i) lemma _root_.supr_infi_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.frame α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨆ j, ⨅ i, f i j) = ⨅ i, ⨆ j, f i j := @supr_infi_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ _ (λ i, (hf i).dual_left) lemma _root_.infi_supr_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (swap (≤))] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, monotone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_antitone (λ i, (hf i).dual_right) lemma _root_.infi_supr_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [nonempty ι'] [is_directed ι' (≤)] [order.coframe α] {f : ι → ι' → α} (hf : ∀ i, antitone (f i)) : (⨅ j, ⨆ i, f i j) = ⨆ i, ⨅ j, f i j := supr_infi_of_monotone (λ i, (hf i).dual_right) /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_monotone hs /-- A decreasing union distributes over finite intersection. -/ lemma Union_Inter_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := supr_infi_of_antitone hs /-- An increasing intersection distributes over finite union. -/ lemma Inter_Union_of_monotone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (swap (≤))] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_monotone hs /-- A decreasing intersection distributes over finite union. -/ lemma Inter_Union_of_antitone {ι ι' α : Type*} [finite ι] [preorder ι'] [is_directed ι' (≤)] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, antitone (s i)) : (⋂ j : ι', ⋃ i : ι, s i j) = ⋃ i : ι, ⋂ j : ι', s i j := infi_supr_of_antitone hs lemma Union_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] {α : ι → Type*} {I : set ι} {s : Π i, ι' → set (α i)} (hI : I.finite) (hs : ∀ i ∈ I, monotone (s i)) : (⋃ j : ι', I.pi (λ i, s i j)) = I.pi (λ i, ⋃ j, s i j) := begin simp only [pi_def, bInter_eq_Inter, preimage_Union], haveI := hI.fintype, exact Union_Inter_of_monotone (λ i j₁ j₂ h, preimage_mono $ hs i i.2 h) end lemma Union_univ_pi_of_monotone {ι ι' : Type*} [linear_order ι'] [nonempty ι'] [finite ι] {α : ι → Type*} {s : Π i, ι' → set (α i)} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', pi univ (λ i, s i j)) = pi univ (λ i, ⋃ j, s i j) := Union_pi_of_monotone finite_univ (λ i _, hs i) lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : (range (λ x, nat.find_greatest (P x) b)).finite := (finite_le_nat b).subset $ range_subset_iff.2 $ λ x, nat.find_greatest_le _ lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃ a ∈ s, ∀ a' ∈ s, f a ≤ f a' → f a = f a' := begin refine h.induction_on _ _, { exact λ h, absurd h not_nonempty_empty }, intros a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, λ c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, λ c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : s.finite) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : I.finite) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) lemma infinite_of_not_bdd_above : ¬ bdd_above s → s.infinite := mt finite.bdd_above end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : s.finite) : bdd_below s := @finite.bdd_above αᵒᵈ _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : I.finite) : bdd_below (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, bdd_below (S i) := @finite.bdd_above_bUnion αᵒᵈ _ _ _ _ _ H lemma infinite_of_not_bdd_below : ¬ bdd_below s → s.infinite := begin contrapose!, rw not_infinite, apply finite.bdd_below, end end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset /-- If a set `s` does not contain any elements between any pair of elements `x, z ∈ s` with `x ≤ z` (i.e if given `x, y, z ∈ s` such that `x ≤ y ≤ z`, then `y` is either `x` or `z`), then `s` is finite. -/ lemma set.finite_of_forall_between_eq_endpoints {α : Type*} [linear_order α] (s : set α) (h : ∀ (x ∈ s) (y ∈ s) (z ∈ s), x ≤ y → y ≤ z → x = y ∨ y = z) : set.finite s := begin by_contra hinf, change s.infinite at hinf, rcases hinf.exists_subset_card_eq 3 with ⟨t, hts, ht⟩, let f := t.order_iso_of_fin ht, let x := f 0, let y := f 1, let z := f 2, have := h x (hts x.2) y (hts y.2) z (hts z.2) (f.monotone $ by dec_trivial) (f.monotone $ by dec_trivial), have key₁ : (0 : fin 3) ≠ 1 := by dec_trivial, have key₂ : (1 : fin 3) ≠ 2 := by dec_trivial, cases this, { dsimp only [x, y] at this, exact key₁ (f.injective $ subtype.coe_injective this) }, { dsimp only [y, z] at this, exact key₂ (f.injective $ subtype.coe_injective this) } end
edbf7274abce707b31b9894957f9ed6f2bcfd484
94e33a31faa76775069b071adea97e86e218a8ee
/src/model_theory/syntax.lean
7d7c4c35869aaf3d606a366c944b3d885ad69400
[ "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
35,949
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import data.list.prod_sigma import data.set.prod import logic.equiv.fin import model_theory.language_map /-! # Basics on First-Order Syntax This file defines first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * A `first_order.language.term` is defined so that `L.term α` is the type of `L`-terms with free variables indexed by `α`. * A `first_order.language.formula` is defined so that `L.formula α` is the type of `L`-formulas with free variables indexed by `α`. * A `first_order.language.sentence` is a formula with no free variables. * A `first_order.language.Theory` is a set of sentences. * The variables of terms and formulas can be relabelled with `first_order.language.term.relabel`, `first_order.language.bounded_formula.relabel`, and `first_order.language.formula.relabel`. * Given an operation on terms and an operation on relations, `first_order.language.bounded_formula.map_term_rel` gives an operation on formulas. * `first_order.language.bounded_formula.cast_le` adds more `fin`-indexed variables. * `first_order.language.bounded_formula.lift_at` raises the indexes of the `fin`-indexed variables above a particular index. * `first_order.language.term.subst` and `first_order.language.bounded_formula.subst` substitute variables with given terms. * Language maps can act on syntactic objects with functions such as `first_order.language.Lhom.on_formula`. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by `n : fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v w u' v' namespace first_order namespace language variables (L : language.{u v}) {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} {γ : Type*} open_locale first_order open Structure fin /-- A term on `α` is either a variable indexed by an element of `α` or a function symbol applied to simpler terms. -/ inductive term (α : Type u') : Type (max u u') | var {} : ∀ (a : α), term | func {} : ∀ {l : ℕ} (f : L.functions l) (ts : fin l → term), term export term variable {L} namespace term open finset /-- The `finset` of variables used in a given term. -/ @[simp] def var_finset [decidable_eq α] : L.term α → finset α | (var i) := {i} | (func f ts) := univ.bUnion (λ i, (ts i).var_finset) /-- The `finset` of variables from the left side of a sum used in a given term. -/ @[simp] def var_finset_left [decidable_eq α] : L.term (α ⊕ β) → finset α | (var (sum.inl i)) := {i} | (var (sum.inr i)) := ∅ | (func f ts) := univ.bUnion (λ i, (ts i).var_finset_left) /-- Relabels a term's variables along a particular function. -/ @[simp] def relabel (g : α → β) : L.term α → L.term β | (var i) := var (g i) | (func f ts) := func f (λ i, (ts i).relabel) lemma relabel_id (t : L.term α) : t.relabel id = t := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_id_eq_id : (term.relabel id : L.term α → L.term α) = id := funext relabel_id @[simp] lemma relabel_relabel (f : α → β) (g : β → γ) (t : L.term α) : (t.relabel f).relabel g = t.relabel (g ∘ f) := begin induction t with _ _ _ _ ih, { refl, }, { simp [ih] }, end @[simp] lemma relabel_comp_relabel (f : α → β) (g : β → γ) : (term.relabel g ∘ term.relabel f : L.term α → L.term γ) = term.relabel (g ∘ f) := funext (relabel_relabel f g) /-- Restricts a term to use only a set of the given variables. -/ def restrict_var [decidable_eq α] : Π (t : L.term α) (f : t.var_finset → β), L.term β | (var a) f := var (f ⟨a, mem_singleton_self a⟩) | (func F ts) f := func F (λ i, (ts i).restrict_var (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) /-- Restricts a term to use only a set of the given variables on the left side of a sum. -/ def restrict_var_left [decidable_eq α] {γ : Type*} : Π (t : L.term (α ⊕ γ)) (f : t.var_finset_left → β), L.term (β ⊕ γ) | (var (sum.inl a)) f := var (sum.inl (f ⟨a, mem_singleton_self a⟩)) | (var (sum.inr a)) f := var (sum.inr a) | (func F ts) f := func F (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) end term /-- The representation of a constant symbol as a term. -/ def constants.term (c : L.constants) : (L.term α) := func c default /-- Applies a unary function to a term. -/ def functions.apply₁ (f : L.functions 1) (t : L.term α) : L.term α := func f ![t] /-- Applies a binary function to two terms. -/ def functions.apply₂ (f : L.functions 2) (t₁ t₂ : L.term α) : L.term α := func f ![t₁, t₂] namespace term instance inhabited_of_var [inhabited α] : inhabited (L.term α) := ⟨var default⟩ instance inhabited_of_constant [inhabited L.constants] : inhabited (L.term α) := ⟨(default : L.constants).term⟩ /-- Raises all of the `fin`-indexed variables of a term greater than or equal to `m` by `n'`. -/ def lift_at {n : ℕ} (n' m : ℕ) : L.term (α ⊕ fin n) → L.term (α ⊕ fin (n + n')) := relabel (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) /-- Substitutes the variables in a given term with terms. -/ @[simp] def subst : L.term α → (α → L.term β) → L.term β | (var a) tf := tf a | (func f ts) tf := (func f (λ i, (ts i).subst tf)) end term localized "prefix `&`:max := first_order.language.term.var ∘ sum.inr" in first_order namespace Lhom /-- Maps a term's symbols along a language map. -/ @[simp] def on_term (φ : L →ᴸ L') : L.term α → L'.term α | (var i) := var i | (func f ts) := func (φ.on_function f) (λ i, on_term (ts i)) @[simp] lemma id_on_term : ((Lhom.id L).on_term : L.term α → L.term α) = id := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end @[simp] lemma comp_on_term {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_term : L.term α → L''.term α) = φ.on_term ∘ ψ.on_term := begin ext t, induction t with _ _ _ _ ih, { refl }, { simp_rw [on_term, ih], refl, }, end end Lhom /-- Maps a term's symbols along a language equivalence. -/ @[simps] def Lequiv.on_term (φ : L ≃ᴸ L') : L.term α ≃ L'.term α := { to_fun := φ.to_Lhom.on_term, inv_fun := φ.inv_Lhom.on_term, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_term, φ.left_inv, Lhom.id_on_term], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_term, φ.right_inv, Lhom.id_on_term] } variables (L) (α) /-- `bounded_formula α n` is the type of formulas with free variables indexed by `α` and up to `n` additional free variables. -/ inductive bounded_formula : ℕ → Type (max u v u') | falsum {} {n} : bounded_formula n | equal {n} (t₁ t₂ : L.term (α ⊕ fin n)) : bounded_formula n | rel {n l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : bounded_formula n | imp {n} (f₁ f₂ : bounded_formula n) : bounded_formula n | all {n} (f : bounded_formula (n+1)) : bounded_formula n /-- `formula α` is the type of formulas with all free variables indexed by `α`. -/ @[reducible] def formula := L.bounded_formula α 0 /-- A sentence is a formula with no free variables. -/ @[reducible] def sentence := L.formula empty /-- A theory is a set of sentences. -/ @[reducible] def Theory := set L.sentence variables {L} {α} {n : ℕ} /-- Applies a relation to terms as a bounded formula. -/ def relations.bounded_formula {l : ℕ} (R : L.relations n) (ts : fin n → L.term (α ⊕ fin l)) : L.bounded_formula α l := bounded_formula.rel R ts /-- Applies a unary relation to a term as a bounded formula. -/ def relations.bounded_formula₁ (r : L.relations 1) (t : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t] /-- Applies a binary relation to two terms as a bounded formula. -/ def relations.bounded_formula₂ (r : L.relations 2) (t₁ t₂ : L.term (α ⊕ fin n)) : L.bounded_formula α n := r.bounded_formula ![t₁, t₂] /-- The equality of two terms as a bounded formula. -/ def term.bd_equal (t₁ t₂ : L.term (α ⊕ fin n)) : (L.bounded_formula α n) := bounded_formula.equal t₁ t₂ /-- Applies a relation to terms as a bounded formula. -/ def relations.formula (R : L.relations n) (ts : fin n → L.term α) : L.formula α := R.bounded_formula (λ i, (ts i).relabel sum.inl) /-- Applies a unary relation to a term as a formula. -/ def relations.formula₁ (r : L.relations 1) (t : L.term α) : L.formula α := r.formula ![t] /-- Applies a binary relation to two terms as a formula. -/ def relations.formula₂ (r : L.relations 2) (t₁ t₂ : L.term α) : L.formula α := r.formula ![t₁, t₂] /-- The equality of two terms as a first-order formula. -/ def term.equal (t₁ t₂ : L.term α) : (L.formula α) := (t₁.relabel sum.inl).bd_equal (t₂.relabel sum.inl) namespace bounded_formula instance : inhabited (L.bounded_formula α n) := ⟨falsum⟩ instance : has_bot (L.bounded_formula α n) := ⟨falsum⟩ /-- The negation of a bounded formula is also a bounded formula. -/ @[pattern] protected def not (φ : L.bounded_formula α n) : L.bounded_formula α n := φ.imp ⊥ /-- Puts an `∃` quantifier on a bounded formula. -/ @[pattern] protected def ex (φ : L.bounded_formula α (n + 1)) : L.bounded_formula α n := φ.not.all.not instance : has_top (L.bounded_formula α n) := ⟨bounded_formula.not ⊥⟩ instance : has_inf (L.bounded_formula α n) := ⟨λ f g, (f.imp g.not).not⟩ instance : has_sup (L.bounded_formula α n) := ⟨λ f g, f.not.imp g⟩ /-- The biimplication between two bounded formulas. -/ protected def iff (φ ψ : L.bounded_formula α n) := φ.imp ψ ⊓ ψ.imp φ open finset /-- The `finset` of variables used in a given formula. -/ @[simp] def free_var_finset [decidable_eq α] : ∀ {n}, L.bounded_formula α n → finset α | n falsum := ∅ | n (equal t₁ t₂) := t₁.var_finset_left ∪ t₂.var_finset_left | n (rel R ts) := univ.bUnion (λ i, (ts i).var_finset_left) | n (imp f₁ f₂) := f₁.free_var_finset ∪ f₂.free_var_finset | n (all f) := f.free_var_finset /-- Casts `L.bounded_formula α m` as `L.bounded_formula α n`, where `m ≤ n`. -/ @[simp] def cast_le : ∀ {m n : ℕ} (h : m ≤ n), L.bounded_formula α m → L.bounded_formula α n | m n h falsum := falsum | m n h (equal t₁ t₂) := equal (t₁.relabel (sum.map id (fin.cast_le h))) (t₂.relabel (sum.map id (fin.cast_le h))) | m n h (rel R ts) := rel R (term.relabel (sum.map id (fin.cast_le h)) ∘ ts) | m n h (imp f₁ f₂) := (f₁.cast_le h).imp (f₂.cast_le h) | m n h (all f) := (f.cast_le (add_le_add_right h 1)).all @[simp] lemma cast_le_rfl {n} (h : n ≤ n) (φ : L.bounded_formula α n) : φ.cast_le h = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq], }, { simp [fin.cast_le_of_eq, ih1, ih2], }, { simp [fin.cast_le_of_eq, ih3], }, end @[simp] lemma cast_le_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) (φ : L.bounded_formula α k) : (φ.cast_le km).cast_le mn = φ.cast_le (km.trans mn) := begin revert m n, induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3; intros m n km mn, { refl }, { simp }, { simp only [cast_le, eq_self_iff_true, heq_iff_eq, true_and], rw [← function.comp.assoc, relabel_comp_relabel], simp }, { simp [ih1, ih2] }, { simp only [cast_le, ih3] } end @[simp] lemma cast_le_comp_cast_le {k m n} (km : k ≤ m) (mn : m ≤ n) : (bounded_formula.cast_le mn ∘ bounded_formula.cast_le km : L.bounded_formula α k → L.bounded_formula α n) = bounded_formula.cast_le (km.trans mn) := funext (cast_le_cast_le km mn) /-- Restricts a bounded formula to only use a particular set of free variables. -/ def restrict_free_var [decidable_eq α] : Π {n : ℕ} (φ : L.bounded_formula α n) (f : φ.free_var_finset → β), L.bounded_formula β n | n falsum f := falsum | n (equal t₁ t₂) f := equal (t₁.restrict_var_left (f ∘ set.inclusion (subset_union_left _ _))) (t₂.restrict_var_left (f ∘ set.inclusion (subset_union_right _ _))) | n (rel R ts) f := rel R (λ i, (ts i).restrict_var_left (f ∘ set.inclusion (subset_bUnion_of_mem _ (mem_univ i)))) | n (imp φ₁ φ₂) f := (φ₁.restrict_free_var (f ∘ set.inclusion (subset_union_left _ _))).imp (φ₂.restrict_free_var (f ∘ set.inclusion (subset_union_right _ _))) | n (all φ) f := (φ.restrict_free_var f).all /-- Places universal quantifiers on all extra variables of a bounded formula. -/ def alls : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.all.alls /-- Places existential quantifiers on all extra variables of a bounded formula. -/ def exs : ∀ {n}, L.bounded_formula α n → L.formula α | 0 φ := φ | (n + 1) φ := φ.ex.exs /-- Maps bounded formulas along a map of terms and a map of relations. -/ def map_term_rel {g : ℕ → ℕ} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin (g n))) (fr : ∀ n, L.relations n → L'.relations n) (h : ∀ n, L'.bounded_formula β (g (n + 1)) → L'.bounded_formula β (g n + 1)) : ∀ {n}, L.bounded_formula α n → L'.bounded_formula β (g n) | n falsum := falsum | n (equal t₁ t₂) := equal (ft _ t₁) (ft _ t₂) | n (rel R ts) := rel (fr _ R) (λ i, ft _ (ts i)) | n (imp φ₁ φ₂) := φ₁.map_term_rel.imp φ₂.map_term_rel | n (all φ) := (h n φ.map_term_rel).all /-- Raises all of the `fin`-indexed variables of a formula greater than or equal to `m` by `n'`. -/ def lift_at : ∀ {n : ℕ} (n' m : ℕ), L.bounded_formula α n → L.bounded_formula α (n + n') := λ n n' m φ, φ.map_term_rel (λ k t, t.lift_at n' m) (λ _, id) (λ _, cast_le (by rw [add_assoc, add_comm 1, add_assoc])) @[simp] lemma map_term_rel_map_term_rel {L'' : language} (ft : ∀ n, L.term (α ⊕ fin n) → L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n → L'.relations n) (ft' : ∀ n, L'.term (β ⊕ fin n) → L''.term (γ ⊕ fin n)) (fr' : ∀ n, L'.relations n → L''.relations n) {n} (φ : L.bounded_formula α n) : (φ.map_term_rel ft fr (λ _, id)).map_term_rel ft' fr' (λ _, id) = φ.map_term_rel (λ _, (ft' _) ∘ (ft _)) (λ _, (fr' _) ∘ (fr _)) (λ _, id) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end @[simp] lemma map_term_rel_id_id_id {n} (φ : L.bounded_formula α n) : φ.map_term_rel (λ _, id) (λ _, id) (λ _, id) = φ := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [map_term_rel] }, { simp [map_term_rel] }, { simp [map_term_rel, ih1, ih2] }, { simp [map_term_rel, ih3], } end /-- An equivalence of bounded formulas given by an equivalence of terms and an equivalence of relations. -/ @[simps] def map_term_rel_equiv (ft : ∀ n, L.term (α ⊕ fin n) ≃ L'.term (β ⊕ fin n)) (fr : ∀ n, L.relations n ≃ L'.relations n) {n} : L.bounded_formula α n ≃ L'.bounded_formula β n := ⟨map_term_rel (λ n, ft n) (λ n, fr n) (λ _, id), map_term_rel (λ n, (ft n).symm) (λ n, (fr n).symm) (λ _, id), λ φ, by simp, λ φ, by simp⟩ /-- A function to help relabel the variables in bounded formulas. -/ def relabel_aux (g : α → β ⊕ fin n) (k : ℕ) : α ⊕ fin k → β ⊕ fin (n + k) := sum.map id fin_sum_fin_equiv ∘ equiv.sum_assoc _ _ _ ∘ sum.map g id @[simp] lemma sum_elim_comp_relabel_aux {m : ℕ} {g : α → (β ⊕ fin n)} {v : β → M} {xs : fin (n + m) → M} : sum.elim v xs ∘ relabel_aux g m = sum.elim (sum.elim v (xs ∘ cast_add m) ∘ g) (xs ∘ nat_add n) := begin ext x, cases x, { simp only [bounded_formula.relabel_aux, function.comp_app, sum.map_inl, sum.elim_inl], cases g x with l r; simp }, { simp [bounded_formula.relabel_aux] } end @[simp] lemma relabel_aux_sum_inl (k : ℕ) : relabel_aux (sum.inl : α → α ⊕ fin n) k = sum.map id (nat_add n) := begin ext x, cases x; { simp [relabel_aux] }, end /-- Relabels a bounded formula's variables along a particular function. -/ def relabel (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : L.bounded_formula β (n + k) := φ.map_term_rel (λ _ t, t.relabel (relabel_aux g _)) (λ _, id) (λ _, cast_le (ge_of_eq (add_assoc _ _ _))) @[simp] lemma relabel_falsum (g : α → (β ⊕ fin n)) {k} : (falsum : L.bounded_formula α k).relabel g = falsum := rfl @[simp] lemma relabel_bot (g : α → (β ⊕ fin n)) {k} : (⊥ : L.bounded_formula α k).relabel g = ⊥ := rfl @[simp] lemma relabel_imp (g : α → (β ⊕ fin n)) {k} (φ ψ : L.bounded_formula α k) : (φ.imp ψ).relabel g = (φ.relabel g).imp (ψ.relabel g) := rfl @[simp] lemma relabel_not (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α k) : φ.not.relabel g = (φ.relabel g).not := by simp [bounded_formula.not] @[simp] lemma relabel_all (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.all.relabel g = (φ.relabel g).all := begin rw [relabel, map_term_rel, relabel], simp, end @[simp] lemma relabel_ex (g : α → (β ⊕ fin n)) {k} (φ : L.bounded_formula α (k + 1)) : φ.ex.relabel g = (φ.relabel g).ex := by simp [bounded_formula.ex] @[simp] lemma relabel_sum_inl (φ : L.bounded_formula α n) : (φ.relabel sum.inl : L.bounded_formula α (0 + n)) = φ.cast_le (ge_of_eq (zero_add n)) := begin simp only [relabel, relabel_aux_sum_inl], induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [fin.nat_add_zero, cast_le_of_eq, map_term_rel] }, { simp [map_term_rel, ih1, ih2], }, { simp [map_term_rel, ih3, cast_le], }, end /-- Substitutes the variables in a given formula with terms. -/ @[simp] def subst {n : ℕ} (φ : L.bounded_formula α n) (f : α → L.term β) : L.bounded_formula β n := φ.map_term_rel (λ _ t, t.subst (sum.elim (term.relabel sum.inl ∘ f) (var ∘ sum.inr))) (λ _, id) (λ _, id) /-- Turns the extra variables of a bounded formula into free variables. -/ @[simp] def to_formula : ∀ {n : ℕ}, L.bounded_formula α n → L.formula (α ⊕ fin n) | n falsum := falsum | n (equal t₁ t₂) := t₁.equal t₂ | n (rel R ts) := R.formula ts | n (imp φ₁ φ₂) := φ₁.to_formula.imp φ₂.to_formula | n (all φ) := (φ.to_formula.relabel (sum.elim (sum.inl ∘ sum.inl) (sum.map sum.inr id ∘ fin_sum_fin_equiv.symm))).all variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} /-- An atomic formula is either equality or a relation symbol applied to terms. Note that `⊥` and `⊤` are not considered atomic in this convention. -/ inductive is_atomic : L.bounded_formula α n → Prop | equal (t₁ t₂ : L.term (α ⊕ fin n)) : is_atomic (bd_equal t₁ t₂) | rel {l : ℕ} (R : L.relations l) (ts : fin l → L.term (α ⊕ fin n)) : is_atomic (R.bounded_formula ts) lemma not_all_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_atomic := λ con, by cases con lemma not_ex_is_atomic (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_atomic := λ con, by cases con lemma is_atomic.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_atomic) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.lift_at {k m : ℕ} (h : is_atomic φ) : (φ.lift_at k m).is_atomic := is_atomic.rec_on h (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) lemma is_atomic.cast_le {h : l ≤ n} (hφ : is_atomic φ) : (φ.cast_le h).is_atomic := is_atomic.rec_on hφ (λ _ _, is_atomic.equal _ _) (λ _ _ _, is_atomic.rel _ _) /-- A quantifier-free formula is a formula defined without quantifiers. These are all equivalent to boolean combinations of atomic formulas. -/ inductive is_qf : L.bounded_formula α n → Prop | falsum : is_qf falsum | of_is_atomic {φ} (h : is_atomic φ) : is_qf φ | imp {φ₁ φ₂} (h₁ : is_qf φ₁) (h₂ : is_qf φ₂) : is_qf (φ₁.imp φ₂) lemma is_atomic.is_qf {φ : L.bounded_formula α n} : is_atomic φ → is_qf φ := is_qf.of_is_atomic lemma is_qf_bot : is_qf (⊥ : L.bounded_formula α n) := is_qf.falsum lemma is_qf.not {φ : L.bounded_formula α n} (h : is_qf φ) : is_qf φ.not := h.imp is_qf_bot lemma is_qf.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_qf) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_qf := is_qf.rec_on h is_qf_bot (λ _ h, (h.relabel f).is_qf) (λ _ _ _ _ h1 h2, h1.imp h2) lemma is_qf.lift_at {k m : ℕ} (h : is_qf φ) : (φ.lift_at k m).is_qf := is_qf.rec_on h is_qf_bot (λ _ ih, ih.lift_at.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma is_qf.cast_le {h : l ≤ n} (hφ : is_qf φ) : (φ.cast_le h).is_qf := is_qf.rec_on hφ is_qf_bot (λ _ ih, ih.cast_le.is_qf) (λ _ _ _ _ ih1 ih2, ih1.imp ih2) lemma not_all_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.all.is_qf := λ con, begin cases con with _ con, exact (φ.not_all_is_atomic con), end lemma not_ex_is_qf (φ : L.bounded_formula α (n + 1)) : ¬ φ.ex.is_qf := λ con, begin cases con with _ con _ _ con, { exact (φ.not_ex_is_atomic con) }, { exact not_all_is_qf _ con } end /-- Indicates that a bounded formula is in prenex normal form - that is, it consists of quantifiers applied to a quantifier-free formula. -/ inductive is_prenex : ∀ {n}, L.bounded_formula α n → Prop | of_is_qf {n} {φ : L.bounded_formula α n} (h : is_qf φ) : is_prenex φ | all {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.all | ex {n} {φ : L.bounded_formula α (n + 1)} (h : is_prenex φ) : is_prenex φ.ex lemma is_qf.is_prenex {φ : L.bounded_formula α n} : is_qf φ → is_prenex φ := is_prenex.of_is_qf lemma is_atomic.is_prenex {φ : L.bounded_formula α n} (h : is_atomic φ) : is_prenex φ := h.is_qf.is_prenex lemma is_prenex.induction_on_all_not {P : ∀ {n}, L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_prenex φ) (hq : ∀ {m} {ψ : L.bounded_formula α m}, ψ.is_qf → P ψ) (ha : ∀ {m} {ψ : L.bounded_formula α (m + 1)}, P ψ → P ψ.all) (hn : ∀ {m} {ψ : L.bounded_formula α m}, P ψ → P ψ.not) : P φ := is_prenex.rec_on h (λ _ _, hq) (λ _ _ _, ha) (λ _ _ _ ih, hn (ha (hn ih))) lemma is_prenex.relabel {m : ℕ} {φ : L.bounded_formula α m} (h : φ.is_prenex) (f : α → β ⊕ (fin n)) : (φ.relabel f).is_prenex := is_prenex.rec_on h (λ _ _ h, (h.relabel f).is_prenex) (λ _ _ _ h, by simp [h.all]) (λ _ _ _ h, by simp [h.ex]) lemma is_prenex.cast_le (hφ : is_prenex φ) : ∀ {n} {h : l ≤ n}, (φ.cast_le h).is_prenex := is_prenex.rec_on hφ (λ _ _ ih _ _, ih.cast_le.is_prenex) (λ _ _ _ ih _ _, ih.all) (λ _ _ _ ih _ _, ih.ex) lemma is_prenex.lift_at {k m : ℕ} (h : is_prenex φ) : (φ.lift_at k m).is_prenex := is_prenex.rec_on h (λ _ _ ih, ih.lift_at.is_prenex) (λ _ _ _ ih, ih.cast_le.all) (λ _ _ _ ih, ih.cast_le.ex) /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` is quantifier-free and `ψ` is in prenex normal form, then `φ.to_prenex_imp_right ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp_right : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n φ (bounded_formula.ex ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).ex | n φ (all ψ) := ((φ.lift_at 1 n).to_prenex_imp_right ψ).all | n φ ψ := φ.imp ψ lemma is_qf.to_prenex_imp_right {φ : L.bounded_formula α n} : Π {ψ : L.bounded_formula α n}, is_qf ψ → (φ.to_prenex_imp_right ψ = φ.imp ψ) | _ is_qf.falsum := rfl | _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ (is_qf.imp is_qf.falsum _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp_right ψ) := begin induction hψ with _ _ hψ _ _ _ ih1 _ _ _ ih2, { rw hψ.to_prenex_imp_right, exact (hφ.imp hψ).is_prenex }, { exact (ih1 hφ.lift_at).all }, { exact (ih2 hφ.lift_at).ex } end /-- An auxiliary operation to `first_order.language.bounded_formula.to_prenex`. If `φ` and `ψ` are in prenex normal form, then `φ.to_prenex_imp ψ` is a prenex normal form for `φ.imp ψ`. -/ def to_prenex_imp : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n → L.bounded_formula α n | n (bounded_formula.ex φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).all | n (all φ) ψ := (φ.to_prenex_imp (ψ.lift_at 1 n)).ex | _ φ ψ := φ.to_prenex_imp_right ψ lemma is_qf.to_prenex_imp : Π {φ ψ : L.bounded_formula α n}, φ.is_qf → φ.to_prenex_imp ψ = φ.to_prenex_imp_right ψ | _ _ is_qf.falsum := rfl | _ _ (is_qf.of_is_atomic (is_atomic.equal _ _)) := rfl | _ _ (is_qf.of_is_atomic (is_atomic.rel _ _)) := rfl | _ _ (is_qf.imp is_qf.falsum _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.equal _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.of_is_atomic (is_atomic.rel _ _)) _) := rfl | _ _ (is_qf.imp (is_qf.imp _ _) _) := rfl lemma is_prenex_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) : is_prenex (φ.to_prenex_imp ψ) := begin induction hφ with _ _ hφ _ _ _ ih1 _ _ _ ih2, { rw hφ.to_prenex_imp, exact is_prenex_to_prenex_imp_right hφ hψ }, { exact (ih1 hψ.lift_at).ex }, { exact (ih2 hψ.lift_at).all } end /-- For any bounded formula `φ`, `φ.to_prenex` is a semantically-equivalent formula in prenex normal form. -/ def to_prenex : ∀ {n}, L.bounded_formula α n → L.bounded_formula α n | _ falsum := ⊥ | _ (equal t₁ t₂) := t₁.bd_equal t₂ | _ (rel R ts) := rel R ts | _ (imp f₁ f₂) := f₁.to_prenex.to_prenex_imp f₂.to_prenex | _ (all f) := f.to_prenex.all lemma to_prenex_is_prenex (φ : L.bounded_formula α n) : φ.to_prenex.is_prenex := bounded_formula.rec_on φ (λ _, is_qf_bot.is_prenex) (λ _ _ _, (is_atomic.equal _ _).is_prenex) (λ _ _ _ _, (is_atomic.rel _ _).is_prenex) (λ _ _ _ h1 h2, is_prenex_to_prenex_imp h1 h2) (λ _ _, is_prenex.all) end bounded_formula namespace Lhom open bounded_formula /-- Maps a bounded formula's symbols along a language map. -/ @[simp] def on_bounded_formula (g : L →ᴸ L') : ∀ {k : ℕ}, L.bounded_formula α k → L'.bounded_formula α k | k falsum := falsum | k (equal t₁ t₂) := (g.on_term t₁).bd_equal (g.on_term t₂) | k (rel R ts) := (g.on_relation R).bounded_formula (g.on_term ∘ ts) | k (imp f₁ f₂) := (on_bounded_formula f₁).imp (on_bounded_formula f₂) | k (all f) := (on_bounded_formula f).all @[simp] lemma id_on_bounded_formula : ((Lhom.id L).on_bounded_formula : L.bounded_formula α n → L.bounded_formula α n) = id := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { rw [on_bounded_formula, Lhom.id_on_term, id.def, id.def, id.def, bd_equal] }, { rw [on_bounded_formula, Lhom.id_on_term], refl, }, { rw [on_bounded_formula, ih1, ih2, id.def, id.def, id.def] }, { rw [on_bounded_formula, ih3, id.def, id.def] } end @[simp] lemma comp_on_bounded_formula {L'' : language} (φ : L' →ᴸ L'') (ψ : L →ᴸ L') : ((φ.comp ψ).on_bounded_formula : L.bounded_formula α n → L''.bounded_formula α n) = φ.on_bounded_formula ∘ ψ.on_bounded_formula := begin ext f, induction f with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, comp_on_term, function.comp_app], refl, }, { simp only [on_bounded_formula, comp_on_relation, comp_on_term, function.comp_app], refl }, { simp only [on_bounded_formula, function.comp_app, ih1, ih2, eq_self_iff_true, and_self], }, { simp only [ih3, on_bounded_formula, function.comp_app] } end /-- Maps a formula's symbols along a language map. -/ def on_formula (g : L →ᴸ L') : L.formula α → L'.formula α := g.on_bounded_formula /-- Maps a sentence's symbols along a language map. -/ def on_sentence (g : L →ᴸ L') : L.sentence → L'.sentence := g.on_formula /-- Maps a theory's symbols along a language map. -/ def on_Theory (g : L →ᴸ L') (T : L.Theory) : L'.Theory := g.on_sentence '' T @[simp] lemma mem_on_Theory {g : L →ᴸ L'} {T : L.Theory} {φ : L'.sentence} : φ ∈ g.on_Theory T ↔ ∃ φ₀, φ₀ ∈ T ∧ g.on_sentence φ₀ = φ := set.mem_image _ _ _ end Lhom namespace Lequiv /-- Maps a bounded formula's symbols along a language equivalence. -/ @[simps] def on_bounded_formula (φ : L ≃ᴸ L') : L.bounded_formula α n ≃ L'.bounded_formula α n := { to_fun := φ.to_Lhom.on_bounded_formula, inv_fun := φ.inv_Lhom.on_bounded_formula, left_inv := by rw [function.left_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.left_inv, Lhom.id_on_bounded_formula], right_inv := by rw [function.right_inverse_iff_comp, ← Lhom.comp_on_bounded_formula, φ.right_inv, Lhom.id_on_bounded_formula] } lemma on_bounded_formula_symm (φ : L ≃ᴸ L') : (φ.on_bounded_formula.symm : L'.bounded_formula α n ≃ L.bounded_formula α n) = φ.symm.on_bounded_formula := rfl /-- Maps a formula's symbols along a language equivalence. -/ def on_formula (φ : L ≃ᴸ L') : L.formula α ≃ L'.formula α := φ.on_bounded_formula @[simp] lemma on_formula_apply (φ : L ≃ᴸ L') : (φ.on_formula : L.formula α → L'.formula α) = φ.to_Lhom.on_formula := rfl @[simp] lemma on_formula_symm (φ : L ≃ᴸ L') : (φ.on_formula.symm : L'.formula α ≃ L.formula α) = φ.symm.on_formula := rfl /-- Maps a sentence's symbols along a language equivalence. -/ @[simps] def on_sentence (φ : L ≃ᴸ L') : L.sentence ≃ L'.sentence := φ.on_formula end Lequiv localized "infix ` =' `:88 := first_order.language.term.bd_equal" in first_order -- input \~- or \simeq localized "infixr ` ⟹ `:62 := first_order.language.bounded_formula.imp" in first_order -- input \==> localized "prefix `∀'`:110 := first_order.language.bounded_formula.all" in first_order localized "prefix `∼`:max := first_order.language.bounded_formula.not" in first_order -- input \~, the ASCII character ~ has too low precedence localized "infix ` ⇔ `:61 := first_order.language.bounded_formula.iff" in first_order -- input \<=> localized "prefix `∃'`:110 := first_order.language.bounded_formula.ex" in first_order -- input \ex namespace formula /-- Relabels a formula's variables along a particular function. -/ def relabel (g : α → β) : L.formula α → L.formula β := @bounded_formula.relabel _ _ _ 0 (sum.inl ∘ g) 0 /-- The graph of a function as a first-order formula. -/ def graph (f : L.functions n) : L.formula (fin (n + 1)) := equal (var 0) (func f (λ i, var i.succ)) /-- The negation of a formula. -/ protected def not (φ : L.formula α) : L.formula α := φ.not /-- The implication between formulas, as a formula. -/ protected def imp : L.formula α → L.formula α → L.formula α := bounded_formula.imp /-- The biimplication between formulas, as a formula. -/ protected def iff (φ ψ : L.formula α) : L.formula α := φ.iff ψ lemma is_atomic_graph (f : L.functions n) : (graph f).is_atomic := bounded_formula.is_atomic.equal _ _ end formula namespace relations variable (r : L.relations 2) /-- The sentence indicating that a basic relation symbol is reflexive. -/ protected def reflexive : L.sentence := ∀' r.bounded_formula₂ &0 &0 /-- The sentence indicating that a basic relation symbol is irreflexive. -/ protected def irreflexive : L.sentence := ∀' ∼ (r.bounded_formula₂ &0 &0) /-- The sentence indicating that a basic relation symbol is symmetric. -/ protected def symmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &0) /-- The sentence indicating that a basic relation symbol is antisymmetric. -/ protected def antisymmetric : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ (r.bounded_formula₂ &1 &0 ⟹ term.bd_equal &0 &1)) /-- The sentence indicating that a basic relation symbol is transitive. -/ protected def transitive : L.sentence := ∀' ∀' ∀' (r.bounded_formula₂ &0 &1 ⟹ r.bounded_formula₂ &1 &2 ⟹ r.bounded_formula₂ &0 &2) /-- The sentence indicating that a basic relation symbol is total. -/ protected def total : L.sentence := ∀' ∀' (r.bounded_formula₂ &0 &1 ⊔ r.bounded_formula₂ &1 &0) end relations section cardinality variable (L) /-- A sentence indicating that a structure has `n` distinct elements. -/ protected def sentence.card_ge (n) : L.sentence := (((((list.fin_range n).product (list.fin_range n)).filter (λ ij : _ × _, ij.1 ≠ ij.2)).map (λ (ij : _ × _), ∼ ((& ij.1).bd_equal (& ij.2)))).foldr (⊓) ⊤).exs /-- A theory indicating that a structure is infinite. -/ def infinite_theory : L.Theory := set.range (sentence.card_ge L) /-- A theory that indicates a structure is nonempty. -/ def nonempty_theory : L.Theory := {sentence.card_ge L 1} /-- A theory indicating that each of a set of constants is distinct. -/ def distinct_constants_theory (s : set α) : L[[α]].Theory := (λ ab : α × α, (((L.con ab.1).term.equal (L.con ab.2).term).not)) '' ((s ×ˢ s) ∩ (set.diagonal α)ᶜ) variables {L} {α} open set lemma monotone_distinct_constants_theory : monotone (L.distinct_constants_theory : set α → L[[α]].Theory) := λ s t st, (image_subset _ (inter_subset_inter_left _ (prod_mono st st))) lemma directed_distinct_constants_theory : directed (⊆) (L.distinct_constants_theory : set α → L[[α]].Theory) := monotone.directed_le monotone_distinct_constants_theory lemma distinct_constants_theory_eq_Union (s : set α) : L.distinct_constants_theory s = ⋃ (t : finset s), L.distinct_constants_theory (t.map (function.embedding.subtype (λ x, x ∈ s))) := begin classical, simp only [distinct_constants_theory], rw [← image_Union, ← Union_inter], refine congr rfl (congr (congr rfl _) rfl), ext ⟨i, j⟩, simp only [prod_mk_mem_set_prod_eq, finset.coe_map, function.embedding.coe_subtype, mem_Union, mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], refine ⟨λ h, ⟨{⟨i, h.1⟩, ⟨j, h.2⟩}, ⟨h.1, _⟩, ⟨h.2, _⟩⟩, _⟩, { simp }, { simp }, { rintros ⟨t, ⟨is, _⟩, ⟨js, _⟩⟩, exact ⟨is, js⟩ } end end cardinality end language end first_order
63ee8c2886c11cd77cd3afcfb0adf5a41f7b1308
a7dd8b83f933e72c40845fd168dde330f050b1c9
/src/analysis/asymptotics.lean
d4a76437b72ac817577bebe858ab55080e904ad8
[ "Apache-2.0" ]
permissive
NeilStrickland/mathlib
10420e92ee5cb7aba1163c9a01dea2f04652ed67
3efbd6f6dff0fb9b0946849b43b39948560a1ffe
refs/heads/master
1,589,043,046,346
1,558,938,706,000
1,558,938,706,000
181,285,984
0
0
Apache-2.0
1,568,941,848,000
1,555,233,833,000
Lean
UTF-8
Lean
false
false
29,269
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad We introduce these relations: `is_O f g l` : "f is big O of g along l" `is_o f g l` : "f is little o of g along l" Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) (nhds 0) l`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ import analysis.normed_space.basic open filter namespace asymptotics variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section variables [has_norm β] [has_norm γ] [has_norm δ] def is_O (f : α → β) (g : α → γ) (l : filter α) : Prop := ∃ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l def is_o (f : α → β) (g : α → γ) (l : filter α) : Prop := ∀ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l theorem is_O_refl (f : α → β) (l : filter α) : is_O f f l := ⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩ theorem is_O.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_O f g l) {δ : Type*} (k : δ → α) : is_O (f ∘ k) (g ∘ k) (l.comap k) := let ⟨c, cpos, hfgc⟩ := hfg in ⟨c, cpos, mem_comap_sets.mpr ⟨_, hfgc, set.subset.refl _⟩⟩ theorem is_o.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_o f g l) {δ : Type*} (k : δ → α) : is_o (f ∘ k) (g ∘ k) (l.comap k) := λ c cpos, mem_comap_sets.mpr ⟨_, hfg c cpos, set.subset.refl _⟩ theorem is_O.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂) (h' : is_O f g l₂) : is_O f g l₁ := let ⟨c, cpos, h'c⟩ := h' in ⟨c, cpos, h (h'c)⟩ theorem is_o.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂) (h' : is_o f g l₂) : is_o f g l₁ := λ c cpos, h (h' c cpos) theorem is_o.to_is_O {f : α → β} {g : α → γ} {l : filter α} (hgf : is_o f g l) : is_O f g l := ⟨1, zero_lt_one, hgf 1 zero_lt_one⟩ theorem is_O.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_O f g l) (h₂ : is_O g k l) : is_O f k l := let ⟨c, cpos, hc⟩ := h₁, ⟨c', c'pos, hc'⟩ := h₂ in begin use [c * c', mul_pos cpos c'pos], filter_upwards [hc, hc'], dsimp, intros x h₁x h₂x, rw mul_assoc, exact le_trans h₁x (mul_le_mul_of_nonneg_left h₂x (le_of_lt cpos)) end theorem is_o.trans_is_O {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_o f g l) (h₂ : is_O g k l) : is_o f k l := begin intros c cpos, rcases h₂ with ⟨c', c'pos, hc'⟩, have cc'pos := div_pos cpos c'pos, filter_upwards [h₁ (c / c') cc'pos, hc'], dsimp, intros x h₁x h₂x, refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt cc'pos)) _), rw [←mul_assoc, div_mul_cancel _ (ne_of_gt c'pos)] end theorem is_O.trans_is_o {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_O f g l) (h₂ : is_o g k l) : is_o f k l := begin intros c cpos, rcases h₁ with ⟨c', c'pos, hc'⟩, have cc'pos := div_pos cpos c'pos, filter_upwards [hc', h₂ (c / c') cc'pos], dsimp, intros x h₁x h₂x, refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt c'pos)) _), rw [←mul_assoc, mul_div_cancel' _ (ne_of_gt c'pos)] end theorem is_o.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_o f g l) (h₂ : is_o g k l) : is_o f k l := h₁.to_is_O.trans_is_o h₂ theorem is_o_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h₁ : is_o f g l₁) (h₂ : is_o f g l₂) : is_o f g (l₁ ⊔ l₂) := begin intros c cpos, rw mem_sup_sets, exact ⟨h₁ c cpos, h₂ c cpos⟩ end theorem is_O_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := bex_congr $ λ c _, filter.congr_sets $ by filter_upwards [hf, hg] λ x e₁ e₂, by dsimp at e₁ e₂ ⊢; rw [e₁, e₂] theorem is_o_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr $ λ c _, filter.congr_sets $ by filter_upwards [hf, hg] λ x e₁ e₂, by dsimp at e₁ e₂ ⊢; rw [e₁, e₂] theorem is_O.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1 theorem is_o.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1 theorem is_O_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : {x | f₁ x = f₂ x} ∈ l) : is_O f₁ g l ↔ is_O f₂ g l := is_O_congr h (univ_mem_sets' $ λ _, rfl) theorem is_o_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : {x | f₁ x = f₂ x} ∈ l) : is_o f₁ g l ↔ is_o f₂ g l := is_o_congr h (univ_mem_sets' $ λ _, rfl) theorem is_O.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_o.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_O_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (h : {x | g₁ x = g₂ x} ∈ l) : is_O f g₁ l ↔ is_O f g₂ l := is_O_congr (univ_mem_sets' $ λ _, rfl) h theorem is_o_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (h : {x | g₁ x = g₂ x} ∈ l) : is_o f g₁ l ↔ is_o f g₂ l := is_o_congr (univ_mem_sets' $ λ _, rfl) h theorem is_O.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg end section variables [has_norm β] [normed_group γ] [normed_group δ] @[simp] theorem is_O_norm_right {f : α → β} {g : α → γ} {l : filter α} : is_O f (λ x, ∥g x∥) l ↔ is_O f g l := by simp only [is_O, norm_norm] @[simp] theorem is_o_norm_right {f : α → β} {g : α → γ} {l : filter α} : is_o f (λ x, ∥g x∥) l ↔ is_o f g l := by simp only [is_o, norm_norm] @[simp] theorem is_O_neg_right {f : α → β} {g : α → γ} {l : filter α} : is_O f (λ x, -(g x)) l ↔ is_O f g l := by { rw ←is_O_norm_right, simp only [norm_neg], rw is_O_norm_right } @[simp] theorem is_o_neg_right {f : α → β} {g : α → γ} {l : filter α} : is_o f (λ x, -(g x)) l ↔ is_o f g l := by { rw ←is_o_norm_right, simp only [norm_neg], rw is_o_norm_right } theorem is_O_iff {f : α → β} {g : α → γ} {l : filter α} : is_O f g l ↔ ∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l := suffices (∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l) → is_O f g l, from ⟨λ ⟨c, cpos, hc⟩, ⟨c, hc⟩, this⟩, assume ⟨c, hc⟩, or.elim (lt_or_ge 0 c) (assume : c > 0, ⟨c, this, hc⟩) (assume h'c : c ≤ 0, have {x : α | ∥f x∥ ≤ 1 * ∥g x∥} ∈ l, begin filter_upwards [hc], intros x, show ∥f x∥ ≤ c * ∥g x∥ → ∥f x∥ ≤ 1 * ∥g x∥, { intro hx, apply le_trans hx, apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), show c ≤ 1, from le_trans h'c zero_le_one } end, ⟨1, zero_lt_one, this⟩) theorem is_O_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h₁ : is_O f g l₁) (h₂ : is_O f g l₂) : is_O f g (l₁ ⊔ l₂) := begin rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, rcases h₂ with ⟨c₂, c₂pos, hc₂⟩, have : 0 < max c₁ c₂, by { rw lt_max_iff, left, exact c₁pos }, use [max c₁ c₂, this], rw mem_sup_sets, split, { filter_upwards [hc₁], dsimp, intros x hx, exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)) }, filter_upwards [hc₂], dsimp, intros x hx, exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _)) end lemma is_O.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_O f g₁ l) : is_O f (λx, (g₁ x, g₂ x)) l := begin have : is_O g₁ (λx, (g₁ x, g₂ x)) l := ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩, exact is_O.trans h this end lemma is_O.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_O f g₂ l) : is_O f (λx, (g₁ x, g₂ x)) l := begin have : is_O g₂ (λx, (g₁ x, g₂ x)) l := ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩, exact is_O.trans h this end lemma is_o.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_o f g₁ l) : is_o f (λx, (g₁ x, g₂ x)) l := is_o.trans_is_O h (is_O.prod_rightl (is_O_refl g₁ l)) lemma is_o.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_o f g₂ l) : is_o f (λx, (g₁ x, g₂ x)) l := is_o.trans_is_O h (is_O.prod_rightr (is_O_refl g₂ l)) end section variables [normed_group β] [normed_group δ] [has_norm γ] @[simp] theorem is_O_norm_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, ∥f x∥) g l ↔ is_O f g l := by simp only [is_O, norm_norm] @[simp] theorem is_o_norm_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, ∥f x∥) g l ↔ is_o f g l := by simp only [is_o, norm_norm] @[simp] theorem is_O_neg_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, -f x) g l ↔ is_O f g l := by { rw ←is_O_norm_left, simp only [norm_neg], rw is_O_norm_left } @[simp] theorem is_o_neg_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, -f x) g l ↔ is_o f g l := by { rw ←is_o_norm_left, simp only [norm_neg], rw is_o_norm_left } theorem is_O.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := let ⟨c₁, c₁pos, hc₁⟩ := h₁, ⟨c₂, c₂pos, hc₂⟩ := h₂ in begin use [c₁ + c₂, add_pos c₁pos c₂pos], filter_upwards [hc₁, hc₂], intros x hx₁ hx₂, show ∥f₁ x + f₂ x∥ ≤ (c₁ + c₂) * ∥g x∥, apply le_trans (norm_triangle _ _), rw add_mul, exact add_le_add hx₁ hx₂ end theorem is_o.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := begin intros c cpos, filter_upwards [h₁ (c / 2) (half_pos cpos), h₂ (c / 2) (half_pos cpos)], intros x hx₁ hx₂, dsimp at hx₁ hx₂, apply le_trans (norm_triangle _ _), apply le_trans (add_le_add hx₁ hx₂), rw [←mul_add, ←two_mul, ←mul_assoc, div_mul_cancel _ two_ne_zero] end theorem is_O.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := h₁.add (is_O_neg_left.mpr h₂) theorem is_o.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := h₁.add (is_o_neg_left.mpr h₂) theorem is_O_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := by simpa using @is_O_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l theorem is_O.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f₁ x - f₂ x) g l → is_O (λ x, f₂ x - f₁ x) g l := is_O_comm.1 theorem is_O.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left (by simp) theorem is_O.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := by simpa using @is_o_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l theorem is_o.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f₁ x - f₂ x) g l → is_o (λ x, f₂ x - f₁ x) g l := is_o_comm.1 theorem is_o.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left (by simp) theorem is_o.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ @[simp] theorem is_O_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} : is_O (λx, (f₁ x, f₂ x)) g l ↔ is_O f₁ g l ∧ is_O f₂ g l := begin split, { assume h, split, { exact is_O.trans (is_O.prod_rightl (is_O_refl f₁ l)) h }, { exact is_O.trans (is_O.prod_rightr (is_O_refl f₂ l)) h } }, { rintros ⟨h₁, h₂⟩, have : is_O (λx, ∥f₁ x∥ + ∥f₂ x∥) g l := is_O.add (is_O_norm_left.2 h₁) (is_O_norm_left.2 h₂), apply is_O.trans _ this, refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩, simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq], split; exact le_trans (by simp) (le_abs_self _) } end @[simp] theorem is_o_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} : is_o (λx, (f₁ x, f₂ x)) g l ↔ is_o f₁ g l ∧ is_o f₂ g l := begin split, { assume h, split, { exact is_O.trans_is_o (is_O.prod_rightl (is_O_refl f₁ l)) h }, { exact is_O.trans_is_o (is_O.prod_rightr (is_O_refl f₂ l)) h } }, { rintros ⟨h₁, h₂⟩, have : is_o (λx, ∥f₁ x∥ + ∥f₂ x∥) g l := is_o.add (is_o_norm_left.2 h₁) (is_o_norm_left.2 h₂), apply is_O.trans_is_o _ this, refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩, simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq], split; exact le_trans (by simp) (le_abs_self _) } end end section variables [normed_group β] [normed_group γ] theorem is_O_zero (g : α → γ) (l : filter α) : is_O (λ x, (0 : β)) g l := ⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩ theorem is_O_refl_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f x - f x) g l := by simpa using is_O_zero g l theorem is_O_zero_right_iff {f : α → β} {l : filter α} : is_O f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l := begin rw [is_O_iff], split, { rintros ⟨c, hc⟩, filter_upwards [hc], dsimp, intro x, rw [norm_zero, mul_zero], intro hx, rw ←norm_eq_zero, exact le_antisymm hx (norm_nonneg _) }, intro h, use 0, filter_upwards [h], dsimp, intros x hx, rw [hx, norm_zero, zero_mul] end theorem is_o_zero (g : α → γ) (l : filter α) : is_o (λ x, (0 : β)) g l := λ c cpos, by { filter_upwards [univ_mem_sets], intros x _, simp, exact mul_nonneg (le_of_lt cpos) (norm_nonneg _)} theorem is_o_refl_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f x - f x) g l := by simpa using is_o_zero g l theorem is_o_zero_right_iff {f : α → β} (l : filter α) : is_o f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l := begin split, { intro h, exact is_O_zero_right_iff.mp h.to_is_O }, intros h c cpos, filter_upwards [h], dsimp, intros x hx, rw [hx, norm_zero, norm_zero, mul_zero] end end section variables [has_norm β] [normed_field γ] theorem is_O_const_one (c : β) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : γ)) l := begin rw is_O_iff, refine ⟨∥c∥, _⟩, simp only [norm_one, mul_one], apply univ_mem_sets', simp [le_refl], end end section variables [normed_field β] [normed_group γ] theorem is_O_const_mul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) (c : β) : is_O (λ x, c * f x) g l := begin cases classical.em (c = 0) with h'' h'', { simp [h''], apply is_O_zero }, rcases h with ⟨c', c'pos, h'⟩, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), refine ⟨∥c∥ * c', mul_pos cpos c'pos, _⟩, filter_upwards [h'], dsimp, intros x h₀, rw [normed_field.norm_mul, mul_assoc], exact mul_le_mul_of_nonneg_left h₀ (norm_nonneg _) end theorem is_O_const_mul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : β} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := begin split, { intro h, convert is_O_const_mul_left h c⁻¹, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] }, intro h, apply is_O_const_mul_left h end theorem is_o_const_mul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) (c : β) : is_o (λ x, c * f x) g l := begin cases classical.em (c = 0) with h'' h'', { simp [h''], apply is_o_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), intros c' c'pos, dsimp, filter_upwards [h (c' / ∥c∥) (div_pos c'pos cpos)], dsimp, intros x hx, rw [normed_field.norm_mul], apply le_trans (mul_le_mul_of_nonneg_left hx (le_of_lt cpos)), rw [←mul_assoc, mul_div_cancel' _ cne0] end theorem is_o_const_mul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : β} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := begin split, { intro h, convert is_o_const_mul_left h c⁻¹, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] }, intro h', apply is_o_const_mul_left h' end end section variables [normed_group β] [normed_field γ] theorem is_O_of_is_O_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ} (h : is_O f (λ x, c * g x) l) : is_O f g l := begin cases classical.em (c = 0) with h' h', { simp [h', is_O_zero_right_iff] at h, rw is_O_congr_left h, apply is_O_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), rcases h with ⟨c', c'pos, h''⟩, refine ⟨c' * ∥c∥, mul_pos c'pos cpos, _⟩, convert h'', ext x, dsimp, rw [normed_field.norm_mul, mul_assoc] end theorem is_O_const_mul_right_iff {f : α → β} {g : α → γ} {l : filter α} {c : γ} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := begin split, { intro h, exact is_O_of_is_O_const_mul_right h }, intro h, apply is_O_of_is_O_const_mul_right, show is_O f (λ (x : α), c⁻¹ * (c * g x)) l, convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] end theorem is_o_of_is_o_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ} (h : is_o f (λ x, c * g x) l) : is_o f g l := begin cases classical.em (c = 0) with h' h', { simp [h', is_o_zero_right_iff] at h, rw is_o_congr_left h, apply is_o_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), intros c' c'pos, convert h (c' / ∥c∥) (div_pos c'pos cpos), dsimp, ext x, rw [normed_field.norm_mul, ←mul_assoc, div_mul_cancel _ cne0] end theorem is_o_const_mul_right {f : α → β} {g : α → γ} {l : filter α} {c : γ} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := begin split, { intro h, exact is_o_of_is_o_const_mul_right h }, intro h, apply is_o_of_is_o_const_mul_right, show is_o f (λ (x : α), c⁻¹ * (c * g x)) l, convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] end theorem is_o_one_iff {f : α → β} {l : filter α} : is_o f (λ x, (1 : γ)) l ↔ tendsto f l (nhds 0) := begin rw [normed_space.tendsto_nhds_zero, is_o], split, { intros h e epos, filter_upwards [h (e / 2) (half_pos epos)], simp, intros x hx, exact lt_of_le_of_lt hx (half_lt_self epos) }, intros h e epos, filter_upwards [h e epos], simp, intros x hx, exact le_of_lt hx end theorem is_O_one_of_tendsto {f : α → β} {l : filter α} {y : β} (h : tendsto f l (nhds y)) : is_O f (λ x, (1 : γ)) l := begin have Iy : ∥y∥ < ∥y∥ + 1 := lt_add_one _, refine ⟨∥y∥ + 1, lt_of_le_of_lt (norm_nonneg _) Iy, _⟩, simp only [mul_one, norm_one], have : tendsto (λx, ∥f x∥) l (nhds ∥y∥) := (continuous_norm.tendsto _).comp h, exact this (ge_mem_nhds Iy) end end section variables [normed_group β] [normed_group γ] theorem is_O.trans_tendsto {f : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f g l) (h₂ : tendsto g l (nhds 0)) : tendsto f l (nhds 0) := (@is_o_one_iff _ _ ℝ _ _ _ _).1 $ h₁.trans_is_o $ is_o_one_iff.2 h₂ theorem is_o.trans_tendsto {f : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f g l) : tendsto g l (nhds 0) → tendsto f l (nhds 0) := h₁.to_is_O.trans_tendsto end section variables [normed_field β] [normed_field γ] theorem is_O_mul {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, rcases h₂ with ⟨c₂, c₂pos, hc₂⟩, refine ⟨c₁ * c₂, mul_pos c₁pos c₂pos, _⟩, filter_upwards [hc₁, hc₂], dsimp, intros x hx₁ hx₂, rw [normed_field.norm_mul, normed_field.norm_mul, mul_assoc, mul_left_comm c₂, ←mul_assoc], exact mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _)) end theorem is_o_mul_left {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l): is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, filter_upwards [hc₁, h₂ (c / c₁) (div_pos cpos c₁pos)], dsimp, intros x hx₁ hx₂, rw [normed_field.norm_mul, normed_field.norm_mul], apply le_trans (mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _))), rw [mul_comm c₁, mul_assoc, mul_left_comm c₁, ←mul_assoc _ c₁, div_mul_cancel _ (ne_of_gt c₁pos)], rw [mul_left_comm] end theorem is_o_mul_right {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l): is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := by convert is_o_mul_left h₂ h₁; simp only [mul_comm] theorem is_o_mul {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l): is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := is_o_mul_left h₁.to_is_O h₂ end /- Note: the theorems in the next two sections can also be used for the integers, since scalar multiplication is multiplication. -/ section variables {K : Type*} [normed_field K] [normed_space K β] [normed_group γ] set_option class.instance_max_depth 43 theorem is_O_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) (c : K) : is_O (λ x, c • f x) g l := begin rw [←is_O_norm_left], simp only [norm_smul], apply is_O_const_mul_left, rw [is_O_norm_left], apply h end theorem is_O_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) : is_O (λ x, c • f x) g l ↔ is_O f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left] end theorem is_o_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) (c : K) : is_o (λ x, c • f x) g l := begin rw [←is_o_norm_left], simp only [norm_smul], apply is_o_const_mul_left, rw [is_o_norm_left], apply h end theorem is_o_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) : is_o (λ x, c • f x) g l ↔ is_o f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end end section variables {K : Type*} [normed_group β] [normed_field K] [normed_space K γ] set_option class.instance_max_depth 43 theorem is_O_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) : is_O f (λ x, c • g x) l ↔ is_O f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : K} (hc : c ≠ 0) : is_o f (λ x, c • g x) l ↔ is_o f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right cne0, is_o_norm_right] end end section variables {K : Type*} [normed_field K] [normed_space K β] [normed_space K γ] set_option class.instance_max_depth 43 theorem is_O_smul {k : α → K} {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) : is_O (λ x, k x • f x) (λ x, k x • g x) l := begin rw [←is_O_norm_left, ←is_O_norm_right], simp only [norm_smul], apply is_O_mul (is_O_refl _ _), rw [is_O_norm_left, is_O_norm_right], exact h end theorem is_o_smul {k : α → K} {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) : is_o (λ x, k x • f x) (λ x, k x • g x) l := begin rw [←is_o_norm_left, ←is_o_norm_right], simp only [norm_smul], apply is_o_mul_left (is_O_refl _ _), rw [is_o_norm_left, is_o_norm_right], exact h end end section variables [normed_field β] theorem tendsto_nhds_zero_of_is_o {f g : α → β} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (nhds 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from is_o_mul_right h (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : β)) l, begin use [1, zero_lt_one], filter_upwards [univ_mem_sets], simp, intro x, cases classical.em (∥g x∥ = 0) with h' h'; simp [h'], exact zero_le_one end, is_o_one_iff.mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → β} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (nhds 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : β)) l, from is_o_one_iff.mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert is_o_mul_right eq₁ (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin use [1, zero_lt_one], refine filter.univ_mem_sets' (assume x, _), suffices : ∥f x∥ ≤ ∥f x∥ / ∥g x∥ * ∥g x∥, { simpa }, by_cases g x = 0, { simp only [h, hgf x h, norm_zero, mul_zero] }, { rw [div_mul_cancel], exact mt (norm_eq_zero _).1 h } end, eq₃.trans_is_o eq₂ theorem is_o_iff_tendsto [normed_field β] {f g : α → β} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (nhds 0) := iff.intro tendsto_nhds_zero_of_is_o (is_o_of_tendsto hgf) end end asymptotics
5b933f03af8511ccb1fe87ceddf7535d2de6114d
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/inferences/demod.lean
f1da85a6cf70cf7967884e10df31bc048464aecc
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
4,721
lean
import super.inferences.superposition namespace super open tactic variables (gt : term_order) meta def get_simpl_clauses : prover (list (expr × expr × clause)) := do act ← get_active, pure $ do act ← act.values, clause_type.atom `(%%l = %%r) ← pure act.cls.ty | [], pure (l,r,act.cls) variables (simpl_clauses : list (expr × expr × clause)) meta def simplify1 : expr → tactic (expr × expr) | e := first $ do st ← closed_subterms e, (l, r, cls) ← simpl_clauses, pure $ tactic.retrieve $ do unify st l transparency.reducible, (do l_ty ← infer_type l, st_ty ← infer_type st, unify l_ty st_ty), l ← instantiate_mvars l, r ← instantiate_mvars r, guard $ gt l r, ty ← infer_type st, ctx ← kabstract e l transparency.reducible ff, guard $ ctx.has_var, let ctx := expr.lam ty.hyp_name_hint binder_info.default ty ctx, type_check ctx, prf ← mk_mapp ``congr_arg [none, none, l, r, ctx, cls.prf], prf ← instantiate_mvars prf, guard $ ¬ prf.has_meta_var, pure (ctx.app' r, prf) meta def simplify : expr → tactic (option $ expr × expr) | e := do res ← try_core (simplify1 gt simpl_clauses e), match res with | none := pure none | some (e', prf) := do res ← simplify e', match res with | none := pure (e', prf) | some (e'', prf') := do prf'' ← mk_mapp ``eq.trans [none, e, e', e'', prf, prf'], pure (e'', prf'') end end meta def simplify_clause (cls : clause) : tactic (option clause) := do ⟨did_simpl, simpld⟩ ← (cls.literals.mfoldr (λ l ⟨did_simpl, cls⟩, do some i ← pure $ cls.literals.index_of' l, res ← simplify gt simpl_clauses l.formula, match res with | none := pure (did_simpl, cls) | some (f', prf) := if l.is_pos then do prf ← mk_mapp ``eq.mp [l.formula, f', prf], let prf : clause := ⟨clause_type.imp l.formula (clause_type.atom f'), prf⟩, prod.mk tt <$> clause.resolve cls i prf 0 else do prf ← mk_mapp ``eq.mpr [l.formula, f', prf], let prf : clause := ⟨clause_type.imp f' (clause_type.atom l.formula), prf⟩, prod.mk tt <$> clause.resolve prf 1 cls i end) (ff, cls) : tactic (bool × clause)), if did_simpl then pure simpld else pure none meta def simplify_with_ground_core (cls : clause) (tac : clause → tactic (option clause)) : tactic (option (list expr × packed_clause)) := tactic.retrieve $ do mvars ← cls.prf.sorted_mvars, free_var_tys ← abstract_mvar_telescope mvars, lcs ← mk_locals_core free_var_tys, (mvars.zip lcs).mmap' $ λ ⟨m, lc⟩, unify m lc, let umvars := cls.prf.univ_meta_vars.to_list, ups ← umvars.mmap (λ _, mk_fresh_name), cls ← cls.instantiate_mvars, let cls := cls.instantiate_univ_mvars (native.rb_map.of_list (umvars.zip (ups.map level.param))), some simpld ← tac cls | pure none, simpld ← simpld.instantiate_mvars, simpld.check_if_debug, when simpld.prf.has_meta_var $ fail "simplify_with_ground_core has_meta_var", let simpld := simpld.abstract_locals (lcs.map expr.local_uniq_name).reverse, let simpld := simpld.instantiate_univ_params (ups.zip (umvars.map level.mvar)), pure $ some ⟨mvars, umvars, free_var_tys, simpld⟩ meta def simplify_with_ground (cls : clause) (tac : clause → tactic (option clause)) : tactic (option clause) := option.map (λ s : list expr × packed_clause, s.2.cls.instantiate_vars s.1) <$> simplify_with_ground_core cls tac meta def simplification.forward_demod : simplification_rule | cls := do gt ← get_term_order, simpl_clauses@(_::_) ← get_simpl_clauses | pure cls, simpld ← simplify_with_ground cls $ simplify_clause gt simpl_clauses, simpld.to_list.mmap' (monad_lift ∘ clause.check_if_debug), pure $ simpld.get_or_else cls meta def simplify_with_ground_packed (cls : clause) (tac : clause → tactic (option clause)) : tactic (option packed_clause) := option.map prod.snd <$> simplify_with_ground_core cls tac meta def inference.backward_demod : inference_rule | given := do clause_type.atom `(@eq %%ty %%r %%l) ← pure given.cls.ty | pure [], let simpl_clauses := [(l,r,given.cls)], let funsym := name_of_funsym r.get_app_fn, if funsym = name.anonymous then pure [] else do gt ← get_term_order, active ← get_active, list.join <$> (active.values.mmap $ λ act, if act.id = given.id then pure [] else do act_ty ← act.cls.ty.to_expr, if (contained_funsyms act_ty).contains funsym then do simpld ← simplify_with_ground_packed act.cls $ simplify_clause gt simpl_clauses, match simpld with | some simpld := do remove_redundant act.id, clause.check_results_if_debug $ pure <$> simpld.unpack | none := pure [] end else pure []) end super
e25125217ccefe8816993b403116a03435f6d6de
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/order/lattice_intervals.lean
5d778cfba13a0e9a879643c1f9e703a0d9a6e5c1
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,881
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 order.bounded_lattice import data.set.intervals.basic /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.semilattice_inf_bot` * `set.Ii*.semillatice_inf` * `set.I*c.semilattice_sup_top` * `set.I*c.semillatice_inf` * `set.Iic.bounded_lattice`, within a `bounded_lattice` * `set.Ici.bounded_lattice`, within a `bounded_lattice` -/ variable {α : Type*} namespace set namespace Ico variables {a b : α} instance [semilattice_inf α] : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ def order_bot [partial_order α] (h : a < b) : order_bot (Ico a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Ico a b` is a `semilattice_inf_bot` whenever `a < b`. -/ def semilattice_inf_bot [semilattice_inf α] (h : a < b) : semilattice_inf_bot (Ico a b) := { .. (Ico.semilattice_inf), .. (Ico.order_bot h) } end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc variables {a b : α} instance [semilattice_sup α] : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ def order_top [partial_order α] (h : a < b) : order_top (Ioc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Ioc a b` is a `semilattice_sup_top` whenever `a < b`. -/ def semilattice_sup_top [semilattice_sup α] (h : a < b) : semilattice_sup_top (Ioc a b) := { .. (Ioc.semilattice_sup), .. (Ioc.order_top h) } end Ioc namespace Iio instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Iio namespace Iic variables {a : α} instance [semilattice_inf α] : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] : lattice (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.semilattice_sup) } instance [partial_order α] : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop, .. (subtype.partial_order _) } @[simp] lemma coe_top [partial_order α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [semilattice_inf α] : semilattice_inf_top (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_top) } instance [semilattice_sup α] : semilattice_sup_top (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_top) } instance [order_bot α] : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le, .. (infer_instance : partial_order (Iic a)) } @[simp] lemma coe_bot [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [partial_order α] [no_bot_order α] {a : α} : no_bot_order (Iic a) := ⟨λ x, let ⟨y, hy⟩ := no_bot x.1 in ⟨⟨y, le_trans hy.le x.2⟩, hy⟩ ⟩ instance [semilattice_inf_bot α] : semilattice_inf_bot (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_bot) } instance [semilattice_sup_bot α] : semilattice_sup_bot (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_bot) } instance [bounded_lattice α] : bounded_lattice (Iic a) := { .. (Iic.order_top), .. (Iic.order_bot), .. (Iic.lattice) } end Iic namespace Ici variables {a : α} instance [semilattice_inf α] : semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] : lattice (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.semilattice_sup) } instance [partial_order α] : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop, .. (subtype.partial_order _) } @[simp] lemma coe_bot [partial_order α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [semilattice_inf α] : semilattice_inf_bot (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_bot) } instance [semilattice_sup α] : semilattice_sup_bot (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_bot) } instance [order_top α] : order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top, .. (infer_instance : partial_order (Ici a)) } @[simp] lemma coe_top [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [partial_order α] [no_top_order α] {a : α} : no_top_order (Ici a) := ⟨λ x, let ⟨y, hy⟩ := no_top x.1 in ⟨⟨y, le_trans x.2 hy.le⟩, hy⟩ ⟩ instance [semilattice_sup_top α] : semilattice_sup_top (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_top) } instance [semilattice_inf_top α] : semilattice_inf_top (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_top) } instance [bounded_lattice α] : bounded_lattice (Ici a) := { .. (Ici.order_top), .. (Ici.order_bot), .. (Ici.lattice) } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. (Icc.semilattice_inf), .. (Icc.semilattice_sup) } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ def order_bot [partial_order α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Icc a b` has a top element whenever `a ≤ b`. -/ def order_top [partial_order α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Icc a b` is a `semilattice_inf_bot` whenever `a ≤ b`. -/ def semilattice_inf_bot [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_inf_top` whenever `a ≤ b`. -/ def semilattice_inf_top [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_sup_bot` whenever `a ≤ b`. -/ def semilattice_sup_bot [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `semilattice_sup_top` whenever `a ≤ b`. -/ def semilattice_sup_top [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `bounded_lattice` whenever `a ≤ b`. -/ def bounded_lattice [lattice α] {a b : α} (h : a ≤ b) : bounded_lattice (Icc a b) := { .. (Icc.semilattice_inf_bot h), .. (Icc.semilattice_sup_top h) } end Icc end set
04512596ea02f7c39009c992c890da8adccea866
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/simplify_with_hypotheses.lean
81cfba8ed41c920bc22e8da13c58e6430d292f2e
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
583
lean
open tactic example (A : Type) (a₁ a₂ : A) (f : A → A) (H₀ : a₁ = a₂) : f a₁ = f a₂ := by simp_using_hs example (A : Type) (a₁ a₁' a₂ a₂' : A) (f : A → A) (H₀ : a₁' = a₂') (H₁ : f a₁ = a₁') (H₂ : f a₂ = a₂') : f a₁ = f a₂ := by simp_using_hs constants (A : Type.{1}) (x y z w : A) (f : A → A) (H₁ : f (f x) = f y) (H₂ : f (f y) = f z) (H₃ : f (f z) = w) definition foo : f (f (f (f x))) = w := by do h₁ ← mk_const `H₁, h₂ ← mk_const `H₂, h₃ ← mk_const `H₃, simp_using [h₁, h₂, h₃]
5da349978630f437d7bf641c9e52409678d72a97
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/hott/457.hlean
ae03e8d59f53ae54e2459ede4c61ebc69da826c8
[ "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
189
hlean
import algebra.group open eq path_algebra definition foo {A : Type} (a b c : A) (H₁ : a = c) (H₂ : c = b) : a = b := begin apply concat, rotate 1, apply H₂, apply H₁ end
5ebcb32e1e368b8029e1a9cc259379f4315ec9c7
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/dfinsupp/interval.lean
ef238ca546402a73c2b5249df31b8d3fa0cac5da
[ "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,811
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite import data.dfinsupp.order /-! # Finite intervals of finitely supported functions This file provides the `locally_finite_order` instance for `Π₀ i, α i` when `α` itself is locally finite and calculates the cardinality of its finite intervals. -/ open dfinsupp finset open_locale big_operators pointwise variables {ι : Type*} {α : ι → Type*} namespace finset variables [decidable_eq ι] [Π i, has_zero (α i)] {s : finset ι} {f : Π₀ i, α i} {t : Π i, finset (α i)} /-- Finitely supported product of finsets. -/ def dfinsupp (s : finset ι) (t : Π i, finset (α i)) : finset (Π₀ i, α i) := (s.pi t).map ⟨λ f, dfinsupp.mk s $ λ i, f i i.2, begin refine (mk_injective _).comp (λ f g h, _), ext i hi, convert congr_fun h ⟨i, hi⟩, end⟩ @[simp] lemma card_dfinsupp (s : finset ι) (t : Π i, finset (α i)) : (s.dfinsupp t).card = ∏ i in s, (t i).card := (card_map _).trans $ card_pi _ _ variables [Π i, decidable_eq (α i)] lemma mem_dfinsupp_iff : f ∈ s.dfinsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := begin refine mem_map.trans ⟨_, _⟩, { rintro ⟨f, hf, rfl⟩, refine ⟨support_mk_subset, λ i hi, _⟩, convert mem_pi.1 hf i hi, exact mk_of_mem hi }, { refine λ h, ⟨λ i _, f i, mem_pi.2 h.2, _⟩, ext i, dsimp, exact ite_eq_left_iff.2 (λ hi, (not_mem_support_iff.1 $ λ H, hi $ h.1 H).symm) } end /-- When `t` is supported on `s`, `f ∈ s.dfinsupp t` precisely means that `f` is pointwise in `t`. -/ @[simp] lemma mem_dfinsupp_iff_of_support_subset {t : Π₀ i, finset (α i)} (ht : t.support ⊆ s) : f ∈ s.dfinsupp t ↔ ∀ i, f i ∈ t i := begin refine mem_dfinsupp_iff.trans (forall_and_distrib.symm.trans $ forall_congr $ λ i, ⟨λ h, _, λ h, ⟨λ hi, ht $ mem_support_iff.2 $ λ H, mem_support_iff.1 hi _, λ _, h⟩⟩), { by_cases hi : i ∈ s, { exact h.2 hi }, { rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 (not_mem_mono ht hi)], exact zero_mem_zero } }, { rwa [H, mem_zero] at h } end end finset open finset namespace dfinsupp variables [decidable_eq ι] [Π i, decidable_eq (α i)] section bundled_singleton variables [Π i, has_zero (α i)] {f : Π₀ i, α i} {i : ι} {a : α i} /-- Pointwise `finset.singleton` bundled as a `dfinsupp`. -/ def singleton (f : Π₀ i, α i) : Π₀ i, finset (α i) := ⟦{ to_fun := λ i, {f i}, pre_support := f.support.1, zero := λ i, (ne_or_eq (f i) 0).imp mem_support_iff.2 (congr_arg _) }⟧ lemma mem_singleton_apply_iff : a ∈ f.singleton i ↔ a = f i := mem_singleton end bundled_singleton section bundled_Icc variables [Π i, has_zero (α i)] [Π i, partial_order (α i)] [Π i, locally_finite_order (α i)] {f g : Π₀ i, α i} {i : ι} {a : α i} /-- Pointwise `finset.Icc` bundled as a `dfinsupp`. -/ def range_Icc (f g : Π₀ i, α i) : Π₀ i, finset (α i) := ⟦{ to_fun := λ i, Icc (f i) (g i), pre_support := f.support.1 + g.support.1, zero := λ i, begin refine or_iff_not_imp_left.2 (λ h, _), rw [not_mem_support_iff.1 (multiset.not_mem_mono (multiset.le_add_right _ _).subset h), not_mem_support_iff.1 (multiset.not_mem_mono (multiset.le_add_left _ _).subset h)], exact Icc_self _, end }⟧ @[simp] lemma range_Icc_apply (f g : Π₀ i, α i) (i : ι) : f.range_Icc g i = Icc (f i) (g i) := rfl lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc lemma support_range_Icc_subset : (f.range_Icc g).support ⊆ f.support ∪ g.support := begin refine λ x hx, _, by_contra, refine not_mem_support_iff.2 _ hx, rw [range_Icc_apply, not_mem_support_iff.1 (not_mem_mono (subset_union_left _ _) h), not_mem_support_iff.1 (not_mem_mono (subset_union_right _ _) h)], exact Icc_self _, end end bundled_Icc section pi variables [Π i, has_zero (α i)] /-- Given a finitely supported function `f : Π₀ i, finset (α i)`, one can define the finset `f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/ def pi (f : Π₀ i, finset (α i)) : finset (Π₀ i, α i) := f.support.dfinsupp f @[simp] lemma mem_pi {f : Π₀ i, finset (α i)} {g : Π₀ i, α i} : g ∈ f.pi ↔ ∀ i, g i ∈ f i := mem_dfinsupp_iff_of_support_subset $ subset.refl _ @[simp] lemma card_pi (f : Π₀ i, finset (α i)) : f.pi.card = f.prod (λ i, (f i).card) := begin rw [pi, card_dfinsupp], exact finset.prod_congr rfl (λ i _, by simp only [pi.nat_apply, nat.cast_id]), end end pi section locally_finite variables [Π i, partial_order (α i)] [Π i, has_zero (α i)] [Π i, locally_finite_order (α i)] instance : locally_finite_order (Π₀ i, α i) := locally_finite_order.of_Icc (Π₀ i, α i) (λ f g, (f.support ∪ g.support).dfinsupp $ f.range_Icc g) (λ f g x, begin refine (mem_dfinsupp_iff_of_support_subset $ support_range_Icc_subset).trans _, simp_rw [mem_range_Icc_apply_iff, forall_and_distrib], refl, end) variables (f g : Π₀ i, α i) lemma card_Icc : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card := card_dfinsupp _ _ lemma card_Ico : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end locally_finite end dfinsupp
d06b34e2aca6a6621f7572acd56200b6ff435b4d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/equiv/fin.lean
5531aced375308d68fff5f608e90cfd381581e2d
[ "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
11,290
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 data.fin import data.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universe variables u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv_punit_of_unique /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := equiv.subtype_equiv_right (λ x, by subst h) @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin n) : fin (n + 1) ≃ option (fin n) := { to_fun := λ x, if x = i.cast_succ then none else some (i.pred_above x), inv_fun := λ x, x.cases_on' i.cast_succ (fin.succ_above i.cast_succ), left_inv := λ x, if h : x = i.cast_succ then by simp [h] else by simp [h, fin.succ_above_ne], right_inv := λ x, by { cases x; simp [fin.succ_above_ne] }} @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i.cast_succ = none := by simp [fin_succ_equiv'] lemma fin_succ_equiv'_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) : (fin_succ_equiv' i) m.cast_succ = some m := begin have : m.cast_succ ≤ i.cast_succ := h.le, simp [fin_succ_equiv', h.ne, fin.pred_above_below, this] end lemma fin_succ_equiv'_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) : (fin_succ_equiv' i) m.succ = some m := begin have : i.cast_succ < m.succ, { refine (lt_of_le_of_lt _ m.cast_succ_lt_succ), exact h }, simp [fin_succ_equiv', this, fin.pred_above_above, ne_of_gt] end @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i.cast_succ := rfl lemma fin_succ_equiv_symm'_some_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := by simp [fin_succ_equiv', ne_of_gt h, fin.succ_above, not_le_of_gt h] lemma fin_succ_equiv_symm'_some_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) : (fin_succ_equiv' i).symm (some m) = m.succ := by simp [fin_succ_equiv', fin.succ_above, h.not_lt] lemma fin_succ_equiv_symm'_coe_below {n : ℕ} {i m : fin (n + 1)} (h : m < i) : (fin_succ_equiv' i).symm m = m.cast_succ := by { convert fin_succ_equiv_symm'_some_below h; simp } lemma fin_succ_equiv_symm'_coe_above {n : ℕ} {i m : fin (n + 1)} (h : i ≤ m) : (fin_succ_equiv' i).symm m = m.succ := by { convert fin_succ_equiv_symm'_some_above h; simp } /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ -- TODO: make the `n = 0` case neater def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := nat.cases_on n { to_fun := λ _, none, inv_fun := λ _, 0, left_inv := λ _, by simp, right_inv := λ x, by { cases x, simp, exact x.elim0 } } (λ _, fin_succ_equiv' 0) @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := by cases n; refl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := begin cases n, { exact m.elim0 }, convert fin_succ_equiv'_above m.zero_le end @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := by cases n; refl @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := begin cases n, { exact m.elim0 }, convert fin_succ_equiv_symm'_some_above m.zero_le end @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv (n + 1) := rfl /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := λ x, sum.rec_on x (λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩) (λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩), inv_fun := λ x, if H : x.1 < m then sum.inl ⟨x.1, H⟩ else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩, left_inv := λ x, begin cases x with y y, { simp [fin.ext_iff, y.is_lt], }, { have H : ¬m + y.val < m := not_lt_of_ge (nat.le_add_right _ _), simp [H, nat.add_sub_cancel_left, fin.ext_iff] } end, right_inv := λ x, begin by_cases H : (x:ℕ) < m, { dsimp, rw [dif_pos H], simp }, { dsimp, rw [dif_neg H], simp [fin.ext_iff, nat.add_sub_of_le (le_of_not_gt H)] } end } @[simp] lemma fin_sum_fin_equiv_apply_left (x : fin m) : @fin_sum_fin_equiv m n (sum.inl x) = ⟨x.1, nat.lt_of_lt_of_le x.2 $ nat.le_add_right m n⟩ := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (x : fin n) : @fin_sum_fin_equiv m n (sum.inr x) = ⟨m + x.1, nat.add_lt_add_left x.2 m⟩ := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_left (x : fin (m + n)) (h : ↑x < m) : fin_sum_fin_equiv.symm x = sum.inl ⟨x.1, h⟩ := by simp [fin_sum_fin_equiv, dif_pos h] @[simp] lemma fin_sum_fin_equiv_symm_apply_right (x : fin (m + n)) (h : m ≤ ↑x) : fin_sum_fin_equiv.symm x = sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ h).symm ▸ x.2⟩ := by simp [fin_sum_fin_equiv, dif_neg (not_lt.mpr h)] /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := begin dsimp [fin_add_flip, fin_sum_fin_equiv], rw [dif_pos h], refl, end @[simp] lemma fin_add_flip_apply_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, lt_of_le_of_lt (nat.sub_le _ _) (by { convert h₂ using 1, simp [add_comm] })⟩ := begin dsimp [fin_add_flip, fin_sum_fin_equiv], rw [dif_neg (not_lt.mpr h₁)], refl, end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
4b626d77c8ea9fd64735447f7602939cda94e598
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/array/lemmas.lean
15745bf1532134e66d638b8c6b5c96a3fa21f91e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,569
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, Mario Carneiro -/ import control.traversable.equiv import data.vector.basic universes u v w namespace d_array variables {n : ℕ} {α : fin n → Type u} instance [∀ i, inhabited (α i)] : inhabited (d_array n α) := ⟨⟨default⟩⟩ end d_array namespace array instance {n α} [inhabited α] : inhabited (array n α) := d_array.inhabited theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α} (hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list := by congr; assumption /- rev_list -/ section rev_list variables {n : ℕ} {α : Type u} {a : array n α} theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α), (a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t | 0 h t := rfl | (i+1) h t := rev_list_reverse_aux i _ _ @[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list := rev_list_reverse_aux _ _ _ @[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list := by rw [←rev_list_reverse, list.reverse_reverse] end rev_list /- mem -/ section mem variables {n : ℕ} {α : Type u} {v : α} {a : array n α} theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v := iff.rfl theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n), (∃ (j : fin n), (j : ℕ) < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h [] | 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩ | (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in ⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1) (λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩) (λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e; have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]), λ m, begin simp [d_array.iterate_aux, list.mem] at m, cases m with e m', exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩, exact let ⟨j, ji, e⟩ := IH.2 m' in ⟨j, nat.le_succ_of_le ji, e⟩ end⟩ @[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a := iff.symm $ iff.trans (exists_congr $ λ j, iff.symm $ show j.1 < n ∧ read a j = v ↔ read a j = v, from and_iff_right j.2) (mem_rev_list_aux _) @[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a := by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list end mem /- foldr -/ section foldr variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α} theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n), (d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b | 0 h := rfl | (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _) theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f := rev_list_foldr_aux _ end foldr /- foldl -/ section foldl variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α} theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) := by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr] end foldl /- length -/ section length variables {n : ℕ} {α : Type u} theorem rev_list_length_aux (a : array n α) (i h) : (a.iterate_aux (λ _, (::)) i h []).length = i := by induction i; simp [*, d_array.iterate_aux] @[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n := rev_list_length_aux a _ _ @[simp] theorem to_list_length (a : array n α) : a.to_list.length = n := by rw[←rev_list_reverse, list.length_reverse, rev_list_length] end length /- nth -/ section nth variables {n : ℕ} {α : Type u} {a : array n α} theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'}, (∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) → (a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩ | 0 _ _ _ al := al i _ $ zero_add _ | (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk, show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from match k, hjk, tl with | 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end | k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [add_comm, add_assoc, *]; cc) end theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ := to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero) @[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') : list.nth_le a.to_list i h' = a.read i := by cases i; apply to_list_nth_le theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v := begin rw list.nth_eq_some, have ll := to_list_length a, split; intro h; cases h with h e; subst v, { exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ }, { exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ } end theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i v := list.ext_le (by simp) $ λ j h₁ h₂, begin have h₃ : j < n, {simpa using h₁}, rw [to_list_nth_le _ h₃], refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm, by_cases ij : (i : ℕ) = j, { subst j, rw [show (⟨(i : ℕ), h₃⟩ : fin _) = i, from fin.eq_of_veq rfl, array.read_write, list.nth_update_nth_of_lt], simp [h₃] }, { rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne, to_list_nth.2 ⟨h₃, rfl⟩], exact fin.ne_of_vne ij } end end nth /- enum -/ section enum variables {n : ℕ} {α : Type u} {a : array n α} theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v := by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm] end enum /- to_array -/ section to_array variables {n : ℕ} {α : Type u} @[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a := heq_of_heq_of_eq (@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) == (@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $ d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _ @[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l := list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ h2 _ end to_array /- push_back -/ section push_back variables {n : ℕ} {α : Type u} {v : α} {a : array n α} lemma push_back_rev_list_aux : ∀ i h h', d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' [] | 0 h h' := rfl | (i+1) h h' := begin simp [d_array.iterate_aux], refine ⟨_, push_back_rev_list_aux _ _ _⟩, dsimp [read, d_array.read, push_back], rw [dif_neg], refl, exact ne_of_lt h', end @[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list := begin unfold push_back rev_list foldl iterate d_array.iterate, dsimp [d_array.iterate_aux, read, d_array.read, push_back], rw [dif_pos (eq.refl n)], apply congr_arg, apply push_back_rev_list_aux end @[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] := by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons] @[simp] lemma read_push_back_left (i : fin n) : (a.push_back v).read i.cast_succ = a.read i := begin cases i with i hi, have : ¬ i = n := ne_of_lt hi, simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read] end @[simp] lemma read_push_back_right : (a.push_back v).read (fin.last _) = v := begin cases hn : fin.last n with k hk, have : k = n := by simpa [fin.eq_iff_veq ] using hn.symm, simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read] end end push_back /- foreach -/ section foreach variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β} {a : array n α} @[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) := rfl end foreach /- map -/ section map variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α} theorem read_map : (a.map f).read i = f (a.read i) := read_foreach end map /- map₂ -/ section map₂ variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α} @[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) := read_foreach end map₂ end array namespace equiv /-- The natural equivalence between length-`n` heterogeneous arrays and dependent functions from `fin n`. -/ def d_array_equiv_fin {n : ℕ} (α : fin n → Type*) : d_array n α ≃ (Π i, α i) := ⟨d_array.read, d_array.mk, λ ⟨f⟩, rfl, λ f, rfl⟩ /-- The natural equivalence between length-`n` arrays and functions from `fin n`. -/ def array_equiv_fin (n : ℕ) (α : Type*) : array n α ≃ (fin n → α) := d_array_equiv_fin _ /-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/ def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α := (vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm end equiv namespace array open function variable {n : ℕ} instance : traversable (array n) := @equiv.traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ instance : is_lawful_traversable (array n) := @equiv.is_lawful_traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ _ end array
1c747878e145d14f56098b4cf273b2738098311a
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Std/Data/PersistentHashMap.lean
15a864b6ac27b0634f8a802ebd2cb5eaaee916a0
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
13,304
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 -/ namespace Std universes u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) where | entry (key : α) (val : β) : Entry α β σ | ref (node : σ) : Entry α β σ | null : Entry α β σ instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) where | entries (es : Array (Entry α β (Node α β))) : Node α β | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray size : Nat := 0 abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap variable {α : Type u} {β : Type v} def empty [BEq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop where | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop where | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem size_set {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := by simp [h] private theorem size_push {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by simp [h] partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩ ⟨Node.collision (keys.set idx k) (vals.set j v) (size_set heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (size_push heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions let ks := (ks.push k₁).push k₂ let vs : Array β := Array.mkEmpty maxCollisions let vs := (vs.push v₁).push v₂ Node.collision ks vs rfl partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let rec traverse (i : Nat) (entries : Node α β) : Node α β := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ let h := hash k let h := div2Shift h (shift * (depth - 1)) traverse (i+1) (insertAux entries h depth k v) else entries traverse 0 mkEmptyEntries | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat Node.entries $ entries.modify j fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert [BEq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 } partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (vals.get ⟨i, by rw [←heq]; assumption⟩) else findAtAux keys vals heq (i+1) k else none partial def findAux [BEq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k) k @[inline] def getOp [BEq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β := self.find? idx @[inline] def findD [BEq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [BEq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (k', vals.get ⟨i, by rw [←heq]; assumption⟩) else findEntryAtAux keys vals heq (i+1) k else none partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k) k partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then true else containsAtAux keys vals heq (i+1) k else false partial def containsAux [BEq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' v => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) := if h : i < a.size then match a.get ⟨i, h⟩ with | Entry.null => isUnaryEntries a (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries a (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have : 0 < keys.size := by rw [←h]; decide some (keys.get ⟨0, this⟩, vals.get ⟨0, by rw [←heq]; assumption⟩) else none partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq) have : keys.size - 1 = vals.size - 1 := by rw [heq] (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat let entry := entries.get! j match entry with | Entry.null => (n, false) | Entry.entry k' v => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null let (newNode, deleted) := eraseAux node (div2Shift h shift) k if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase [BEq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k let (n, del) := eraseAux n h k { root := n, size := if del then sz - 1 else sz } section variable {m : Type w → Type w'} [Monad m] variable {σ : Type w} @[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => let rec traverse (i : Nat) (acc : σ) : m σ := do if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ traverse (i+1) (← f acc k v) else pure acc traverse 0 acc | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux f node acc) acc @[specialize] def foldlM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ := foldlMAux f map.root init @[specialize] def forM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ @[specialize] def foldl [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ := Id.run $ map.foldlM f init end def toList [BEq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) := m.foldl (init := []) fun ps k v => (k, v) :: ps structure Stats where numNodes : Nat := 0 numNull : Nat := 0 numCollisions : Nat := 0 maxDepth : Nat := 0 partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth } entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats [BEq α] [Hashable α] (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentHashMap end Std
abdb84460dffc235d9fb66dbbd1693a27a1f8287
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/matrix/notation.lean
f5a8a68b300657296e8e3686b3d9e1709c2257eb
[ "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
17,725
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen Notation for vectors and matrices -/ import data.fintype.card import data.matrix.basic import tactic.fin_cases /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives a matrix, so `![![a, b], ![c, d]] : matrix (fin 2) (fin 2) α`. This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of this notation. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} open_locale matrix section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin_zero_elim /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} [fintype m'] [fintype n'] [fintype o'] lemma empty_eq (v : fin 0 → α) : v = ![] := by { ext i, fin_cases i } section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty.2 $ λ ⟨k⟩, k.elim0 /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := cons_val_succ x u 0 @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { fin_cases i, refl } /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ @[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v := by { ext, simp [fin.append] } @[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : fin.append ho (vec_cons x u) v = vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [fin.append], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, fin.append], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact add_lt_add i.property i.property } end lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, fin.append], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := rfl @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _ @[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = λ _, ![] := funext (λ _, empty_eq _) lemma mul_val_succ (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl @[simp] lemma cons_mul (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) : vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) : vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) : vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, simp [vec_mul_vec]} end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_cons (x y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x * y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor end matrix
b1ee43674fca2b2440c1efa28373de077d4d0602
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/lint/type_classes.lean
0b0efafc654f0599bf651cb144c556554ed5ddc0
[ "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
24,729
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import data.bool.basic import meta.rb_map import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority. * `has_nonempty_instances` checks that every type has a `nonempty` instance, an `inhabited` instance, or a `unique` instance. * `impossible_instance` checks that there are no instances which can never apply. * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments. * `dangerous_instance` checks for instances that generate subproblems with metavariables. * `fails_quickly` checks that type class resolution finishes quickly. * `class_structure` checks that every `class` is a structure, i.e. `@[class] def` is forbidden. * `has_coe_variable` checks that there is no instance of type `has_coe α t`. * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]`. * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. * `linter.has_coe_to_fun` checks whether necessary `has_coe_to_fun` instances are declared. * `linter.check_reducibility` checks whether non-instances with a class as type are reducible. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do (_, tp) ← open_pis d.type, tp ← whnf tp transparency.none, let (fn, args) := tp.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_local_constant ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- There are places where typeclass arguments are specified with implicit `{}` brackets instead of the usual `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type of one of the other arguments. When they can be inferred from these other arguments, it is faster to use this method than to use type class inference. For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α` and `β` are `semiring`s as `{rα : semiring α} {rβ : semiring β}` rather than the usual `[semiring α] [semiring β]`. -/ library_note "implicit instance arguments" /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost always the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good.", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. See note [lower instance priority] for instructions to change the priority.", auto_decls := tt } /-- Reports declarations of types that do not have an nonemptiness instance. A `nonempty`, `inhabited` or `unique` instance suffices, and we prefer a computable `inhabited` or `unique` instance if possible. -/ private meta def has_nonempty_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← open_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let nonempty_insts := insts_tys.filter (λ i, i.app_fn.const_name ∈ [``nonempty, ``inhabited, `unique]), let nonempty_tys := nonempty_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ nonempty_tys then pure none else pure "nonempty/inhabited/unique instance missing" /-- A linter for missing `nonempty` instances. -/ @[linter] meta def linter.has_nonempty_instance : linter := { test := has_nonempty_instance, auto_decls := ff, no_errors_found := "No types have missing nonempty instances.", errors_found := "TYPES ARE MISSING NONEMPTY INSTANCES. The following types should have an associated instance of the class `nonempty`, or if computably possible `inhabited` or `unique`:", is_fast := ff } attribute [nolint has_nonempty_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable.", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and " ++ "therefore can never succeed. Either mark the arguments with square brackets (if it is a " ++ "class), or don't make it an instance." } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← open_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments.", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]:" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← open_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances.", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new " ++ "type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked " ++ "with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Auxilliary definition for `find_nondep` -/ meta def find_nondep_aux : list expr → expr_set → tactic expr_set | [] r := return r | (h::hs) r := do type ← infer_type h, find_nondep_aux hs $ r.union type.list_local_consts' /-- Finds all hypotheses that don't occur in the target or other hypotheses. -/ meta def find_nondep : tactic (list expr) := do ctx ← local_context, tgt ← target, lconsts ← find_nondep_aux ctx tgt.list_local_consts', return $ ctx.filter $ λ e, !lconsts.contains e /-- Tests whether type-class inference search will end quickly on certain unsolvable type-class problems. This is to detect loops or very slow searches, which are problematic (recall that normal type-class search often creates unsolvable subproblems, which have to fail quickly for type-class inference to perform well. We create these type-class problems by taking an instance, and removing the last hypothesis that doesn't appear in the goal (or a later hypothesis). Note: this argument is necessarily an instance-implicit argument if it passes the `linter.incorrect_type_class_argument`. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised (usually a maximum depth in the search). -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := retrieve $ do tt ← is_instance d.to_name | return none, let e := d.type, g ← mk_meta_var e, set_goals [g], intros, l@(_::_) ← find_nondep | return none, -- if all arguments occur in the goal, this instance is ok clear l.ilast, reset_instance_cache, state ← read, let state_msg := "\nState:\n" ++ to_string state, tgt ← target >>= instantiate_mvars, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ mk_instance tgt | return none, /- it's ok if type-class inference can find an instance with fewer hypotheses. This happens a lot for `has_sizeof` and `has_well_founded`, but can also happen if there is a noncomputable instance with fewer assumptions. -/ return $ if "tactic.mk_instance failed to generate instance for".is_prefix_of msg then none else some $ (++ state_msg) $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. We currently set the number of steps in the type-class search pretty high. Some instances take quite some time to fail, and we seem to run against the caching issue in https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/odd.20repeated.20type.20class.20search -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 30000, auto_decls := tt, no_errors_found := "No type-class searches timed out.", errors_found := "TYPE CLASS SEARCHES TIMED OUT. The following instances are part of a loop, or an excessively long search. It is common that the loop occurs in a different class than the one flagged below, but usually an instance that is part of the loop is also flagged. To debug: (1) run `scripts/mk_all.sh` and create a file with `import all` and `set_option trace.class_instances true` (2) Recreate the state shown in the error message. You can do this easily by copying the type of the instance (the output of `#check @my_instance`), turning this into an example and removing the last argument in square brackets. Prove the example using `by apply_instance`. For example, if `additive.topological_add_group` raises an error, run ``` example {G : Type*} [topological_space G] [group G] : topological_add_group (additive G) := by apply_instance ``` (3) What error do you get? (3a) If the error is \"tactic.mk_instance failed to generate instance\", there might be nothing wrong. But it might take unreasonably long for the type-class inference to fail. Check the trace to see if type-class inference takes any unnecessary long unexpected turns. If not, feel free to increase the value in the definition of the linter `fails_quickly`. (3b) If the error is \"maximum class-instance resolution depth has been reached\" there is almost certainly a loop in the type-class inference. Find which instance causes the type-class inference to go astray, and fix that instance.", is_fast := ff } /-- Checks that all uses of the `@[class]` attribute apply to structures or inductive types. This is future-proofing for lean 4, which no longer supports `@[class] def`. -/ private meta def class_structure (n : name) : tactic (option string) := do is_class ← has_attribute' `class n, if is_class then do env ← get_env, pure $ if env.is_inductive n then none else "is a non-structure or inductive type marked @[class]" else pure none /-- A linter object for `class_structure`. -/ @[linter] meta def linter.class_structure : linter := { test := λ d, class_structure d.to_name, auto_decls := tt, no_errors_found := "All classes are structures.", errors_found := "USE OF @[class] def IS DISALLOWED:" } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances.", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`.", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused elsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. Theorems in the `decidable` namespace are exempt from the check. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, ff ← pure $ (`decidable).is_prefix_of d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`.", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em dec_em' not.decidable_imp_symm /-- Checks whether a declaration is `Prop`-valued and takes a `fintype _` hypothesis that is unused elsewhere in the type. In this case, that hypothesis can be replaced with `casesI nonempty_fintype _` in the proof. -/ meta def linter.fintype_finite_fun (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let fintype_binders := binders.filter $ λ pr, pr.2.type.is_app_of `fintype, if fintype_binders.length = 0 then return none else (λ s, some $ "The following `fintype` hypotheses should be replaced with `casesI nonempty_fintype _` in the proof. " ++ s) <$> print_arguments fintype_binders /-- A linter object for `fintype` vs `finite`. -/ @[linter] meta def linter.fintype_finite : linter := { test := linter.fintype_finite_fun, auto_decls := ff, no_errors_found := "No uses of `fintype` arguments should be replaced with `casesI nonempty_fintype _`.", errors_found := "USES OF `fintype` SHOULD BE REPLACED WITH `casesI nonempty_fintype _` IN THE PROOF." } private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do tt ← return d.is_trusted | pure none, mk_meta_var d.type >>= set_goals ∘ pure, args ← unfreezing intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty _) >>= mk_instance | pure none, set_bool_option `pp.all true, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note [function coercion]." } /-- Checks whether an instance contains a semireducible non-instance with a class as type in its value. We add some restrictions to get not too many false positives: * We only consider classes with an `add` or `mul` field, since those classes are most likely to occur as a field to another class, and be an extension of another class. * We only consider instances of type-valued classes and non-instances that are definitions. * We currently ignore declarations `foo` that have a `foo._main` declaration. We could look inside, or at the generated equation lemmas, but it's unlikely that there are many problematic instances defined using the equation compiler. -/ meta def check_reducible_non_instances (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, ff ← is_prop d.type | return none, env ← get_env, -- We only check if the class of the instance contains an `add` or a `mul` field. let cls := d.type.pi_codomain.get_app_fn.const_name, some constrs ← return $ env.structure_fields cls | return none, tt ← return $ constrs.mem `add || constrs.mem `mul | return none, l ← d.value.list_constant.mfilter $ λ nm, do { d ← env.get nm, ff ← is_instance nm | return ff, tt ← is_class d.type | return ff, tt ← return d.is_definition | return ff, -- We only check if the class of the non-instance contains an `add` or a `mul` field. let cls := d.type.pi_codomain.get_app_fn.const_name, some constrs ← return $ env.structure_fields cls | return ff, tt ← return $ constrs.mem `add || constrs.mem `mul | return ff, ff ← has_attribute' `reducible nm | return ff, return tt }, if l.empty then return none else -- we currently ignore declarations that have a `foo._main` declaration. if l.to_list = [d.to_name ++ `_main] then return none else return $ some $ "This instance contains the declarations " ++ to_string l.to_list ++ ", which are semireducible non-instances." /-- A linter that checks whether an instance contains a semireducible non-instance. -/ @[linter] meta def linter.check_reducibility : linter := { test := check_reducible_non_instances, auto_decls := ff, no_errors_found := "All non-instances are reducible.", errors_found := "THE FOLLOWING INSTANCES MIGHT NOT REDUCE. These instances contain one or more declarations that are not instances and are also not marked `@[reducible]`. This means that type-class inference cannot unfold these declarations, " ++ "which might mean that type-class inference cannot infer that two instances are definitionally " ++ "equal. This can cause unexpected errors when this class occurs " ++ "as an *argument* to a type-class problem. See note [reducible non-instances].", is_fast := tt }
f698215b8e11495185201b9cd4917eb33f5aca92
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/algebra/category/limits/limits.hlean
3a1d5f8fc4b544ffd2986ce4abb23cfe7c9cd912
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,439
hlean
/- 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 Limits in a category -/ import ..constructions.cone ..constructions.discrete ..constructions.product ..constructions.finite_cats ..category ..constructions.functor open is_trunc functor nat_trans eq namespace category variables {ob : Type} [C : precategory ob] {c c' : ob} (D I : Precategory) include C definition is_terminal [class] (c : ob) := Πd, is_contr (d ⟶ c) definition is_contr_of_is_terminal (c d : ob) [H : is_terminal d] : is_contr (c ⟶ d) := H c local attribute is_contr_of_is_terminal [instance] definition terminal_morphism (c c' : ob) [H : is_terminal c'] : c ⟶ c' := !center definition hom_terminal_eq [H : is_terminal c'] (f f' : c ⟶ c') : f = f' := !is_prop.elim definition eq_terminal_morphism [H : is_terminal c'] (f : c ⟶ c') : f = terminal_morphism c c' := !is_prop.elim definition terminal_iso_terminal (c c' : ob) [H : is_terminal c] [K : is_terminal c'] : c ≅ c' := iso.MK !terminal_morphism !terminal_morphism !hom_terminal_eq !hom_terminal_eq local attribute is_terminal [reducible] theorem is_prop_is_terminal [instance] : is_prop (is_terminal c) := _ omit C structure has_terminal_object [class] (D : Precategory) := (d : D) (is_terminal : is_terminal d) definition terminal_object [reducible] [unfold 2] := @has_terminal_object.d attribute has_terminal_object.is_terminal [instance] variable {D} definition terminal_object_iso_terminal_object (H₁ H₂ : has_terminal_object D) : @terminal_object D H₁ ≅ @terminal_object D H₂ := !terminal_iso_terminal theorem is_prop_has_terminal_object [instance] (D : Category) : is_prop (has_terminal_object D) := begin apply is_prop.mk, intro t₁ t₂, induction t₁ with d₁ H₁, induction t₂ with d₂ H₂, assert p : d₁ = d₂, { apply eq_of_iso, apply terminal_iso_terminal}, induction p, exact ap _ !is_prop.elim end variable (D) definition has_limits_of_shape [class] := Π(F : I ⇒ D), has_terminal_object (cone F) /- The next definitions states that a category is complete with respect to diagrams in a certain universe. "is_complete.{o₁ h₁ o₂ h₂}" means that D is complete with respect to diagrams with shape in Precategory.{o₂ h₂} -/ definition is_complete.{o₁ h₁ o₂ h₂} [class] (D : Precategory.{o₁ h₁}) := Π(I : Precategory.{o₂ h₂}), has_limits_of_shape D I definition has_limits_of_shape_of_is_complete [instance] [H : is_complete D] (I : Precategory) : has_limits_of_shape D I := H I section open pi theorem is_prop_has_limits_of_shape [instance] (D : Category) (I : Precategory) : is_prop (has_limits_of_shape D I) := by apply is_trunc_pi; intro F; exact is_prop_has_terminal_object (Category_cone F) local attribute is_complete [reducible] theorem is_prop_is_complete [instance] (D : Category) : is_prop (is_complete D) := _ end variables {D I} definition has_terminal_object_cone [H : has_limits_of_shape D I] (F : I ⇒ D) : has_terminal_object (cone F) := H F local attribute has_terminal_object_cone [instance] variables (F : I ⇒ D) [H : has_limits_of_shape D I] {i j : I} include H definition limit_cone : cone F := !terminal_object definition is_terminal_limit_cone [instance] : is_terminal (limit_cone F) := has_terminal_object.is_terminal _ section specific_limit omit H variable {F} variables (x : cone_obj F) [K : is_terminal x] include K definition to_limit_object : D := cone_to_obj x definition to_limit_nat_trans : constant_functor I (to_limit_object x) ⟹ F := cone_to_nat x definition to_limit_morphism (i : I) : to_limit_object x ⟶ F i := to_limit_nat_trans x i theorem to_limit_commute {i j : I} (f : i ⟶ j) : to_fun_hom F f ∘ to_limit_morphism x i = to_limit_morphism x j := naturality (to_limit_nat_trans x) f ⬝ !id_right definition to_limit_cone_obj [constructor] {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) : cone_obj F := cone_obj.mk d (nat_trans.mk η (λa b f, p f ⬝ !id_right⁻¹)) definition to_hom_limit {d : D} (η : Πi, d ⟶ F i) (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) : d ⟶ to_limit_object x := cone_to_hom (terminal_morphism (to_limit_cone_obj x p) x) theorem to_hom_limit_commute {d : D} (η : Πi, d ⟶ F i) (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) (i : I) : to_limit_morphism x i ∘ to_hom_limit x η p = η i := cone_to_eq (terminal_morphism (to_limit_cone_obj x p) x) i definition to_limit_cone_hom [constructor] {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h : d ⟶ to_limit_object x} (q : Πi, to_limit_morphism x i ∘ h = η i) : cone_hom (to_limit_cone_obj x p) x := cone_hom.mk h q variable {x} theorem to_eq_hom_limit {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h : d ⟶ to_limit_object x} (q : Πi, to_limit_morphism x i ∘ h = η i) : h = to_hom_limit x η p := ap cone_to_hom (eq_terminal_morphism (to_limit_cone_hom x p q)) theorem to_limit_cone_unique {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h₁ : d ⟶ to_limit_object x} (q₁ : Πi, to_limit_morphism x i ∘ h₁ = η i) {h₂ : d ⟶ to_limit_object x} (q₂ : Πi, to_limit_morphism x i ∘ h₂ = η i): h₁ = h₂ := to_eq_hom_limit p q₁ ⬝ (to_eq_hom_limit p q₂)⁻¹ omit K definition to_limit_object_iso_to_limit_object [constructor] (x y : cone_obj F) [K : is_terminal x] [L : is_terminal y] : to_limit_object x ≅ to_limit_object y := cone_iso_pr1 !terminal_iso_terminal end specific_limit /- TODO: relate below definitions to above definitions. However, type class resolution seems to fail... -/ definition limit_object : D := cone_to_obj (limit_cone F) definition limit_nat_trans : constant_functor I (limit_object F) ⟹ F := cone_to_nat (limit_cone F) definition limit_morphism (i : I) : limit_object F ⟶ F i := limit_nat_trans F i variable {H} theorem limit_commute {i j : I} (f : i ⟶ j) : to_fun_hom F f ∘ limit_morphism F i = limit_morphism F j := naturality (limit_nat_trans F) f ⬝ !id_right variable [H] definition limit_cone_obj [constructor] {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) : cone_obj F := cone_obj.mk d (nat_trans.mk η (λa b f, p f ⬝ !id_right⁻¹)) variable {H} definition hom_limit {d : D} (η : Πi, d ⟶ F i) (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) : d ⟶ limit_object F := cone_to_hom (@(terminal_morphism (limit_cone_obj F p) _) (is_terminal_limit_cone _)) theorem hom_limit_commute {d : D} (η : Πi, d ⟶ F i) (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) (i : I) : limit_morphism F i ∘ hom_limit F η p = η i := cone_to_eq (@(terminal_morphism (limit_cone_obj F p) _) (is_terminal_limit_cone _)) i definition limit_cone_hom [constructor] {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h : d ⟶ limit_object F} (q : Πi, limit_morphism F i ∘ h = η i) : cone_hom (limit_cone_obj F p) (limit_cone F) := cone_hom.mk h q variable {F} theorem eq_hom_limit {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h : d ⟶ limit_object F} (q : Πi, limit_morphism F i ∘ h = η i) : h = hom_limit F η p := ap cone_to_hom (@eq_terminal_morphism _ _ _ _ (is_terminal_limit_cone _) (limit_cone_hom F p q)) theorem limit_cone_unique {d : D} {η : Πi, d ⟶ F i} (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) {h₁ : d ⟶ limit_object F} (q₁ : Πi, limit_morphism F i ∘ h₁ = η i) {h₂ : d ⟶ limit_object F} (q₂ : Πi, limit_morphism F i ∘ h₂ = η i): h₁ = h₂ := eq_hom_limit p q₁ ⬝ (eq_hom_limit p q₂)⁻¹ definition limit_hom_limit {F G : I ⇒ D} (η : F ⟹ G) : limit_object F ⟶ limit_object G := hom_limit _ (λi, η i ∘ limit_morphism F i) abstract by intro i j f; rewrite [assoc,naturality,-assoc,limit_commute] end theorem limit_hom_limit_commute {F G : I ⇒ D} (η : F ⟹ G) : limit_morphism G i ∘ limit_hom_limit η = η i ∘ limit_morphism F i := !hom_limit_commute -- theorem hom_limit_commute {d : D} (η : Πi, d ⟶ F i) -- (p : Π⦃i j : I⦄ (f : i ⟶ j), to_fun_hom F f ∘ η i = η j) (i : I) -- : limit_morphism F i ∘ hom_limit F η p = η i := -- cone_to_eq (@(terminal_morphism (limit_cone_obj F p) _) (is_terminal_limit_cone _)) i omit H variable (F) definition limit_object_iso_limit_object [constructor] (H₁ H₂ : has_limits_of_shape D I) : @(limit_object F) H₁ ≅ @(limit_object F) H₂ := cone_iso_pr1 !terminal_object_iso_terminal_object definition limit_functor [constructor] (D I : Precategory) [H : has_limits_of_shape D I] : D ^c I ⇒ D := begin fapply functor.mk: esimp, { intro F, exact limit_object F}, { apply @limit_hom_limit}, { intro F, unfold limit_hom_limit, refine (eq_hom_limit _ _)⁻¹, intro i, apply comp_id_eq_id_comp}, { intro F G H η θ, unfold limit_hom_limit, refine (eq_hom_limit _ _)⁻¹, intro i, rewrite [assoc, hom_limit_commute, -assoc, hom_limit_commute, assoc]} end section bin_products open bool prod.ops definition has_binary_products [reducible] (D : Precategory) := has_limits_of_shape D c2 variables [K : has_binary_products D] (d d' : D) include K definition product_object : D := limit_object (c2_functor D d d') infixr ` ×l `:75 := product_object definition pr1 : d ×l d' ⟶ d := limit_morphism (c2_functor D d d') ff definition pr2 : d ×l d' ⟶ d' := limit_morphism (c2_functor D d d') tt variables {d d'} definition hom_product {x : D} (f : x ⟶ d) (g : x ⟶ d') : x ⟶ d ×l d' := hom_limit (c2_functor D d d') (bool.rec f g) (by intro b₁ b₂ f; induction b₁: induction b₂: esimp at *; try contradiction: apply id_left) theorem pr1_hom_product {x : D} (f : x ⟶ d) (g : x ⟶ d') : !pr1 ∘ hom_product f g = f := hom_limit_commute (c2_functor D d d') (bool.rec f g) _ ff theorem pr2_hom_product {x : D} (f : x ⟶ d) (g : x ⟶ d') : !pr2 ∘ hom_product f g = g := hom_limit_commute (c2_functor D d d') (bool.rec f g) _ tt theorem eq_hom_product {x : D} {f : x ⟶ d} {g : x ⟶ d'} {h : x ⟶ d ×l d'} (p : !pr1 ∘ h = f) (q : !pr2 ∘ h = g) : h = hom_product f g := eq_hom_limit _ (bool.rec p q) theorem product_cone_unique {x : D} {f : x ⟶ d} {g : x ⟶ d'} {h₁ : x ⟶ d ×l d'} (p₁ : !pr1 ∘ h₁ = f) (q₁ : !pr2 ∘ h₁ = g) {h₂ : x ⟶ d ×l d'} (p₂ : !pr1 ∘ h₂ = f) (q₂ : !pr2 ∘ h₂ = g) : h₁ = h₂ := eq_hom_product p₁ q₁ ⬝ (eq_hom_product p₂ q₂)⁻¹ variable (D) -- TODO: define this in terms of limit_functor and functor_two_left (in exponential_laws) definition product_functor [constructor] : D ×c D ⇒ D := functor.mk (λx, product_object x.1 x.2) (λx y f, hom_product (f.1 ∘ !pr1) (f.2 ∘ !pr2)) abstract begin intro x, symmetry, apply eq_hom_product: apply comp_id_eq_id_comp end end abstract begin intro x y z g f, symmetry, apply eq_hom_product, rewrite [assoc,pr1_hom_product,-assoc,pr1_hom_product,assoc], rewrite [assoc,pr2_hom_product,-assoc,pr2_hom_product,assoc] end end omit K variables {D} (d d') definition product_object_iso_product_object [constructor] (H₁ H₂ : has_binary_products D) : @product_object D H₁ d d' ≅ @product_object D H₂ d d' := limit_object_iso_limit_object _ H₁ H₂ end bin_products section equalizers open bool prod.ops sum equalizer_category_hom definition has_equalizers [reducible] (D : Precategory) := has_limits_of_shape D equalizer_category variables [K : has_equalizers D] include K variables {d d' x : D} (f g : d ⟶ d') definition equalizer_object : D := limit_object (equalizer_category_functor D f g) definition equalizer : equalizer_object f g ⟶ d := limit_morphism (equalizer_category_functor D f g) ff theorem equalizes : f ∘ equalizer f g = g ∘ equalizer f g := limit_commute (equalizer_category_functor D f g) (inl f1) ⬝ (limit_commute (equalizer_category_functor D f g) (inl f2))⁻¹ variables {f g} definition hom_equalizer (h : x ⟶ d) (p : f ∘ h = g ∘ h) : x ⟶ equalizer_object f g := hom_limit (equalizer_category_functor D f g) (bool.rec h (g ∘ h)) begin intro b₁ b₂ i; induction i with j j: induction j, -- report(?) "esimp" is super slow here exact p, reflexivity, apply id_left end theorem equalizer_hom_equalizer (h : x ⟶ d) (p : f ∘ h = g ∘ h) : equalizer f g ∘ hom_equalizer h p = h := hom_limit_commute (equalizer_category_functor D f g) (bool.rec h (g ∘ h)) _ ff theorem eq_hom_equalizer {h : x ⟶ d} (p : f ∘ h = g ∘ h) {i : x ⟶ equalizer_object f g} (q : equalizer f g ∘ i = h) : i = hom_equalizer h p := eq_hom_limit _ (bool.rec q begin refine ap (λx, x ∘ i) (limit_commute (equalizer_category_functor D f g) (inl f2))⁻¹ ⬝ _, refine !assoc⁻¹ ⬝ _, exact ap (λx, _ ∘ x) q end) theorem equalizer_cone_unique {h : x ⟶ d} (p : f ∘ h = g ∘ h) {i₁ : x ⟶ equalizer_object f g} (q₁ : equalizer f g ∘ i₁ = h) {i₂ : x ⟶ equalizer_object f g} (q₂ : equalizer f g ∘ i₂ = h) : i₁ = i₂ := eq_hom_equalizer p q₁ ⬝ (eq_hom_equalizer p q₂)⁻¹ omit K variables (f g) definition equalizer_object_iso_equalizer_object [constructor] (H₁ H₂ : has_equalizers D) : @equalizer_object D H₁ _ _ f g ≅ @equalizer_object D H₂ _ _ f g := limit_object_iso_limit_object _ H₁ H₂ end equalizers section pullbacks open sum prod.ops pullback_category_ob pullback_category_hom definition has_pullbacks [reducible] (D : Precategory) := has_limits_of_shape D pullback_category variables [K : has_pullbacks D] include K variables {d₁ d₂ d₃ x : D} (f : d₁ ⟶ d₃) (g : d₂ ⟶ d₃) definition pullback_object : D := limit_object (pullback_category_functor D f g) definition pullback : pullback_object f g ⟶ d₂ := limit_morphism (pullback_category_functor D f g) BL definition pullback_rev : pullback_object f g ⟶ d₁ := limit_morphism (pullback_category_functor D f g) TR theorem pullback_commutes : f ∘ pullback_rev f g = g ∘ pullback f g := limit_commute (pullback_category_functor D f g) (inl f1) ⬝ (limit_commute (pullback_category_functor D f g) (inl f2))⁻¹ variables {f g} definition hom_pullback (h₁ : x ⟶ d₁) (h₂ : x ⟶ d₂) (p : f ∘ h₁ = g ∘ h₂) : x ⟶ pullback_object f g := hom_limit (pullback_category_functor D f g) (pullback_category_ob.rec h₁ h₂ (g ∘ h₂)) begin intro i₁ i₂ k; induction k with j j: induction j, exact p, reflexivity, apply id_left end theorem pullback_hom_pullback (h₁ : x ⟶ d₁) (h₂ : x ⟶ d₂) (p : f ∘ h₁ = g ∘ h₂) : pullback f g ∘ hom_pullback h₁ h₂ p = h₂ := hom_limit_commute (pullback_category_functor D f g) (pullback_category_ob.rec h₁ h₂ (g ∘ h₂)) _ BL theorem pullback_rev_hom_pullback (h₁ : x ⟶ d₁) (h₂ : x ⟶ d₂) (p : f ∘ h₁ = g ∘ h₂) : pullback_rev f g ∘ hom_pullback h₁ h₂ p = h₁ := hom_limit_commute (pullback_category_functor D f g) (pullback_category_ob.rec h₁ h₂ (g ∘ h₂)) _ TR theorem eq_hom_pullback {h₁ : x ⟶ d₁} {h₂ : x ⟶ d₂} (p : f ∘ h₁ = g ∘ h₂) {k : x ⟶ pullback_object f g} (q : pullback f g ∘ k = h₂) (r : pullback_rev f g ∘ k = h₁) : k = hom_pullback h₁ h₂ p := eq_hom_limit _ (pullback_category_ob.rec r q begin refine ap (λx, x ∘ k) (limit_commute (pullback_category_functor D f g) (inl f2))⁻¹ ⬝ _, refine !assoc⁻¹ ⬝ _, exact ap (λx, _ ∘ x) q end) theorem pullback_cone_unique {h₁ : x ⟶ d₁} {h₂ : x ⟶ d₂} (p : f ∘ h₁ = g ∘ h₂) {k₁ : x ⟶ pullback_object f g} (q₁ : pullback f g ∘ k₁ = h₂) (r₁ : pullback_rev f g ∘ k₁ = h₁) {k₂ : x ⟶ pullback_object f g} (q₂ : pullback f g ∘ k₂ = h₂) (r₂ : pullback_rev f g ∘ k₂ = h₁) : k₁ = k₂ := (eq_hom_pullback p q₁ r₁) ⬝ (eq_hom_pullback p q₂ r₂)⁻¹ variables (f g) definition pullback_object_iso_pullback_object [constructor] (H₁ H₂ : has_pullbacks D) : @pullback_object D H₁ _ _ _ f g ≅ @pullback_object D H₂ _ _ _ f g := limit_object_iso_limit_object _ H₁ H₂ end pullbacks namespace ops infixr ×l := product_object end ops end category
31c5056443cdcccdc5d17f864a3bed2026886fc4
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_2023.lean
6d5f131af897a99f197f1595e6bf3c32a1d66907
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
127
lean
variables {p q : Prop} -- BEGIN example (h₁ : ¬p) (h₂ : p) : q := begin exfalso, show false, from h₁ h₂ end -- END
be93723255a7235d096cf49bcd757688996c2295
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/multiplicity.lean
b95e5c0e42adbe2c434aca7cdf11ce8e4ae98198
[ "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
19,767
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Chris Hughes -/ import algebra.associated import algebra.big_operators.basic import ring_theory.valuation.basic /-! # Multiplicity of a divisor For a commutative monoid, this file introduces the notion of multiplicity of a divisor and proves several basic results on it. ## Main definitions * `multiplicity a b`: for two elements `a` and `b` of a commutative monoid returns the largest number `n` such that `a ^ n ∣ b` or infinity, written `⊤`, if `a ^ n ∣ b` for all natural numbers `n`. * `multiplicity.finite a b`: a predicate denoting that the multiplicity of `a` in `b` is finite. -/ variables {α : Type*} open nat part open_locale big_operators /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_monoid α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := enat.find $ λ n, ¬a ^ (n + 1) ∣ b namespace multiplicity section comm_monoid variables [comm_monoid α] /-- `multiplicity.finite a b` indicates that the multiplicity of `a` in `b` is finite. -/ @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b := begin apply part.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp } } end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _ }) (by simpa [finite, not_not] using h), by simp [finite, multiplicity, not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit.pow (n + 1)) $ λ h, hn (h b) lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (h.trans (by simp [mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := by { rw ← enat.some_eq_coe, exact nat.cases_on k (λ _, by { rw pow_zero, exact one_dvd _ }) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) } lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, by rw [enat.lt_coe_iff] at hm; exact nat.find_spec hm.fst ((pow_dvd_pow _ hm.snd).trans h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by { rw [enat.le_coe_iff], exact ⟨this, nat.find_min' _ hsucc⟩ } lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} : multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b := by { rw [pow_dvd_iff_le_multiplicity, not_le] } lemma eq_coe_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := begin rw [← enat.some_eq_coe], exact ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by { rw [enat.lt_coe_iff], exact ⟨h₁, lt_succ_self _⟩ })⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ end lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := (enat.find_eq_top_iff _).trans $ by { simp only [not_not], exact ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _}) (λ n, h _), λ h n, h _⟩ } @[simp] lemma is_unit_left {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (ha.pow _) _) lemma is_unit_right {a b : α} (ha : ¬is_unit a) (hb : is_unit b) : multiplicity a b = 0 := eq_coe_iff.2 ⟨show a ^ 0 ∣ b, by simp only [pow_zero, one_dvd], by { rw pow_one, exact λ h, mt (is_unit_of_dvd_unit h) ha hb }⟩ @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := is_unit_left b is_unit_one lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := is_unit_right ha is_unit_one @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := begin rw [enat.get_eq_iff_eq_coe, eq_coe_iff, pow_zero], simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha, end @[simp] lemma unit_left (a : α) (u : units α) : multiplicity (u : α) a = ⊤ := is_unit_left a u.is_unit lemma unit_right {a : α} (ha : ¬is_unit a) (u : units α) : multiplicity a u = 0 := is_unit_right ha u.is_unit lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := by { rw [← nat.cast_zero, eq_coe_iff], simpa } lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := part.eq_none_iff' lemma ne_top_iff_finite {a b : α} : multiplicity a b ≠ ⊤ ↔ finite a b := by rw [ne.def, eq_top_iff_not_finite, not_not] lemma lt_top_iff_finite {a b : α} : multiplicity a b < ⊤ ↔ finite a b := by rw [lt_top_iff_ne_top, ne_top_iff_finite] open_locale classical lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma multiplicity_le_multiplicity_of_dvd_left {a b c : α} (hdvd : a ∣ b) : multiplicity b c ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n h, (pow_dvd_pow_of_dvd hdvd n).trans h lemma eq_of_associated_left {a b c : α} (h : associated a b) : multiplicity b c = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_left h.dvd) (multiplicity_le_multiplicity_of_dvd_left h.symm.dvd) lemma multiplicity_le_multiplicity_of_dvd_right {a b c : α} (h : b ∣ c) : multiplicity a b ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n hb, hb.trans h lemma eq_of_associated_right {a b c : α} (h : associated b c) : multiplicity a b = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_right h.dvd) (multiplicity_le_multiplicity_of_dvd_right h.symm.dvd) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := begin rw ← pow_one a, apply pow_dvd_of_le_multiplicity, simpa only [nat.cast_one, enat.pos_iff_one_le] using h end lemma dvd_iff_multiplicity_pos {a b : α} : (0 : enat) < multiplicity a b ↔ a ∣ b := ⟨dvd_of_multiplicity_pos, λ hdvd, lt_of_le_of_ne (zero_le _) (λ heq, is_greatest (show multiplicity a b < ↑1, by simpa only [heq, nat.cast_zero] using enat.coe_lt_coe.mpr zero_lt_one) (by rwa pow_one a))⟩ lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from lt_of_not_ge (λ ha', by { clear h, revert ha ha1, dec_trivial! }), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end end comm_monoid section comm_monoid_with_zero variable [comm_monoid_with_zero α] lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn variable [decidable_rel ((∣) : α → α → Prop)] @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := part.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) @[simp] lemma multiplicity_zero_eq_zero_of_ne_zero (a : α) (ha : a ≠ 0) : multiplicity 0 a = 0 := begin apply multiplicity.multiplicity_eq_zero_of_not_dvd, rwa zero_dvd_iff, end end comm_monoid_with_zero section comm_semiring variables [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] open_locale classical @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := part.ext' (by simp only [multiplicity, enat.find, dvd_neg]) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a + b) = multiplicity p b := begin apply le_antisymm, { apply enat.le_of_lt_add_one, cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk, rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd, rw [← dvd_add_iff_right] at h_dvd, apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self, rw [pow_dvd_iff_le_multiplicity, nat.cast_add, ← hk, nat.cast_one], exact enat.add_one_le_of_lt h }, { convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] } end lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a - b) = multiplicity p b := by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] } lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) : multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := begin rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab, { rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab }, { contradiction }, { rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab}, end end comm_ring section comm_cancel_monoid_with_zero variables [comm_cancel_monoid_with_zero α] lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from tsub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [tsub_add_cancel_of_le (succ_le_of_lt hn0)] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (nat.le_add_right n m), finite_mul_aux hpx hb ⟨s, mul_right_cancel₀ hp.1 begin rw [tsub_add_eq_add_tsub (succ_le_of_lt hn0), tsub_add_cancel_of_le this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from tsub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [tsub_add_cancel_of_le (succ_le_of_lt hm0)] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, mul_right_cancel₀ hp.1 begin rw [add_assoc, tsub_add_cancel_of_le (succ_le_of_lt hm0)], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [pow_succ]; exact finite_mul hp ha (finite_pow ha) variable [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := by { rw ← nat.cast_one, exact eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, mul_left_cancel₀ ha0 $ by { clear _fun_match, simpa [pow_succ, mul_assoc] using hb }⟩)⟩ } @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := enat.get_eq_iff_eq_coe.2 (eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, pow_add, pow_one, mul_assoc, mul_assoc, mul_right_inj' (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, by exact not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (_root_.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp hdiva hdivb h), by rw [← enat.coe_inj, enat.coe_get, eq_coe_iff]; exact ⟨hdiv, hsucc⟩ open_locale classical protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← nat.cast_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) : multiplicity p (∏ x in s, f x) = ∑ x in s, multiplicity p (f x) := begin classical, induction s using finset.induction with a s has ih h, { simp only [finset.sum_empty, finset.prod_empty], convert one_right hp.not_unit }, { simp [has, ← ih], convert multiplicity.mul hp } end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by simp [one_right hp.not_unit] | (k+1) := have multiplicity p (a ^ (k + 1)) = multiplicity p (a * a ^ k), by rw pow_succ, by rw [get_eq_get_of_eq _ _ this, multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = k • (multiplicity p a) | 0 := by simp [one_right hp.not_unit] | (succ k) := by simp [pow_succ, succ_nsmul, pow, multiplicity.mul hp] lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) : multiplicity p (p ^ n) = n := by { rw [eq_coe_iff], use dvd_rfl, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self } lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.not_unit n end comm_cancel_monoid_with_zero section valuation variables {R : Type*} [comm_ring R] [is_domain R] {p : R} [decidable_rel (has_dvd.dvd : R → R → Prop)] /-- `multiplicity` of a prime inan integral domain as an additive valuation to `enat`. -/ noncomputable def add_valuation (hp : prime p) : add_valuation R enat := add_valuation.of (multiplicity p) (multiplicity.zero _) (one_right hp.not_unit) (λ _ _, min_le_multiplicity_add) (λ a b, multiplicity.mul hp) @[simp] lemma add_valuation_apply {hp : prime p} {r : R} : add_valuation hp r = multiplicity p r := rfl end valuation end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← nonpos_iff_eq_zero, ← not_lt, enat.pos_iff_one_le, ← nat.cast_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, pow_one] at this, exact hp this end end nat
1609f1d7b1457ed4c592d2d128702adbe3162f2e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/unreachable_cases.lean
d76eca52f3425fbe4f3ecf1448225fb929658d47
[ "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
566
lean
open nat prod inductive ifin : ℕ → Type := -- inductively defined fin-type | fz : Π n, ifin (succ n) | fs : Π {n}, ifin n → ifin (succ n) open ifin definition foo {N : Type} : Π{n : ℕ}, N → ifin n → (N × ifin n) | (succ k) n (fz k) := sorry | (succ k) n (fs x) := sorry definition bar {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | ⌞succ k⌟ (n, fz k) := sorry | ⌞succ k⌟ (n, fs x) := sorry definition bar2 {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | (succ k) (n, fz k) := sorry | (succ k) (n, fs x) := sorry
3db6042c3458a872079f51d84407b13fd0258417
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/limits/shapes/binary_products.lean
3f6e89bff30118c79b6674bae7fc2328e5dd4c62
[ "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
27,622
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.terminal /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. We include lemmas for simplifying equations involving projections and coprojections, and define braiding and associating isomorphisms, and the product comparison morphism. -/ universes v u u₂ open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := {left, right}, complete := λ x, by { cases x; simp } } /-- The equivalence swapping left and right. -/ def walking_pair.swap : walking_pair ≃ walking_pair := { to_fun := λ j, walking_pair.rec_on j right left, inv_fun := λ j, walking_pair.rec_on j right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ j, by { cases j; refl, }, } @[simp] lemma walking_pair.swap_apply_left : walking_pair.swap left = right := rfl @[simp] lemma walking_pair.swap_apply_right : walking_pair.swap right = left := rfl @[simp] lemma walking_pair.swap_symm_apply_tt : walking_pair.swap.symm left = right := rfl @[simp] lemma walking_pair.swap_symm_apply_ff : walking_pair.swap.symm right = left := rfl /-- An equivalence from `walking_pair` to `bool`, sometimes useful when reindexing limits. -/ def walking_pair.equiv_bool : walking_pair ≃ bool := { to_fun := λ j, walking_pair.rec_on j tt ff, -- to match equiv.sum_equiv_sigma_bool inv_fun := λ b, bool.rec_on b right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ b, by { cases b; refl, }, } @[simp] lemma walking_pair.equiv_bool_apply_left : walking_pair.equiv_bool left = tt := rfl @[simp] lemma walking_pair.equiv_bool_apply_right : walking_pair.equiv_bool right = ff := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_tt : walking_pair.equiv_bool.symm tt = left := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_ff : walking_pair.equiv_bool.symm ff = right := rfl variables {C : Type u} [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := discrete.functor (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext ⟨⟩; { dsimp, simp, } end, inv_hom_id' := begin ext ⟨⟩; { dsimp, simp, } end } end section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.left /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.right lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.left /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.right lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ variables {X Y : C} /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- An abbreviation for `has_limit (pair X Y)`. -/ abbreviation has_binary_product (X Y : C) := has_limit (pair X Y) /-- An abbreviation for `has_colimit (pair X Y)`. -/ abbreviation has_binary_coproduct (X Y : C) := has_colimit (pair X Y) /-- If we have chosen a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_binary_product X Y] := limit (pair X Y) /-- If we have chosen a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_binary_coproduct X Y] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_binary_coproduct X Y] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_binary_coproduct X Y] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right @[ext] lemma prod.hom_ext {W X Y : C} [has_binary_product X Y] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_binary_coproduct X Y] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma prod.lift_comp_comp {V W X Y : C} [has_binary_product X Y] (f : V ⟶ W) (g : W ⟶ X) (h : W ⟶ Y) : prod.lift (f ≫ g) (f ≫ h) = f ≫ prod.lift g h := by tidy @[simp, reassoc] lemma coprod.inl_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ @[simp, reassoc] lemma coprod.inr_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma coprod.desc_comp_comp {V W X Y : C} [has_binary_coproduct X Y] (f : V ⟶ W) (g : X ⟶ V) (h : Y ⟶ V) : coprod.desc (g ≫ f) (h ≫ f) = coprod.desc g h ≫ f := by tidy instance prod.mono_lift_of_mono_left {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ abbreviation prod.map {W X Y Z : C} [has_limits_of_shape (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : X ≅ Z` induces a isomorphism `prod.map_iso f g : W ⨯ X ≅ Y ⨯ Z`. -/ abbreviation prod.map_iso {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : W ⨯ X ≅ Y ⨯ Z := lim.map_iso (map_pair_iso f g) -- Note that the next two `simp` lemmas are proved by `simp`, -- but nevertheless are useful, -- because they state the right hand side in terms of `prod.map` -- rather than `lim.map`. @[simp] lemma prod.map_iso_hom {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : (prod.map_iso f g).hom = prod.map f.hom g.hom := by simp @[simp] lemma prod.map_iso_inv {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : (prod.map_iso f g).inv = prod.map f.inv g.inv := by simp /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : W ≅ Z` induces a isomorphism `coprod.map_iso f g : W ⨿ X ≅ Y ⨿ Z`. -/ abbreviation coprod.map_iso {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : W ⨿ X ≅ Y ⨿ Z := colim.map_iso (map_pair_iso f g) @[simp] lemma coprod.map_iso_hom {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : (coprod.map_iso f g).hom = coprod.map f.hom g.hom := by simp @[simp] lemma coprod.map_iso_inv {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ≅ Y) (g : X ≅ Z) : (coprod.map_iso f g).inv = coprod.map f.inv g.inv := by simp section prod_lemmas variable [has_limits_of_shape (discrete walking_pair) C] @[reassoc] lemma prod.map_fst {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := by simp @[reassoc] lemma prod.map_snd {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := by simp @[simp] lemma prod_map_id_id {X Y : C} : prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma prod_lift_fst_snd {X Y : C} : prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma prod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f := by tidy @[reassoc] lemma prod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) := by tidy @[reassoc] lemma prod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g := by tidy @[reassoc] lemma prod.lift_map (V W X Y Z : C) (f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by tidy end prod_lemmas section coprod_lemmas variable [has_colimits_of_shape (discrete walking_pair) C] @[reassoc] lemma coprod.inl_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := by simp @[reassoc] lemma coprod.inr_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := by simp @[simp] lemma coprod_map_id_id {X Y : C} : coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma coprod_desc_inl_inr {X Y : C} : coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma coprod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f := by tidy @[reassoc] lemma coprod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) := by tidy @[reassoc] lemma coprod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g := by tidy @[reassoc] lemma coprod.map_desc {S T U V W : C} (f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) : coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) := by tidy end coprod_lemmas variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. -/ class has_binary_products := (has_limits_of_shape : has_limits_of_shape (discrete walking_pair) C) /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. -/ class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 200] -- see Note [lower instance priority] instance [has_finite_products C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 200] -- see Note [lower instance priority] instance [has_finite_coproducts C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } section variables {C} [has_binary_products C] variables {D : Type u₂} [category.{v} D] [has_binary_products D] -- FIXME deterministic timeout with `-T50000` /-- The binary product functor. -/ @[simps] def prod_functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f := by tidy @[simp, reassoc] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } /-- The product functor can be decomposed. -/ def prod_functor_left_comp (X Y : C) : prod_functor.obj (X ⨯ Y) ≅ prod_functor.obj Y ⋙ prod_functor.obj X := nat_iso.of_components (prod.associator _ _) (by tidy) @[reassoc] lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y ⨯ Z)).hom := by tidy @[reassoc] lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy /-- The product comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary products. -/ def prod_comparison (F : C ⥤ D) (A B : C) : F.obj (A ⨯ B) ⟶ F.obj A ⨯ F.obj B := prod.lift (F.map prod.fst) (F.map prod.snd) /-- Naturality of the prod_comparison morphism in both arguments. -/ @[reassoc] lemma prod_comparison_natural (F : C ⥤ D) {A A' B B' : C} (f : A ⟶ A') (g : B ⟶ B') : F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) := begin rw [prod_comparison, prod_comparison, prod.lift_map], apply prod.hom_ext, { simp only [← F.map_comp, category.assoc, prod.lift_fst, prod.map_fst, category.comp_id] }, { simp only [← F.map_comp, category.assoc, prod.lift_snd, prod.map_snd, prod.lift_snd_assoc] }, end @[reassoc] lemma inv_prod_comparison_map_fst (F : C ⥤ D) (A B : C) [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.fst = prod.fst := begin erw (as_iso (prod_comparison F A B)).inv_comp_eq, dsimp [as_iso_hom, prod_comparison], rw prod.lift_fst, end @[reassoc] lemma inv_prod_comparison_map_snd (F : C ⥤ D) (A B : C) [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.snd = prod.snd := begin erw (as_iso (prod_comparison F A B)).inv_comp_eq, dsimp [as_iso_hom, prod_comparison], rw prod.lift_snd, end /-- If the product comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma prod_comparison_inv_natural (F : C ⥤ D) {A A' B B' : C} (f : A ⟶ A') (g : B ⟶ B') [is_iso (prod_comparison F A B)] [is_iso (prod_comparison F A' B')] : inv (prod_comparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prod_comparison F A' B') := by { erw [(as_iso (prod_comparison F A' B')).eq_comp_inv, category.assoc, (as_iso (prod_comparison F A B)).inv_comp_eq, prod_comparison_natural], refl } variables [has_terminal C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } @[reassoc] lemma prod_left_unitor_hom_naturality (f : X ⟶ Y): prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f := prod.map_snd _ _ @[reassoc] lemma prod_left_unitor_inv_naturality (f : X ⟶ Y): (prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_left_unitor_hom_naturality] @[reassoc] lemma prod_right_unitor_hom_naturality (f : X ⟶ Y): prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f := prod.map_fst _ _ @[reassoc] lemma prod_right_unitor_inv_naturality (f : X ⟶ Y): (prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_right_unitor_hom_naturality] lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts C] /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X ⨿ Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W ⨿ X) Y Z).hom ≫ (coprod.associator W X (Y ⨿ Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
6784097734060e427afb9a210a640c61efd024db
cbb1957fc3e28e502582c54cbce826d666350eda
/fabstract/Cook_S_P_NP/fabstract.lean
a700a8aac19008bbda1b622b2bdaef0b0a4a0ef2
[ "CC-BY-4.0" ]
permissive
andrejbauer/formalabstracts
9040b172da080406448ad1b0260d550122dcad74
a3b84fd90901ccf4b63eb9f95d4286a8775864d0
refs/heads/master
1,609,476,417,918
1,501,541,742,000
1,501,541,760,000
97,241,872
1
0
null
1,500,042,191,000
1,500,042,191,000
null
UTF-8
Lean
false
false
2,616
lean
import meta_data .turing_machines namespace Cook_S_P_NP /- Definitions of the complexity classes P and NP -/ def NP_computable (f : list bool → list bool) : Prop := ∃ s n (TM : NTATM s n) (c k : nat), computes_fn_in_time TM (λ i : fin 1 → list bool, f (i 0)) (λ i, c * ((i 0).length^k + 1)) def P_computable (f : list bool → list bool) : Prop := ∃ s n (TM : TATM s n) (c k : nat), @computes_fn_in_time s n TM _ (λ i : fin 1 → list bool, f (i 0)) (λ i, c * ((i 0).length^k + 1)) -- NP: nondeterministic polynomial time computable problems def NP : set (set (list bool)) := { L | ∃ D : decidable_pred L, NP_computable (λ x, [@to_bool _ (D x)]) } -- P: deterministic polynomial time computable problems def P : set (set (list bool)) := { L | ∃ D : decidable_pred L, P_computable (λ x, [@to_bool _ (D x)]) } inductive prop | true : prop | false : prop | var : nat → prop | not : prop → prop | and : prop → prop → prop | or : prop → prop → prop def encode_nat (n : nat) : list bool := (do b ← n.bits, [tt, b]) ++ [ff] def encode_prop : prop → list bool | prop.true := encode_nat 0 | prop.false := encode_nat 1 | (prop.var i) := encode_nat 2 ++ encode_nat i | (prop.not a) := encode_nat 3 ++ encode_prop a | (prop.and a b) := encode_nat 4 ++ encode_prop a ++ encode_prop b | (prop.or a b) := encode_nat 5 ++ encode_prop a ++ encode_prop b def eval (v : nat → bool) : prop → bool | prop.true := tt | prop.false := ff | (prop.var i) := v i | (prop.not a) := bnot (eval a) | (prop.and a b) := eval a && eval b | (prop.or a b) := eval a || eval b /- Boolean satisfiability problem -/ def SAT : set (list bool) := { x | ∃ p v, encode_prop p = x ∧ eval v p = tt } /- SAT is in NP -/ unfinished SAT_NP : SAT ∈ NP := { description := "SAT is an NP-problem", references := [cite.Item cite.Ibidem "TODO"] } def P_reducible (L₁ L₂ : set (list bool)) : Prop := ∃ f, P_computable f ∧ L₁ = {x | f x ∈ L₂} /- Any problem in NP can be polynomial-time reduced to SAT -/ unfinished SAT_reducibility : ∀ L ∈ NP, P_reducible L SAT := { description := "Any problem in NP can be polynomial-time reduced to SAT", references := [cite.Item cite.Ibidem "TODO"] } def fabstract : meta_data := { description := "A conjecture that the complexity classes P and NP are unequal.", authors := [{name := "Stephen A. Cook"}], primary := cite.DOI "10.1145/800157.805047", secondary := [], results := [result.Proof SAT_NP, result.Proof SAT_reducibility, result.Conjecture (P ≠ NP)] } end Cook_S_P_NP
5c6e88e1b4b403cedc22253f6801257bd8dfe004
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/char_p/pi.lean
b87b8a93d4f30d47c17d07c5df282ba4fdbe8bc4
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
863
lean
/- Copyright (c) 2020 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 algebra.ring.pi /-! # Characteristic of semirings of functions -/ universes u v namespace char_p instance pi (ι : Type u) [hi : nonempty ι] (R : Type v) [semiring R] (p : ℕ) [char_p R p] : char_p (ι → R) p := ⟨λ x, let ⟨i⟩ := hi in iff.symm $ (char_p.cast_eq_zero_iff R p x).symm.trans ⟨λ h, funext $ λ j, show pi.eval_ring_hom (λ _, R) j (↑x : ι → R) = 0, by rw [ring_hom.map_nat_cast, h], λ h, (pi.eval_ring_hom (λ _, R) i).map_nat_cast x ▸ by rw [h, ring_hom.map_zero]⟩⟩ -- diamonds instance pi' (ι : Type u) [hi : nonempty ι] (R : Type v) [comm_ring R] (p : ℕ) [char_p R p] : char_p (ι → R) p := char_p.pi ι R p end char_p
100467afa7b680f96ff348e47096d4b2207367cb
842b7df4a999c5c50bbd215b8617dd705e43c2e1
/nat_num_game/src/Advanced_Proposition_World/adv_prop_wrld8.lean
625a04cee97de6a7054d23d01bc6cf138b4165ca
[]
no_license
Samyak-Surti/LeanCode
1c245631f74b00057d20483c8ac75916e8643b14
944eac3e5f43e2614ed246083b97fbdf24181d83
refs/heads/master
1,669,023,730,828
1,595,534,784,000
1,595,534,784,000
282,037,186
0
0
null
null
null
null
UTF-8
Lean
false
false
594
lean
lemma and_or_distrib_left (P Q R : Prop) : P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin split, intro fpqr, cases fpqr with p qr, cases qr with q r, have pq : P ∧ Q, split, exact p, exact q, left, exact pq, have pr : P ∧ R, split, exact p, exact r, right, exact pr, intro fpqpr, split, cases fpqpr with pq pr, cases pq with p q, exact p, cases pr with p r, exact p, cases fpqpr with pq pr, cases pq with p q, left, exact q, cases pr with p r, right, exact r, end
e716c94f966aa97158771e72cc8240f67e69f34e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/presheafed_space.lean
cc379a666307c5d22bb0b1c078888a30217f3359
[ "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,747
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf import category_theory.adjunction.fully_faithful /-! # Presheafed spaces Introduces the category of topological spaces equipped with a presheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ universes w v u open category_theory open Top open topological_space open opposite open category_theory.category category_theory.functor variables (C : Type u) [category.{v} C] local attribute [tidy] tactic.op_induction' namespace algebraic_geometry /-- A `PresheafedSpace C` is a topological space equipped with a presheaf of `C`s. -/ structure PresheafedSpace := (carrier : Top.{w}) (presheaf : carrier.presheaf C) variables {C} namespace PresheafedSpace attribute [protected] presheaf instance coe_carrier : has_coe (PresheafedSpace.{w v u} C) Top.{w} := { coe := λ X, X.carrier } @[simp] lemma as_coe (X : PresheafedSpace.{w v u} C) : X.carrier = (X : Top.{w}) := rfl @[simp] lemma mk_coe (carrier) (presheaf) : (({ carrier := carrier, presheaf := presheaf } : PresheafedSpace.{v} C) : Top.{v}) = carrier := rfl instance (X : PresheafedSpace.{v} C) : topological_space X := X.carrier.str /-- The constant presheaf on `X` with value `Z`. -/ def const (X : Top) (Z : C) : PresheafedSpace C := { carrier := X, presheaf := { obj := λ U, Z, map := λ U V f, 𝟙 Z, } } instance [inhabited C] : inhabited (PresheafedSpace C) := ⟨const (Top.of pempty) default⟩ /-- A morphism between presheafed spaces `X` and `Y` consists of a continuous map `f` between the underlying topological spaces, and a (notice contravariant!) map from the presheaf on `Y` to the pushforward of the presheaf on `X` via `f`. -/ structure hom (X Y : PresheafedSpace.{w v u} C) := (base : (X : Top.{w}) ⟶ (Y : Top.{w})) (c : Y.presheaf ⟶ base _* X.presheaf) @[ext] lemma ext {X Y : PresheafedSpace C} (α β : hom X Y) (w : α.base = β.base) (h : α.c ≫ (whisker_right (eq_to_hom (by rw w)) _) = β.c) : α = β := begin cases α, cases β, dsimp [presheaf.pushforward_obj] at *, tidy, -- TODO including `injections` would make tidy work earlier. end lemma hext {X Y : PresheafedSpace C} (α β : hom X Y) (w : α.base = β.base) (h : α.c == β.c) : α = β := by { cases α, cases β, congr, exacts [w,h] } . /-- The identity morphism of a `PresheafedSpace`. -/ def id (X : PresheafedSpace.{w v u} C) : hom X X := { base := 𝟙 (X : Top.{w}), c := eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm } instance hom_inhabited (X : PresheafedSpace C) : inhabited (hom X X) := ⟨id X⟩ /-- Composition of morphisms of `PresheafedSpace`s. -/ def comp {X Y Z : PresheafedSpace C} (α : hom X Y) (β : hom Y Z) : hom X Z := { base := α.base ≫ β.base, c := β.c ≫ (presheaf.pushforward _ β.base).map α.c } lemma comp_c {X Y Z : PresheafedSpace C} (α : hom X Y) (β : hom Y Z) : (comp α β).c = β.c ≫ (presheaf.pushforward _ β.base).map α.c := rfl variables (C) section local attribute [simp] id comp /- The proofs below can be done by `tidy`, but it is too slow, and we don't have a tactic caching mechanism. -/ /-- The category of PresheafedSpaces. Morphisms are pairs, a continuous map and a presheaf map from the presheaf on the target to the pushforward of the presheaf on the source. -/ instance category_of_PresheafedSpaces : category (PresheafedSpace.{v v u} C) := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, id_comp' := λ X Y f, begin ext1, { rw comp_c, erw eq_to_hom_map, simp only [eq_to_hom_refl, assoc, whisker_right_id'], erw [comp_id, comp_id] }, apply id_comp end, comp_id' := λ X Y f, begin ext1, { rw comp_c, erw congr_hom (presheaf.id_pushforward _) f.c, simp only [comp_id, functor.id_map, eq_to_hom_refl, assoc, whisker_right_id'], erw eq_to_hom_trans_assoc, simp only [id_comp, eq_to_hom_refl], erw comp_id }, apply comp_id end, assoc' := λ W X Y Z f g h, begin ext1, repeat {rw comp_c}, simp only [eq_to_hom_refl, assoc, functor.map_comp, whisker_right_id'], erw comp_id, congr, refl end } end variables {C} local attribute [simp] eq_to_hom_map @[simp] lemma id_base (X : PresheafedSpace.{v v u} C) : ((𝟙 X) : X ⟶ X).base = 𝟙 (X : Top.{v}) := rfl lemma id_c (X : PresheafedSpace.{v v u} C) : ((𝟙 X) : X ⟶ X).c = eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm := rfl @[simp] lemma id_c_app (X : PresheafedSpace.{v v u} C) (U) : ((𝟙 X) : X ⟶ X).c.app U = X.presheaf.map (eq_to_hom (by { induction U using opposite.rec, cases U, refl })) := by { induction U using opposite.rec, cases U, simp only [id_c], dsimp, simp, } @[simp] lemma comp_base {X Y Z : PresheafedSpace.{v v u} C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).base = f.base ≫ g.base := rfl instance (X Y : PresheafedSpace.{v v u} C) : has_coe_to_fun (X ⟶ Y) (λ _, X → Y) := ⟨λ f, f.base⟩ lemma coe_to_fun_eq {X Y : PresheafedSpace.{v v u} C} (f : X ⟶ Y) : (f : X → Y) = f.base := rfl -- The `reassoc` attribute was added despite the LHS not being a composition of two homs, -- for the reasons explained in the docstring. /-- Sometimes rewriting with `comp_c_app` doesn't work because of dependent type issues. In that case, `erw comp_c_app_assoc` might make progress. The lemma `comp_c_app_assoc` is also better suited for rewrites in the opposite direction. -/ @[reassoc, simp] lemma comp_c_app {X Y Z : PresheafedSpace.{v v u} C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) : (α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.base)).obj (unop U))) := rfl lemma congr_app {X Y : PresheafedSpace.{v v u} C} {α β : X ⟶ Y} (h : α = β) (U) : α.c.app U = β.c.app U ≫ X.presheaf.map (eq_to_hom (by subst h)) := by { subst h, dsimp, simp, } section variables (C) /-- The forgetful functor from `PresheafedSpace` to `Top`. -/ @[simps] def forget : PresheafedSpace.{v v u} C ⥤ Top := { obj := λ X, (X : Top.{v}), map := λ X Y f, f.base } end section iso variables {X Y : PresheafedSpace.{v v u} C} /-- An isomorphism of PresheafedSpaces is a homeomorphism of the underlying space, and a natural transformation between the sheaves. -/ @[simps hom inv] def iso_of_components (H : X.1 ≅ Y.1) (α : H.hom _* X.2 ≅ Y.2) : X ≅ Y := { hom := { base := H.hom, c := α.inv }, inv := { base := H.inv, c := presheaf.to_pushforward_of_iso H α.hom }, hom_inv_id' := by { ext, { simp, erw category.id_comp, simpa }, simp }, inv_hom_id' := begin ext x, induction x using opposite.rec, simp only [comp_c_app, whisker_right_app, presheaf.to_pushforward_of_iso_app, nat_trans.comp_app, eq_to_hom_app, id_c_app, category.assoc], erw [← α.hom.naturality], have := nat_trans.congr_app (α.inv_hom_id) (op x), cases x, rw nat_trans.comp_app at this, convert this, { dsimp, simp }, { simp }, { simp } end } /-- Isomorphic PresheafedSpaces have natural isomorphic presheaves. -/ @[simps] def sheaf_iso_of_iso (H : X ≅ Y) : Y.2 ≅ H.hom.base _* X.2 := { hom := H.hom.c, inv := presheaf.pushforward_to_of_iso ((forget _).map_iso H).symm H.inv.c, hom_inv_id' := begin ext U, have := congr_app H.inv_hom_id U, simp only [comp_c_app, id_c_app, eq_to_hom_map, eq_to_hom_trans] at this, generalize_proofs h at this, simpa using congr_arg (λ f, f ≫ eq_to_hom h.symm) this, end, inv_hom_id' := begin ext U, simp only [presheaf.pushforward_to_of_iso_app, nat_trans.comp_app, category.assoc, nat_trans.id_app, H.hom.c.naturality], have := congr_app H.hom_inv_id ((opens.map H.hom.base).op.obj U), generalize_proofs h at this, simpa using congr_arg (λ f, f ≫ X.presheaf.map (eq_to_hom h.symm)) this end } instance base_is_iso_of_iso (f : X ⟶ Y) [is_iso f] : is_iso f.base := is_iso.of_iso ((forget _).map_iso (as_iso f)) instance c_is_iso_of_iso (f : X ⟶ Y) [is_iso f] : is_iso f.c := is_iso.of_iso (sheaf_iso_of_iso (as_iso f)) /-- This could be used in conjunction with `category_theory.nat_iso.is_iso_of_is_iso_app`. -/ lemma is_iso_of_components (f : X ⟶ Y) [is_iso f.base] [is_iso f.c] : is_iso f := begin convert is_iso.of_iso (iso_of_components (as_iso f.base) (as_iso f.c).symm), ext, { simpa }, { simp }, end end iso section restrict /-- The restriction of a presheafed space along an open embedding into the space. -/ @[simps] def restrict {U : Top} (X : PresheafedSpace.{v v u} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) : PresheafedSpace C := { carrier := U, presheaf := h.is_open_map.functor.op ⋙ X.presheaf } /-- The map from the restriction of a presheafed space. -/ @[simps] def of_restrict {U : Top} (X : PresheafedSpace.{v v u} C) {f : U ⟶ (X : Top.{v})} (h : open_embedding f) : X.restrict h ⟶ X := { base := f, c := { app := λ V, X.presheaf.map (h.is_open_map.adjunction.counit.app V.unop).op, naturality' := λ U V f, show _ = _ ≫ X.presheaf.map _, by { rw [← map_comp, ← map_comp], refl } } } instance of_restrict_mono {U : Top} (X : PresheafedSpace C) (f : U ⟶ X.1) (hf : open_embedding f) : mono (X.of_restrict hf) := begin haveI : mono f := (Top.mono_iff_injective _).mpr hf.inj, constructor, intros Z g₁ g₂ eq, ext V, { induction V using opposite.rec, have hV : (opens.map (X.of_restrict hf).base).obj (hf.is_open_map.functor.obj V) = V, { cases V, simp[opens.map, set.preimage_image_eq _ hf.inj] }, haveI : is_iso (hf.is_open_map.adjunction.counit.app (unop (op (hf.is_open_map.functor.obj V)))) := (nat_iso.is_iso_app_of_is_iso (whisker_left hf.is_open_map.functor hf.is_open_map.adjunction.counit) V : _), have := PresheafedSpace.congr_app eq (op (hf.is_open_map.functor.obj V)), simp only [PresheafedSpace.comp_c_app, PresheafedSpace.of_restrict_c_app, category.assoc, cancel_epi] at this, have h : _ ≫ _ = _ ≫ _ ≫ _ := congr_arg (λ f, (X.restrict hf).presheaf.map (eq_to_hom hV).op ≫ f) this, erw [g₁.c.naturality, g₂.c.naturality_assoc] at h, simp only [presheaf.pushforward_obj_map, eq_to_hom_op, category.assoc, eq_to_hom_map, eq_to_hom_trans] at h, rw ←is_iso.comp_inv_eq at h, simpa using h }, { have := congr_arg PresheafedSpace.hom.base eq, simp only [PresheafedSpace.comp_base, PresheafedSpace.of_restrict_base] at this, rw cancel_mono at this, exact this } end lemma restrict_top_presheaf (X : PresheafedSpace C) : (X.restrict (opens.open_embedding ⊤)).presheaf = (opens.inclusion_top_iso X.carrier).inv _* X.presheaf := by { dsimp, rw opens.inclusion_top_functor X.carrier, refl } lemma of_restrict_top_c (X : PresheafedSpace C) : (X.of_restrict (opens.open_embedding ⊤)).c = eq_to_hom (by { rw [restrict_top_presheaf, ←presheaf.pushforward.comp_eq], erw iso.inv_hom_id, rw presheaf.pushforward.id_eq }) := /- another approach would be to prove the left hand side is a natural isoomorphism, but I encountered a universe issue when `apply nat_iso.is_iso_of_is_iso_app`. -/ begin ext U, change X.presheaf.map _ = _, convert eq_to_hom_map _ _ using 1, congr, simpa, { induction U using opposite.rec, dsimp, congr, ext, exact ⟨ λ h, ⟨⟨x,trivial⟩,h,rfl⟩, λ ⟨⟨_,_⟩,h,rfl⟩, h ⟩ }, /- or `rw [opens.inclusion_top_functor, ←comp_obj, ←opens.map_comp_eq], erw iso.inv_hom_id, cases U, refl` after `dsimp` -/ end /-- The map to the restriction of a presheafed space along the canonical inclusion from the top subspace. -/ @[simps] def to_restrict_top (X : PresheafedSpace C) : X ⟶ X.restrict (opens.open_embedding ⊤) := { base := (opens.inclusion_top_iso X.carrier).inv, c := eq_to_hom (restrict_top_presheaf X) } /-- The isomorphism from the restriction to the top subspace. -/ @[simps] def restrict_top_iso (X : PresheafedSpace C) : X.restrict (opens.open_embedding ⊤) ≅ X := { hom := X.of_restrict _, inv := X.to_restrict_top, hom_inv_id' := ext _ _ (concrete_category.hom_ext _ _ $ λ ⟨x, _⟩, rfl) $ by { erw comp_c, rw X.of_restrict_top_c, ext, simp }, inv_hom_id' := ext _ _ rfl $ by { erw comp_c, rw X.of_restrict_top_c, ext, simpa [-eq_to_hom_refl] } } end restrict /-- The global sections, notated Gamma. -/ @[simps] def Γ : (PresheafedSpace.{v v u} C)ᵒᵖ ⥤ C := { obj := λ X, (unop X).presheaf.obj (op ⊤), map := λ X Y f, f.unop.c.app (op ⊤) } lemma Γ_obj_op (X : PresheafedSpace C) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl lemma Γ_map_op {X Y : PresheafedSpace.{v v u} C} (f : X ⟶ Y) : Γ.map f.op = f.c.app (op ⊤) := rfl end PresheafedSpace end algebraic_geometry open algebraic_geometry algebraic_geometry.PresheafedSpace variables {C} namespace category_theory variables {D : Type u} [category.{v} D] local attribute [simp] presheaf.pushforward_obj namespace functor /-- We can apply a functor `F : C ⥤ D` to the values of the presheaf in any `PresheafedSpace C`, giving a functor `PresheafedSpace C ⥤ PresheafedSpace D` -/ def map_presheaf (F : C ⥤ D) : PresheafedSpace.{v v u} C ⥤ PresheafedSpace.{v v u} D := { obj := λ X, { carrier := X.carrier, presheaf := X.presheaf ⋙ F }, map := λ X Y f, { base := f.base, c := whisker_right f.c F }, } @[simp] lemma map_presheaf_obj_X (F : C ⥤ D) (X : PresheafedSpace C) : ((F.map_presheaf.obj X) : Top.{v}) = (X : Top.{v}) := rfl @[simp] lemma map_presheaf_obj_presheaf (F : C ⥤ D) (X : PresheafedSpace C) : (F.map_presheaf.obj X).presheaf = X.presheaf ⋙ F := rfl @[simp] lemma map_presheaf_map_f (F : C ⥤ D) {X Y : PresheafedSpace.{v v u} C} (f : X ⟶ Y) : (F.map_presheaf.map f).base = f.base := rfl @[simp] lemma map_presheaf_map_c (F : C ⥤ D) {X Y : PresheafedSpace.{v v u} C} (f : X ⟶ Y) : (F.map_presheaf.map f).c = whisker_right f.c F := rfl end functor namespace nat_trans /-- A natural transformation induces a natural transformation between the `map_presheaf` functors. -/ def on_presheaf {F G : C ⥤ D} (α : F ⟶ G) : G.map_presheaf ⟶ F.map_presheaf := { app := λ X, { base := 𝟙 _, c := whisker_left X.presheaf α ≫ eq_to_hom (presheaf.pushforward.id_eq _).symm } } -- TODO Assemble the last two constructions into a functor -- `(C ⥤ D) ⥤ (PresheafedSpace C ⥤ PresheafedSpace D)` end nat_trans end category_theory
ff1a04ef3f22289ed3831831398fd075552de64f
18425d4bab0b5e4677ef791d0065e16639493248
/equipotent.lean
3481fba47fa4b23f1d9f6dab1b122b8b1903283c
[ "MIT" ]
permissive
tizmd/lean-finitary
5feb94a2474b55c0f23e4b61b9ac42403bf222f7
8958fdb3fa3d9fcc304e116fd339448875025e95
refs/heads/master
1,611,397,193,043
1,497,517,825,000
1,497,517,825,000
93,048,842
0
0
null
null
null
null
UTF-8
Lean
false
false
3,308
lean
import function.bijection import data.fin.misc universes u v open function class equipotent (α : Sort u) (β : Sort v) := (map : α → β) (bijection : bijection map) namespace equipotent variables {α : Sort u} {β : Sort v} @[refl] instance rfl : equipotent α α := { map := id, bijection := bijection.of_id } @[symm] instance symm (eqv : equipotent α β) : equipotent β α := { map := eqv.bijection.inv, bijection := eqv.bijection.inverse } instance equipotent_of_inhabited_subsingletons [inhabited α][subsingleton α ][inhabited β][subsingleton β] : equipotent α β := { map := λ a, default β, bijection := { inv := λ b, default α, left_inverse_of_inv := λ a, subsingleton.elim _ a, right_inverse_of_inv := λ b, subsingleton.elim _ b, } } universe w variable {γ : Sort w} @[trans] instance trans (eqv₁ : equipotent α β) (eqv₂ : equipotent β γ) : equipotent α γ := { map := eqv₂.map ∘ eqv₁.map, bijection := bijection.comp eqv₁.bijection eqv₂.bijection } end equipotent def is_equipotent (α : Sort u) (β : Sort v) := ∃ f : α → β, has_bijection f namespace is_equipotent variables {α : Sort u}{β : Sort v} @[refl] def rfl : is_equipotent α α := exists.intro id (exists.intro id (and.intro (take x, rfl) (take x, rfl))) @[symm] def symm : is_equipotent α β → is_equipotent β α := assume Heqv, exists.elim Heqv (λ f ex, exists.elim ex (λ g h, exists.intro g (exists.intro f (and.intro h.right h.left)))) universe w variable {γ : Sort w} @[trans] def trans : is_equipotent α β → is_equipotent β γ → is_equipotent α γ := begin intros Hab Hbc, cases Hab with f f_has_bijection, cases Hbc with g g_has_bijection, apply exists.intro, apply has_bijection.trans, exact f_has_bijection, exact g_has_bijection end def is_equipotent_iff_iff {α : Prop} {β : Prop} : (α ↔ β) ↔ is_equipotent α β := begin apply iff.intro, { intro H, apply (exists.intro (iff.elim_left H)), apply (exists.intro (iff.elim_right H)), apply and.intro, intro p, apply proof_irrel, intro p, apply proof_irrel }, { intro H, cases H with p ex, cases ex with q h, apply iff.intro, assumption, assumption } end end is_equipotent def is_finitary (α : Sort u) n := is_equipotent α (fin n) namespace is_finitary lemma eq_size_of_fin {m n} : is_finitary (fin m) n → m = n := assume ⟨f, Hhas_bijection⟩, if Heq : m = n then Heq else if Hlt : m < n then exists.elim Hhas_bijection (take g, assume Hg, have Hinj : injective g, from injective_of_left_inverse Hg.right, absurd Hinj (fin.not_injective_of_gt g Hlt) ) else have Hinj : injective f, from has_bijection.injective_of_has_bijection Hhas_bijection, have m > n, from lt_of_le_of_ne (le_of_not_gt Hlt) (ne.symm Heq), absurd Hinj (fin.not_injective_of_gt f this) theorem eq_of_size {m n}{α : Sort u} : is_finitary α m → is_finitary α n → m = n := assume Hm Hn, have is_finitary (fin m) n, from is_equipotent.trans (is_equipotent.symm Hm) Hn, eq_size_of_fin this end is_finitary
46187620d3a8ff4a076bf7bd3437c3f6771e9205
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_topology/fundamental_groupoid/induced_maps.lean
1536082abcf65ac0e9d4769c42a9df5a0500c3dc
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,816
lean
/- Copyright (c) 2022 Praneeth Kolichala. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Praneeth Kolichala -/ import topology.homotopy.equiv import category_theory.equivalence import algebraic_topology.fundamental_groupoid.product /-! # Homotopic maps induce naturally isomorphic functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions - `fundamental_groupoid_functor.homotopic_maps_nat_iso H` The natural isomorphism between the induced functors `f : π(X) ⥤ π(Y)` and `g : π(X) ⥤ π(Y)`, given a homotopy `H : f ∼ g` - `fundamental_groupoid_functor.equiv_of_homotopy_equiv hequiv` The equivalence of the categories `π(X)` and `π(Y)` given a homotopy equivalence `hequiv : X ≃ₕ Y` between them. ## Implementation notes - In order to be more universe polymorphic, we define `continuous_map.homotopy.ulift_map` which lifts a homotopy from `I × X → Y` to `(Top.of ((ulift I) × X)) → Y`. This is because this construction uses `fundamental_groupoid_functor.prod_to_prod_Top` to convert between pairs of paths in I and X and the corresponding path after passing through a homotopy `H`. But `fundamental_groupoid_functor.prod_to_prod_Top` requires two spaces in the same universe. -/ noncomputable theory universe u open fundamental_groupoid open category_theory open fundamental_groupoid_functor open_locale fundamental_groupoid open_locale unit_interval namespace unit_interval /-- The path 0 ⟶ 1 in I -/ def path01 : path (0 : I) 1 := { to_fun := id, source' := rfl, target' := rfl } /-- The path 0 ⟶ 1 in ulift I -/ def upath01 : path (ulift.up 0 : ulift.{u} I) (ulift.up 1) := { to_fun := ulift.up, source' := rfl, target' := rfl } local attribute [instance] path.homotopic.setoid /-- The homotopy path class of 0 → 1 in `ulift I` -/ def uhpath01 : @from_top (Top.of $ ulift.{u} I) (ulift.up (0 : I)) ⟶ from_top (ulift.up 1) := ⟦upath01⟧ end unit_interval namespace continuous_map.homotopy open unit_interval (uhpath01) local attribute [instance] path.homotopic.setoid section casts /-- Abbreviation for `eq_to_hom` that accepts points in a topological space -/ abbreviation hcast {X : Top} {x₀ x₁ : X} (hx : x₀ = x₁) : from_top x₀ ⟶ from_top x₁ := eq_to_hom hx @[simp] lemma hcast_def {X : Top} {x₀ x₁ : X} (hx₀ : x₀ = x₁) : hcast hx₀ = eq_to_hom hx₀ := rfl variables {X₁ X₂ Y : Top.{u}} {f : C(X₁, Y)} {g : C(X₂, Y)} {x₀ x₁ : X₁} {x₂ x₃ : X₂} {p : path x₀ x₁} {q : path x₂ x₃} (hfg : ∀ t, f (p t) = g (q t)) include hfg /-- If `f(p(t) = g(q(t))` for two paths `p` and `q`, then the induced path homotopy classes `f(p)` and `g(p)` are the same as well, despite having a priori different types -/ lemma heq_path_of_eq_image : (πₘ f).map ⟦p⟧ == (πₘ g).map ⟦q⟧ := by { simp only [map_eq, ← path.homotopic.map_lift], apply path.homotopic.hpath_hext, exact hfg, } private lemma start_path : f x₀ = g x₂ := by { convert hfg 0; simp only [path.source], } private lemma end_path : f x₁ = g x₃ := by { convert hfg 1; simp only [path.target], } lemma eq_path_of_eq_image : (πₘ f).map ⟦p⟧ = hcast (start_path hfg) ≫ (πₘ g).map ⟦q⟧ ≫ hcast (end_path hfg).symm := by { rw functor.conj_eq_to_hom_iff_heq, exact heq_path_of_eq_image hfg } end casts /- We let `X` and `Y` be spaces, and `f` and `g` be homotopic maps between them -/ variables {X Y : Top.{u}} {f g : C(X, Y)} (H : continuous_map.homotopy f g) {x₀ x₁ : X} (p : from_top x₀ ⟶ from_top x₁) /-! These definitions set up the following diagram, for each path `p`: f(p) *--------* | \ | H₀ | \ d | H₁ | \ | *--------* g(p) Here, `H₀ = H.eval_at x₀` is the path from `f(x₀)` to `g(x₀)`, and similarly for `H₁`. Similarly, `f(p)` denotes the path in Y that the induced map `f` takes `p`, and similarly for `g(p)`. Finally, `d`, the diagonal path, is H(0 ⟶ 1, p), the result of the induced `H` on `path.homotopic.prod (0 ⟶ 1) p`, where `(0 ⟶ 1)` denotes the path from `0` to `1` in `I`. It is clear that the diagram commutes (`H₀ ≫ g(p) = d = f(p) ≫ H₁`), but unfortunately, many of the paths do not have defeq starting/ending points, so we end up needing some casting. -/ /-- Interpret a homotopy `H : C(I × X, Y) as a map C(ulift I × X, Y) -/ def ulift_map : C(Top.of (ulift.{u} I × X), Y) := ⟨λ x, H (x.1.down, x.2), H.continuous.comp ((continuous_induced_dom.comp continuous_fst).prod_mk continuous_snd)⟩ @[simp] lemma ulift_apply (i : ulift.{u} I) (x : X) : H.ulift_map (i, x) = H (i.down, x) := rfl /-- An abbreviation for `prod_to_prod_Top`, with some types already in place to help the typechecker. In particular, the first path should be on the ulifted unit interval. -/ abbreviation prod_to_prod_Top_I {a₁ a₂ : Top.of (ulift I)} {b₁ b₂ : X} (p₁ : from_top a₁ ⟶ from_top a₂) (p₂ : from_top b₁ ⟶ from_top b₂) := @category_theory.functor.map _ _ _ _ (prod_to_prod_Top (Top.of $ ulift I) X) (a₁, b₁) (a₂, b₂) (p₁, p₂) /-- The diagonal path `d` of a homotopy `H` on a path `p` -/ def diagonal_path : from_top (H (0, x₀)) ⟶ from_top (H (1, x₁)) := (πₘ H.ulift_map).map (prod_to_prod_Top_I uhpath01 p) /-- The diagonal path, but starting from `f x₀` and going to `g x₁` -/ def diagonal_path' : from_top (f x₀) ⟶ from_top (g x₁) := hcast (H.apply_zero x₀).symm ≫ (H.diagonal_path p) ≫ hcast (H.apply_one x₁) /-- Proof that `f(p) = H(0 ⟶ 0, p)`, with the appropriate casts -/ lemma apply_zero_path : (πₘ f).map p = hcast (H.apply_zero x₀).symm ≫ (πₘ H.ulift_map).map (prod_to_prod_Top_I (𝟙 (ulift.up 0)) p) ≫ hcast (H.apply_zero x₁) := begin apply quotient.induction_on p, intro p', apply @eq_path_of_eq_image _ _ _ _ H.ulift_map _ _ _ _ _ ((path.refl (ulift.up _)).prod p'), simp, end /-- Proof that `g(p) = H(1 ⟶ 1, p)`, with the appropriate casts -/ lemma apply_one_path : (πₘ g).map p = hcast (H.apply_one x₀).symm ≫ ((πₘ H.ulift_map).map (prod_to_prod_Top_I (𝟙 (ulift.up 1)) p)) ≫ hcast (H.apply_one x₁) := begin apply quotient.induction_on p, intro p', apply @eq_path_of_eq_image _ _ _ _ H.ulift_map _ _ _ _ _ ((path.refl (ulift.up _)).prod p'), simp, end /-- Proof that `H.eval_at x = H(0 ⟶ 1, x ⟶ x)`, with the appropriate casts -/ lemma eval_at_eq (x : X) : ⟦H.eval_at x⟧ = hcast (H.apply_zero x).symm ≫ (πₘ H.ulift_map).map (prod_to_prod_Top_I uhpath01 (𝟙 x)) ≫ hcast (H.apply_one x).symm.symm := begin dunfold prod_to_prod_Top_I uhpath01 hcast, refine (@functor.conj_eq_to_hom_iff_heq (πₓ Y) _ _ _ _ _ _ _ _ _).mpr _, simp only [id_eq_path_refl, prod_to_prod_Top_map, path.homotopic.prod_lift, map_eq, ← path.homotopic.map_lift], apply path.homotopic.hpath_hext, intro, refl, end /- Finally, we show `d = f(p) ≫ H₁ = H₀ ≫ g(p)` -/ lemma eq_diag_path : (πₘ f).map p ≫ ⟦H.eval_at x₁⟧ = H.diagonal_path' p ∧ (⟦H.eval_at x₀⟧ ≫ (πₘ g).map p : from_top (f x₀) ⟶ from_top (g x₁)) = H.diagonal_path' p := begin rw [H.apply_zero_path, H.apply_one_path, H.eval_at_eq, H.eval_at_eq], dunfold prod_to_prod_Top_I, split; { slice_lhs 2 5 { simp [← category_theory.functor.map_comp], }, refl, }, end end continuous_map.homotopy namespace fundamental_groupoid_functor open category_theory open_locale fundamental_groupoid local attribute [instance] path.homotopic.setoid variables {X Y : Top.{u}} {f g : C(X, Y)} (H : continuous_map.homotopy f g) /-- Given a homotopy H : f ∼ g, we have an associated natural isomorphism between the induced functors `f` and `g` -/ def homotopic_maps_nat_iso : πₘ f ⟶ πₘ g := { app := λ x, ⟦H.eval_at x⟧, naturality' := λ x y p, by rw [(H.eq_diag_path p).1, (H.eq_diag_path p).2] } instance : is_iso (homotopic_maps_nat_iso H) := by apply nat_iso.is_iso_of_is_iso_app open_locale continuous_map /-- Homotopy equivalent topological spaces have equivalent fundamental groupoids. -/ def equiv_of_homotopy_equiv (hequiv : X ≃ₕ Y) : πₓ X ≌ πₓ Y := begin apply equivalence.mk (πₘ hequiv.to_fun : πₓ X ⥤ πₓ Y) (πₘ hequiv.inv_fun : πₓ Y ⥤ πₓ X); simp only [Groupoid.hom_to_functor, Groupoid.id_to_functor], { convert (as_iso (homotopic_maps_nat_iso hequiv.left_inv.some)).symm, exacts [((π).map_id X).symm, ((π).map_comp _ _).symm] }, { convert as_iso (homotopic_maps_nat_iso hequiv.right_inv.some), exacts [((π).map_comp _ _).symm, ((π).map_id Y).symm] }, end end fundamental_groupoid_functor
505f551f52cdb6d932601e17c15e87225713e0ee
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/MetavarContext.lean
2f7ecc85c02704040eec4c7800de60a1e36c64b9
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
54,606
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.Util.MonadCache import Lean.LocalContext namespace Lean /- The metavariable context stores metavariable declarations and their assignments. It is used in the elaborator, tactic framework, unifier (aka `isDefEq`), and type class resolution (TC). First, we list all the requirements imposed by these modules. - We may invoke TC while executing `isDefEq`. We need this feature to be able to solve unification problems such as: ``` f ?a (ringAdd ?s) ?x ?y =?= f Int intAdd n m ``` where `(?a : Type) (?s : Ring ?a) (?x ?y : ?a)` During `isDefEq` (i.e., unification), it will need to solve the constrain ``` ringAdd ?s =?= intAdd ``` We say `ringAdd ?s` is stuck because it cannot be reduced until we synthesize the term `?s : Ring ?a` using TC. This can be done since we have assigned `?a := Int` when solving `?a =?= Int`. - TC uses `isDefEq`, and `isDefEq` may create TC problems as shown above. Thus, we may have nested TC problems. - `isDefEq` extends the local context when going inside binders. Thus, the local context for nested TC may be an extension of the local context for outer TC. - TC should not assign metavariables created by the elaborator, simp, tactic framework, and outer TC problems. Reason: TC commits to the first solution it finds. Consider the TC problem `Coe Nat ?x`, where `?x` is a metavariable created by the caller. There are many solutions to this problem (e.g., `?x := Int`, `?x := Real`, ...), and it doesn’t make sense to commit to the first one since TC does not know the constraints the caller may impose on `?x` after the TC problem is solved. Remark: we claim it is not feasible to make the whole system backtrackable, and allow the caller to backtrack back to TC and ask it for another solution if the first one found did not work. We claim it would be too inefficient. - TC metavariables should not leak outside of TC. Reason: we want to get rid of them after we synthesize the instance. - `simp` invokes `isDefEq` for matching the left-hand-side of equations to terms in our goal. Thus, it may invoke TC indirectly. - In Lean3, we didn’t have to create a fresh pattern for trying to match the left-hand-side of equations when executing `simp`. We had a mechanism called "tmp" metavariables. It avoided this overhead, but it created many problems since `simp` may indirectly call TC which may recursively call TC. Moreover, we may want to allow TC to invoke tactics in the future. Thus, when `simp` invokes `isDefEq`, it may indirectly invoke a tactic and `simp` itself. The Lean3 approach assumed that metavariables were short-lived, this is not true in Lean4, and to some extent was also not true in Lean3 since `simp`, in principle, could trigger an arbitrary number of nested TC problems. - Here are some possible call stack traces we could have in Lean3 (and Lean4). ``` Elaborator (-> TC -> isDefEq)+ Elaborator -> isDefEq (-> TC -> isDefEq)* Elaborator -> simp -> isDefEq (-> TC -> isDefEq)* ``` In Lean4, TC may also invoke tactics in the future. - In Lean3 and Lean4, TC metavariables are not really short-lived. We solve an arbitrary number of unification problems, and we may have nested TC invocations. - TC metavariables do not share the same local context even in the same invocation. In the C++ and Lean implementations we use a trick to ensure they do: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L3583-L3594 - Metavariables may be natural, synthetic or syntheticOpaque. a) Natural metavariables may be assigned by unification (i.e., `isDefEq`). b) Synthetic metavariables may still be assigned by unification, but whenever possible `isDefEq` will avoid the assignment. For example, if we have the unification constaint `?m =?= ?n`, where `?m` is synthetic, but `?n` is not, `isDefEq` solves it by using the assignment `?n := ?m`. We use synthetic metavariables for type class resolution. Any module that creates synthetic metavariables, must also check whether they have been assigned by `isDefEq`, and then still synthesize them, and check whether the sythesized result is compatible with the one assigned by `isDefEq`. c) SyntheticOpaque metavariables are never assigned by `isDefEq`. That is, the constraint `?n =?= Nat.succ Nat.zero` always fail if `?n` is a syntheticOpaque metavariable. This kind of metavariable is created by tactics such as `intro`. Reason: in the tactic framework, subgoals as represented as metavariables, and a subgoal `?n` is considered as solved whenever the metavariable is assigned. This distinction was not precise in Lean3 and produced counterintuitive behavior. For example, the following hack was added in Lean3 to work around one of these issues: https://github.com/leanprover/lean/blob/92826917a252a6092cffaf5fc5f1acb1f8cef379/src/library/type_context.cpp#L2751 - When creating lambda/forall expressions, we need to convert/abstract free variables and convert them to bound variables. Now, suppose we a trying to create a lambda/forall expression by abstracting free variable `xs` and a term `t[?m]` which contains a metavariable `?m`, and the local context of `?m` contains `xs`. The term ``` fun xs => t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variables in `xs`. We address this issue by changing the free variable abstraction procedure. We consider two cases: `?m` is natural, `?m` is synthetic. Assume the type of `?m` is `A[xs]`. Then, in both cases we create an auxiliary metavariable `?n` with type `forall xs => A[xs]`, and local context := local context of `?m` - `xs`. In both cases, we produce the term `fun xs => t[?n xs]` 1- If `?m` is natural or synthetic, then we assign `?m := ?n xs`, and we produce the term `fun xs => t[?n xs]` 2- If `?m` is syntheticOpaque, then we mark `?n` as a syntheticOpaque variable. However, `?n` is managed by the metavariable context itself. We say we have a "delayed assignment" `?n xs := ?m`. That is, after a term `s` is assigned to `?m`, and `s` does not contain metavariables, we replace any occurrence `?n ts` with `s[xs := ts]`. Gruesome details: - When we create the type `forall xs => A` for `?n`, we may encounter the same issue if `A` contains metavariables. So, the process above is recursive. We claim it terminates because we keep creating new metavariables with smaller local contexts. - Suppose, we have `t[?m]` and we want to create a let-expression by abstracting a let-decl free variable `x`, and the local context of `?m` contatins `x`. Similarly to the previous case ``` let x : T := v; t[?m] ``` will be ill-formed if we later assign a term `s` to `?m`, and `s` contains free variable `x`. Again, assume the type of `?m` is `A[x]`. 1- If `?m` is natural or synthetic, then we create `?n : (let x : T := v; A[x])` with and local context := local context of `?m` - `x`, we assign `?m := ?n`, and produce the term `let x : T := v; t[?n]`. That is, we are just making sure `?n` must never be assigned to a term containing `x`. 2- If `?m` is syntheticOpaque, we create a fresh syntheticOpaque `?n` with type `?n : T -> (let x : T := v; A[x])` and local context := local context of `?m` - `x`, create the delayed assignment `?n #[x] := ?m`, and produce the term `let x : T := v; t[?n x]`. Now suppose we assign `s` to `?m`. We do not assign the term `fun (x : T) => s` to `?n`, since `fun (x : T) => s` may not even be type correct. Instead, we just replace applications `?n r` with `s[x/r]`. The term `r` may not necessarily be a bound variable. For example, a tactic may have reduced `let x : T := v; t[?n x]` into `t[?n v]`. We are essentially using the pair "delayed assignment + application" to implement a delayed substitution. - We use TC for implementing coercions. Both Joe Hendrix and Reid Barton reported a nasty limitation. In Lean3, TC will not be used if there are metavariables in the TC problem. For example, the elaborator will not try to synthesize `Coe Nat ?x`. This is good, but this constraint is too strict for problems such as `Coe (Vector Bool ?n) (BV ?n)`. The coercion exists independently of `?n`. Thus, during TC, we want `isDefEq` to throw an exception instead of return `false` whenever it tries to assign a metavariable owned by its caller. The idea is to sign to the caller that it cannot solve the TC problem at this point, and more information is needed. That is, the caller must make progress an assign its metavariables before trying to invoke TC again. In Lean4, we are using a simpler design for the `MetavarContext`. - No distinction betwen temporary and regular metavariables. - Metavariables have a `depth` Nat field. - MetavarContext also has a `depth` field. - We bump the `MetavarContext` depth when we create a nested problem. Example: Elaborator (depth = 0) -> Simplifier matcher (depth = 1) -> TC (level = 2) -> TC (level = 3) -> ... - When `MetavarContext` is at depth N, `isDefEq` does not assign variables from `depth < N`. - Metavariables from depth N+1 must be fully assigned before we return to level N. - New design even allows us to invoke tactics from TC. * Main concern We don't have tmp metavariables anymore in Lean4. Thus, before trying to match the left-hand-side of an equation in `simp`. We first must bump the level of the `MetavarContext`, create fresh metavariables, then create a new pattern by replacing the free variable on the left-hand-side with these metavariables. We are hoping to minimize this overhead by - Using better indexing data structures in `simp`. They should reduce the number of time `simp` must invoke `isDefEq`. - Implementing `isDefEqApprox` which ignores metavariables and returns only `false` or `undef`. It is a quick filter that allows us to fail quickly and avoid the creation of new fresh metavariables, and a new pattern. - Adding built-in support for arithmetic, Logical connectives, etc. Thus, we avoid a bunch of lemmas in the simp set. - Adding support for AC-rewriting. In Lean3, users use AC lemmas as rewriting rules for "sorting" terms. This is inefficient, requires a quadratic number of rewrite steps, and does not preserve the structure of the goal. The temporary metavariables were also used in the "app builder" module used in Lean3. The app builder uses `isDefEq`. So, it could, in principle, invoke an arbitrary number of nested TC problems. However, in Lean3, all app builder uses are controlled. That is, it is mainly used to synthesize implicit arguments using very simple unification and/or non-nested TC. So, if the "app builder" becomes a bottleneck without tmp metavars, we may solve the issue by implementing `isDefEqCheap` that never invokes TC and uses tmp metavars. -/ structure LocalInstance where className : Name fvar : Expr deriving Inhabited abbrev LocalInstances := Array LocalInstance instance : BEq LocalInstance where beq i₁ i₂ := i₁.fvar == i₂.fvar /-- Remove local instance with the given `fvarId`. Do nothing if `localInsts` does not contain any free variable with id `fvarId`. -/ def LocalInstances.erase (localInsts : LocalInstances) (fvarId : FVarId) : LocalInstances := match localInsts.findIdx? (fun inst => inst.fvar.fvarId! == fvarId) with | some idx => localInsts.eraseIdx idx | _ => localInsts inductive MetavarKind where | natural | synthetic | syntheticOpaque deriving Inhabited, Repr def MetavarKind.isSyntheticOpaque : MetavarKind → Bool | MetavarKind.syntheticOpaque => true | _ => false def MetavarKind.isNatural : MetavarKind → Bool | MetavarKind.natural => true | _ => false structure MetavarDecl where userName : Name := Name.anonymous lctx : LocalContext type : Expr depth : Nat localInstances : LocalInstances kind : MetavarKind numScopeArgs : Nat := 0 -- See comment at `CheckAssignment` `Meta/ExprDefEq.lean` index : Nat -- We use this field to track how old a metavariable is. It is set using a counter at `MetavarContext` deriving Inhabited /-- A delayed assignment for a metavariable `?m`. It represents an assignment of the form `?m := (fun fvars => val)`. The local context `lctx` provides the declarations for `fvars`. Note that `fvars` may not be defined in the local context for `?m`. - TODO: after we delete the old frontend, we can remove the field `lctx`. This field is only used in old C++ implementation. -/ structure DelayedMetavarAssignment where lctx : LocalContext fvars : Array Expr val : Expr open Std (HashMap PersistentHashMap) structure MetavarContext where depth : Nat := 0 mvarCounter : Nat := 0 -- Counter for setting the field `index` at `MetavarDecl` lDepth : PersistentHashMap MVarId Nat := {} decls : PersistentHashMap MVarId MetavarDecl := {} lAssignment : PersistentHashMap MVarId Level := {} eAssignment : PersistentHashMap MVarId Expr := {} dAssignment : PersistentHashMap MVarId DelayedMetavarAssignment := {} class MonadMCtx (m : Type → Type) where getMCtx : m MetavarContext modifyMCtx : (MetavarContext → MetavarContext) → m Unit export MonadMCtx (getMCtx modifyMCtx) instance (m n) [MonadLift m n] [MonadMCtx m] : MonadMCtx n where getMCtx := liftM (getMCtx : m _) modifyMCtx := fun f => liftM (modifyMCtx f : m _) namespace MetavarContext instance : Inhabited MetavarContext := ⟨{}⟩ @[export lean_mk_metavar_ctx] def mkMetavarContext : Unit → MetavarContext := fun _ => {} /- Low level API for adding/declaring metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addExprMVarDecl (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (numScopeArgs : Nat := 0) : MetavarContext := { mctx with mvarCounter := mctx.mvarCounter + 1 decls := mctx.decls.insert mvarId { depth := mctx.depth index := mctx.mvarCounter userName lctx localInstances type kind numScopeArgs } } def addExprMVarDeclExp (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) (lctx : LocalContext) (localInstances : LocalInstances) (type : Expr) (kind : MetavarKind) : MetavarContext := addExprMVarDecl mctx mvarId userName lctx localInstances type kind /- Low level API for adding/declaring universe level metavariable declarations. It is used to implement actions in the monads `MetaM`, `ElabM` and `TacticM`. It should not be used directly since the argument `(mvarId : MVarId)` is assumed to be "unique". -/ def addLevelMVarDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := { mctx with lDepth := mctx.lDepth.insert mvarId mctx.depth } def findDecl? (mctx : MetavarContext) (mvarId : MVarId) : Option MetavarDecl := mctx.decls.find? mvarId def getDecl (mctx : MetavarContext) (mvarId : MVarId) : MetavarDecl := match mctx.decls.find? mvarId with | some decl => decl | none => panic! "unknown metavariable" def findUserName? (mctx : MetavarContext) (userName : Name) : Option MVarId := let search : Except MVarId Unit := mctx.decls.forM fun mvarId decl => if decl.userName == userName then throw mvarId else pure () match search with | Except.ok _ => none | Except.error mvarId => some mvarId def setMVarKind (mctx : MetavarContext) (mvarId : MVarId) (kind : MetavarKind) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with kind := kind } } def setMVarUserName (mctx : MetavarContext) (mvarId : MVarId) (userName : Name) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with userName := userName } } /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mctx : MetavarContext) (mvarId : MVarId) (type : Expr) : MetavarContext := let decl := mctx.getDecl mvarId { mctx with decls := mctx.decls.insert mvarId { decl with type := type } } def findLevelDepth? (mctx : MetavarContext) (mvarId : MVarId) : Option Nat := mctx.lDepth.find? mvarId def getLevelDepth (mctx : MetavarContext) (mvarId : MVarId) : Nat := match mctx.findLevelDepth? mvarId with | some d => d | none => panic! "unknown metavariable" def isAnonymousMVar (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.findDecl? mvarId with | none => false | some mvarDecl => mvarDecl.userName.isAnonymous def renameMVar (mctx : MetavarContext) (mvarId : MVarId) (newUserName : Name) : MetavarContext := match mctx.findDecl? mvarId with | none => panic! "unknown metavariable" | some mvarDecl => { mctx with decls := mctx.decls.insert mvarId { mvarDecl with userName := newUserName } } def assignLevel (m : MetavarContext) (mvarId : MVarId) (val : Level) : MetavarContext := { m with lAssignment := m.lAssignment.insert mvarId val } def assignExpr (m : MetavarContext) (mvarId : MVarId) (val : Expr) : MetavarContext := { m with eAssignment := m.eAssignment.insert mvarId val } def assignDelayed (m : MetavarContext) (mvarId : MVarId) (lctx : LocalContext) (fvars : Array Expr) (val : Expr) : MetavarContext := { m with dAssignment := m.dAssignment.insert mvarId { lctx := lctx, fvars := fvars, val := val } } def getLevelAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Level := m.lAssignment.find? mvarId def getExprAssignment? (m : MetavarContext) (mvarId : MVarId) : Option Expr := m.eAssignment.find? mvarId def getDelayedAssignment? (m : MetavarContext) (mvarId : MVarId) : Option DelayedMetavarAssignment := m.dAssignment.find? mvarId def isLevelAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.lAssignment.contains mvarId def isExprAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.eAssignment.contains mvarId def isDelayedAssigned (m : MetavarContext) (mvarId : MVarId) : Bool := m.dAssignment.contains mvarId def eraseDelayed (m : MetavarContext) (mvarId : MVarId) : MetavarContext := { m with dAssignment := m.dAssignment.erase mvarId } /- Given a sequence of delayed assignments ``` mvarId₁ := mvarId₂ ...; ... mvarIdₙ := mvarId_root ... -- where `mvarId_root` is not delayed assigned ``` in `mctx`, `getDelayedRoot mctx mvarId₁` return `mvarId_root`. If `mvarId₁` is not delayed assigned then return `mvarId₁` -/ partial def getDelayedRoot (m : MetavarContext) : MVarId → MVarId | mvarId => match getDelayedAssignment? m mvarId with | some d => match d.val.getAppFn with | Expr.mvar mvarId _ => getDelayedRoot m mvarId | _ => mvarId | none => mvarId def isLevelAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := match mctx.lDepth.find? mvarId with | some d => d == mctx.depth | _ => panic! "unknown universe metavariable" def isExprAssignable (mctx : MetavarContext) (mvarId : MVarId) : Bool := let decl := mctx.getDecl mvarId decl.depth == mctx.depth def incDepth (mctx : MetavarContext) : MetavarContext := { mctx with depth := mctx.depth + 1 } /-- Return true iff the given level contains an assigned metavariable. -/ def hasAssignedLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignedLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignedLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignedLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssigned mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains assigned (level/expr) metavariables or delayed assigned mvars -/ def hasAssignedMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignedLevelMVar mctx) | Expr.sort lvl _ => hasAssignedLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignedMVar mctx f) || (a.hasMVar && hasAssignedMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignedMVar mctx t) || (v.hasMVar && hasAssignedMVar mctx v) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignedMVar mctx d) || (b.hasMVar && hasAssignedMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignedMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssigned mvarId || mctx.isDelayedAssigned mvarId /-- Return true iff the given level contains a metavariable that can be assigned. -/ def hasAssignableLevelMVar (mctx : MetavarContext) : Level → Bool | Level.succ lvl _ => lvl.hasMVar && hasAssignableLevelMVar mctx lvl | Level.max lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.imax lvl₁ lvl₂ _ => (lvl₁.hasMVar && hasAssignableLevelMVar mctx lvl₁) || (lvl₂.hasMVar && hasAssignableLevelMVar mctx lvl₂) | Level.mvar mvarId _ => mctx.isLevelAssignable mvarId | Level.zero _ => false | Level.param _ _ => false /-- Return `true` iff expression contains a metavariable that can be assigned. -/ def hasAssignableMVar (mctx : MetavarContext) : Expr → Bool | Expr.const _ lvls _ => lvls.any (hasAssignableLevelMVar mctx) | Expr.sort lvl _ => hasAssignableLevelMVar mctx lvl | Expr.app f a _ => (f.hasMVar && hasAssignableMVar mctx f) || (a.hasMVar && hasAssignableMVar mctx a) | Expr.letE _ t v b _ => (t.hasMVar && hasAssignableMVar mctx t) || (v.hasMVar && hasAssignableMVar mctx v) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.forallE _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.lam _ d b _ => (d.hasMVar && hasAssignableMVar mctx d) || (b.hasMVar && hasAssignableMVar mctx b) | Expr.fvar _ _ => false | Expr.bvar _ _ => false | Expr.lit _ _ => false | Expr.mdata _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.proj _ _ e _ => e.hasMVar && hasAssignableMVar mctx e | Expr.mvar mvarId _ => mctx.isExprAssignable mvarId /- Notes on artificial eta-expanded terms due to metavariables. We try avoid synthetic terms such as `((fun x y => t) a b)` in the output produced by the elaborator. This kind of term may be generated when instantiating metavariable assignments. This module tries to avoid their generation because they often introduce unnecessary dependencies and may affect automation. When elaborating terms, we use metavariables to represent "holes". Each hole has a context which includes all free variables that may be used to "fill" the hole. Suppose, we create a metavariable (hole) `?m : Nat` in a context containing `(x : Nat) (y : Nat) (b : Bool)`, then we can assign terms such as `x + y` to `?m` since `x` and `y` are in the context used to create `?m`. Now, suppose we have the term `?m + 1` and we want to create the lambda expression `fun x => ?m + 1`. This term is not correct since we may assign to `?m` a term containing `x`. We address this issue by create a synthetic metavariable `?n : Nat → Nat` and adding the delayed assignment `?n #[x] := ?m`, and the term `fun x => ?n x + 1`. When we later assign a term `t[x]` to `?m`, `fun x => t[x]` is assigned to `?n`, and if we substitute it at `fun x => ?n x + 1`, we produce `fun x => ((fun x => t[x]) x) + 1`. To avoid this term eta-expanded term, we apply beta-reduction when instantiating metavariable assignments in this module. This operation is performed at `instantiateExprMVars`, `elimMVarDeps`, and `levelMVarToParam`. -/ partial def instantiateLevelMVars [Monad m] [MonadMCtx m] : Level → m Level | lvl@(Level.succ lvl₁ _) => return Level.updateSucc! lvl (← instantiateLevelMVars lvl₁) | lvl@(Level.max lvl₁ lvl₂ _) => return Level.updateMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.imax lvl₁ lvl₂ _) => return Level.updateIMax! lvl (← instantiateLevelMVars lvl₁) (← instantiateLevelMVars lvl₂) | lvl@(Level.mvar mvarId _) => do match getLevelAssignment? (← getMCtx) mvarId with | some newLvl => if !newLvl.hasMVar then pure newLvl else do let newLvl' ← instantiateLevelMVars newLvl modifyMCtx fun mctx => mctx.assignLevel mvarId newLvl' pure newLvl' | none => pure lvl | lvl => pure lvl /-- instantiateExprMVars main function -/ partial def instantiateExprMVars [Monad m] [MonadMCtx m] [STWorld ω m] [MonadLiftT (ST ω) m] (e : Expr) : MonadCacheT ExprStructEq Expr m Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← instantiateExprMVars s) | Expr.forallE _ d b _ => return e.updateForallE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.lam _ d b _ => return e.updateLambdaE! (← instantiateExprMVars d) (← instantiateExprMVars b) | Expr.letE _ t v b _ => return e.updateLet! (← instantiateExprMVars t) (← instantiateExprMVars v) (← instantiateExprMVars b) | Expr.const _ lvls _ => return e.updateConst! (← lvls.mapM instantiateLevelMVars) | Expr.sort lvl _ => return e.updateSort! (← instantiateLevelMVars lvl) | Expr.mdata _ b _ => return e.updateMData! (← instantiateExprMVars b) | Expr.app .. => e.withApp fun f args => do let instArgs (f : Expr) : MonadCacheT ExprStructEq Expr m Expr := do let args ← args.mapM instantiateExprMVars pure (mkAppN f args) let instApp : MonadCacheT ExprStructEq Expr m Expr := do let wasMVar := f.isMVar let f ← instantiateExprMVars f if wasMVar && f.isLambda then /- Some of the arguments in args are irrelevant after we beta reduce. -/ instantiateExprMVars (f.betaRev args.reverse) else instArgs f match f with | Expr.mvar mvarId _ => let mctx ← getMCtx match mctx.getDelayedAssignment? mvarId with | none => instApp | some { fvars := fvars, val := val, .. } => /- Apply "delayed substitution" (i.e., delayed assignment + application). That is, `f` is some metavariable `?m`, that is delayed assigned to `val`. If after instantiating `val`, we obtain `newVal`, and `newVal` does not contain metavariables, we replace the free variables `fvars` in `newVal` with the first `fvars.size` elements of `args`. -/ if fvars.size > args.size then /- We don't have sufficient arguments for instantiating the free variables `fvars`. This can only happy if a tactic or elaboration function is not implemented correctly. We decided to not use `panic!` here and report it as an error in the frontend when we are checking for unassigned metavariables in an elaborated term. -/ instArgs f else let newVal ← instantiateExprMVars val if newVal.hasExprMVar then instArgs f else do let args ← args.mapM instantiateExprMVars /- Example: suppose we have `?m t1 t2 t3` That is, `f := ?m` and `args := #[t1, t2, t3]` Morever, `?m` is delayed assigned `?m #[x, y] := f x y` where, `fvars := #[x, y]` and `newVal := f x y`. After abstracting `newVal`, we have `f (Expr.bvar 0) (Expr.bvar 1)`. After `instantiaterRevRange 0 2 args`, we have `f t1 t2`. After `mkAppRange 2 3`, we have `f t1 t2 t3` -/ let newVal := newVal.abstract fvars let result := newVal.instantiateRevRange 0 fvars.size args let result := mkAppRange result fvars.size args.size args pure result | _ => instApp | e@(Expr.mvar mvarId _) => checkCache { val := e : ExprStructEq } fun _ => do let mctx ← getMCtx match mctx.getExprAssignment? mvarId with | some newE => do let newE' ← instantiateExprMVars newE modifyMCtx fun mctx => mctx.assignExpr mvarId newE' pure newE' | none => pure e | e => pure e instance : MonadMCtx (StateRefT MetavarContext (ST ω)) where getMCtx := get modifyMCtx := modify def instantiateMVars (mctx : MetavarContext) (e : Expr) : Expr × MetavarContext := if !e.hasMVar then (e, mctx) else let instantiate {ω} (e : Expr) : (MonadCacheT ExprStructEq Expr $ StateRefT MetavarContext $ ST ω) Expr := instantiateExprMVars e runST fun _ => instantiate e |>.run |>.run mctx def instantiateLCtxMVars (mctx : MetavarContext) (lctx : LocalContext) : LocalContext × MetavarContext := lctx.foldl (init := ({}, mctx)) fun (lctx, mctx) ldecl => match ldecl with | LocalDecl.cdecl _ fvarId userName type bi => let (type, mctx) := mctx.instantiateMVars type (lctx.mkLocalDecl fvarId userName type bi, mctx) | LocalDecl.ldecl _ fvarId userName type value nonDep => let (type, mctx) := mctx.instantiateMVars type let (value, mctx) := mctx.instantiateMVars value (lctx.mkLetDecl fvarId userName type value nonDep, mctx) def instantiateMVarDeclMVars (mctx : MetavarContext) (mvarId : MVarId) : MetavarContext := let mvarDecl := mctx.getDecl mvarId let (lctx, mctx) := mctx.instantiateLCtxMVars mvarDecl.lctx let (type, mctx) := mctx.instantiateMVars mvarDecl.type { mctx with decls := mctx.decls.insert mvarId { mvarDecl with lctx := lctx, type := type } } namespace DependsOn private abbrev M := StateM ExprSet private def shouldVisit (e : Expr) : M Bool := do if !e.hasMVar && !e.hasFVar then return false else if (← get).contains e then return false else modify fun s => s.insert e return true @[specialize] private partial def dep (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := let rec visit (e : Expr) : M Bool := do if !(← shouldVisit e) then pure false else visitMain e, visitMain : Expr → M Bool | Expr.proj _ _ s _ => visit s | 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.mdata _ b _ => visit b | Expr.app f a _ => visit a <||> if f.isApp then visitMain f else visit f | Expr.mvar mvarId _ => match mctx.getExprAssignment? mvarId with | some a => visit a | none => let lctx := (mctx.getDecl mvarId).lctx return lctx.any fun decl => p decl.fvarId | Expr.fvar fvarId _ => return p fvarId | e => pure false visit e @[inline] partial def main (mctx : MetavarContext) (p : FVarId → Bool) (e : Expr) : M Bool := if !e.hasFVar && !e.hasMVar then pure false else dep mctx p e end DependsOn /-- Return `true` iff `e` depends on a free variable `x` s.t. `p x` is `true`. For each metavariable `?m` occurring in `x` 1- If `?m := t`, then we visit `t` looking for `x` 2- If `?m` is unassigned, then we consider the worst case and check whether `x` is in the local context of `?m`. This case is a "may dependency". That is, we may assign a term `t` to `?m` s.t. `t` contains `x`. -/ @[inline] def findExprDependsOn (mctx : MetavarContext) (e : Expr) (p : FVarId → Bool) : Bool := DependsOn.main mctx p e |>.run' {} /-- Similar to `findExprDependsOn`, but checks the expressions in the given local declaration depends on a free variable `x` s.t. `p x` is `true`. -/ @[inline] def findLocalDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (p : FVarId → Bool) : Bool := match localDecl with | LocalDecl.cdecl (type := t) .. => findExprDependsOn mctx t p | LocalDecl.ldecl (type := t) (value := v) .. => (DependsOn.main mctx p t <||> DependsOn.main mctx p v).run' {} def exprDependsOn (mctx : MetavarContext) (e : Expr) (fvarId : FVarId) : Bool := findExprDependsOn mctx e fun fvarId' => fvarId == fvarId' def localDeclDependsOn (mctx : MetavarContext) (localDecl : LocalDecl) (fvarId : FVarId) : Bool := findLocalDeclDependsOn mctx localDecl fun fvarId' => fvarId == fvarId' namespace MkBinding inductive Exception where | revertFailure (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (decl : LocalDecl) instance : ToString Exception where toString | Exception.revertFailure _ lctx toRevert decl => "failed to revert " ++ toString (toRevert.map (fun x => "'" ++ toString (lctx.getFVar! x).userName ++ "'")) ++ ", '" ++ toString decl.userName ++ "' depends on them, and it is an auxiliary declaration created by the elaborator" ++ " (possible solution: use tactic 'clear' to remove '" ++ toString decl.userName ++ "' from local context)" /-- `MkBinding` and `elimMVarDepsAux` are mutually recursive, but `cache` is only used at `elimMVarDepsAux`. We use a single state object for convenience. We have a `NameGenerator` because we need to generate fresh auxiliary metavariables. -/ structure State where mctx : MetavarContext ngen : NameGenerator cache : HashMap ExprStructEq Expr := {} abbrev MCore := EStateM Exception State abbrev M := ReaderT Bool MCore def preserveOrder : M Bool := read instance : MonadHashMapCacheAdapter ExprStructEq Expr M where getCache := do let s ← get; pure s.cache modifyCache := fun f => modify fun s => { s with cache := f s.cache } /-- Return the local declaration of the free variable `x` in `xs` with the smallest index -/ private def getLocalDeclWithSmallestIdx (lctx : LocalContext) (xs : Array Expr) : LocalDecl := do let mut d : LocalDecl := lctx.getFVar! xs[0] for i in [1:xs.size] do let curr := lctx.getFVar! xs[i] if curr.index < d.index then d := curr return d /-- Given `toRevert` an array of free variables s.t. `lctx` contains their declarations, return a new array of free variables that contains `toRevert` and all free variables in `lctx` that may depend on `toRevert`. Remark: the result is sorted by `LocalDecl` indices. Remark: We used to throw an `Exception.revertFailure` exception when an auxiliary declaration had to be reversed. Recall that auxiliary declarations are created when compiling (mutually) recursive definitions. The `revertFailure` due to auxiliary declaration dependency was originally introduced in Lean3 to address issue https://github.com/leanprover/lean/issues/1258. In Lean4, this solution is not satisfactory because all definitions/theorems are potentially recursive. So, even an simple (incomplete) definition such as ``` variables {α : Type} in def f (a : α) : List α := _ ``` would trigger the `Exception.revertFailure` exception. In the definition above, the elaborator creates the auxiliary definition `f : {α : Type} → List α`. The `_` is elaborated as a new fresh variable `?m` that contains `α : Type`, `a : α`, and `f : α → List α` in its context, When we try to create the lambda `fun {α : Type} (a : α) => ?m`, we first need to create an auxiliary `?n` which do not contain `α` and `a` in its context. That is, we create the metavariable `?n : {α : Type} → (a : α) → (f : α → List α) → List α`, add the delayed assignment `?n #[α, a, f] := ?m α a f`, and create the lambda `fun {α : Type} (a : α) => ?n α a f`. See `elimMVarDeps` for more information. If we kept using the Lean3 approach, we would get the `Exception.revertFailure` exception because we are reverting the auxiliary definition `f`. Note that https://github.com/leanprover/lean/issues/1258 is not an issue in Lean4 because we have changed how we compile recursive definitions. -/ def collectDeps (mctx : MetavarContext) (lctx : LocalContext) (toRevert : Array Expr) (preserveOrder : Bool) : Except Exception (Array Expr) := do if toRevert.size == 0 then pure toRevert else if preserveOrder then -- Make sure none of `toRevert` is an AuxDecl -- Make sure toRevert[j] does not depend on toRevert[i] for j > i toRevert.size.forM fun i => do let fvar := toRevert[i] let decl := lctx.getFVar! fvar i.forM fun j => do let prevFVar := toRevert[j] let prevDecl := lctx.getFVar! prevFVar if localDeclDependsOn mctx prevDecl fvar.fvarId! then throw (Exception.revertFailure mctx lctx toRevert prevDecl) let newToRevert := if preserveOrder then toRevert else Array.mkEmpty toRevert.size let firstDeclToVisit := getLocalDeclWithSmallestIdx lctx toRevert let initSize := newToRevert.size lctx.foldlM (init := newToRevert) (start := firstDeclToVisit.index) fun (newToRevert : Array Expr) decl => if initSize.any fun i => decl.fvarId == (newToRevert.get! i).fvarId! then pure newToRevert else if toRevert.any fun x => decl.fvarId == x.fvarId! then pure (newToRevert.push decl.toExpr) else if findLocalDeclDependsOn mctx decl (fun fvarId => newToRevert.any fun x => x.fvarId! == fvarId) then pure (newToRevert.push decl.toExpr) else pure newToRevert /-- Create a new `LocalContext` by removing the free variables in `toRevert` from `lctx`. We use this function when we create auxiliary metavariables at `elimMVarDepsAux`. -/ def reduceLocalContext (lctx : LocalContext) (toRevert : Array Expr) : LocalContext := toRevert.foldr (init := lctx) fun x lctx => lctx.erase x.fvarId! @[inline] private def getMCtx : M MetavarContext := return (← get).mctx /-- Return free variables in `xs` that are in the local context `lctx` -/ private def getInScope (lctx : LocalContext) (xs : Array Expr) : Array Expr := xs.foldl (init := #[]) fun scope x => if lctx.contains x.fvarId! then scope.push x else scope /-- Execute `x` with an empty cache, and then restore the original cache. -/ @[inline] private def withFreshCache (x : M α) : M α := do let cache ← modifyGet fun s => (s.cache, { s with cache := {} }) let a ← x modify fun s => { s with cache := cache } pure a /-- Create an application `mvar ys` where `ys` are the free variables. See "Gruesome details" in the beginning of the file for understanding how let-decl free variables are handled. -/ private def mkMVarApp (lctx : LocalContext) (mvar : Expr) (xs : Array Expr) (kind : MetavarKind) : Expr := xs.foldl (init := mvar) fun e x => match kind with | MetavarKind.syntheticOpaque => mkApp e x | _ => if (lctx.getFVar! x).isLet then e else mkApp e x /-- Return true iff some `e` in `es` depends on `fvarId` -/ private def anyDependsOn (mctx : MetavarContext) (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => exprDependsOn mctx e fvarId mutual private partial def visit (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else checkCache { val := e : ExprStructEq } fun _ => elim xs e private partial def elim (xs : Array Expr) (e : Expr) : M Expr := match e with | Expr.proj _ _ s _ => return e.updateProj! (← visit xs s) | Expr.forallE _ d b _ => return e.updateForallE! (← visit xs d) (← visit xs b) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit xs d) (← visit xs b) | Expr.letE _ t v b _ => return e.updateLet! (← visit xs t) (← visit xs v) (← visit xs b) | Expr.mdata _ b _ => return e.updateMData! (← visit xs b) | Expr.app _ _ _ => e.withApp fun f args => elimApp xs f args | Expr.mvar mvarId _ => elimApp xs e #[] | e => return e private partial def mkAuxMVarType (lctx : LocalContext) (xs : Array Expr) (kind : MetavarKind) (e : Expr) : M Expr := do let e ← abstractRangeAux xs xs.size e xs.size.foldRevM (init := e) fun i e => let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => do let type := type.headBeta let type ← abstractRangeAux xs i type pure <| Lean.mkForall n bi type e | LocalDecl.ldecl _ _ n type value nonDep => do let type := type.headBeta let type ← abstractRangeAux xs i type let value ← abstractRangeAux xs i value let e := mkLet n type value e nonDep match kind with | MetavarKind.syntheticOpaque => -- See "Gruesome details" section in the beginning of the file let e := e.liftLooseBVars 0 1 pure <| mkForall n BinderInfo.default type e | _ => pure e where abstractRangeAux (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elim xs e pure (e.abstractRange i xs) private partial def elimMVar (xs : Array Expr) (mvarId : MVarId) (args : Array Expr) : M (Expr × Array Expr) := do let mctx ← getMCtx let mvarDecl := mctx.getDecl mvarId let mvarLCtx := mvarDecl.lctx let toRevert := getInScope mvarLCtx xs if toRevert.size == 0 then let args ← args.mapM (visit xs) return (mkAppN (mkMVar mvarId) args, #[]) else /- `newMVarKind` is the kind for the new auxiliary metavariable. There is an alternative approach where we use ``` let newMVarKind := if !mctx.isExprAssignable mvarId || mvarDecl.isSyntheticOpaque then MetavarKind.syntheticOpaque else MetavarKind.natural ``` In this approach, we use the natural kind for the new auxiliary metavariable if the original metavariable is synthetic and assignable. Since we mainly use synthetic metavariables for pending type class (TC) resolution problems, this approach may minimize the number of TC resolution problems that may need to be resolved. A potential disadvantage is that `isDefEq` will not eagerly use `synthPending` for natural metavariables. That being said, we should try this approach as soon as we have an extensive test suite. -/ let newMVarKind := if !mctx.isExprAssignable mvarId then MetavarKind.syntheticOpaque else mvarDecl.kind /- If `mvarId` is the lhs of a delayed assignment `?m #[x_1, ... x_n] := val`, then `nestedFVars` is `#[x_1, ..., x_n]`. In this case, we produce a new `syntheticOpaque` metavariable `?n` and a delayed assignment ``` ?n #[y_1, ..., y_m, x_1, ... x_n] := ?m x_1 ... x_n ``` where `#[y_1, ..., y_m]` is `toRevert` after `collectDeps`. Remark: `newMVarKind != MetavarKind.syntheticOpaque ==> nestedFVars == #[]` -/ let rec cont (nestedFVars : Array Expr) (nestedLCtx : LocalContext) : M (Expr × Array Expr) := do let args ← args.mapM (visit xs) let preserve ← preserveOrder match collectDeps mctx mvarLCtx toRevert preserve with | Except.error ex => throw ex | Except.ok toRevert => let newMVarLCtx := reduceLocalContext mvarLCtx toRevert let newLocalInsts := mvarDecl.localInstances.filter fun inst => toRevert.all fun x => inst.fvar != x -- Remark: we must reset the before processing `mkAuxMVarType` because `toRevert` may not be equal to `xs` let newMVarType ← withFreshCache do mkAuxMVarType mvarLCtx toRevert newMVarKind mvarDecl.type let newMVarId := { name := (← get).ngen.curr } let newMVar := mkMVar newMVarId let result := mkMVarApp mvarLCtx newMVar toRevert newMVarKind let numScopeArgs := mvarDecl.numScopeArgs + result.getAppNumArgs modify fun s => { s with mctx := s.mctx.addExprMVarDecl newMVarId Name.anonymous newMVarLCtx newLocalInsts newMVarType newMVarKind numScopeArgs, ngen := s.ngen.next } match newMVarKind with | MetavarKind.syntheticOpaque => modify fun s => { s with mctx := assignDelayed s.mctx newMVarId nestedLCtx (toRevert ++ nestedFVars) (mkAppN (mkMVar mvarId) nestedFVars) } | _ => modify fun s => { s with mctx := assignExpr s.mctx mvarId result } return (mkAppN result args, toRevert) if !mvarDecl.kind.isSyntheticOpaque then cont #[] mvarLCtx else match mctx.getDelayedAssignment? mvarId with | none => cont #[] mvarLCtx | some { fvars := fvars, lctx := nestedLCtx, .. } => cont fvars nestedLCtx -- Remark: nestedLCtx is bigger than mvarLCtx private partial def elimApp (xs : Array Expr) (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId _ => match (← getMCtx).getExprAssignment? mvarId with | some newF => if newF.isLambda then let args ← args.mapM (visit xs) elim xs <| newF.betaRev args.reverse else elimApp xs newF args | none => return (← elimMVar xs mvarId args).1 | _ => return mkAppN (← visit xs f) (← args.mapM (visit xs)) end partial def elimMVarDeps (xs : Array Expr) (e : Expr) : M Expr := if !e.hasMVar then pure e else withFreshCache do elim xs e partial def revert (xs : Array Expr) (mvarId : MVarId) : M (Expr × Array Expr) := withFreshCache do elimMVar xs mvarId #[] /-- Similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. `elimMVarDeps` is defined later in this file. -/ @[inline] def abstractRange (xs : Array Expr) (i : Nat) (e : Expr) : M Expr := do let e ← elimMVarDeps xs e pure (e.abstractRange i xs) /-- Similar to `LocalContext.mkBinding`, but handles metavariables correctly. If `usedOnly == false` then `forall` and `lambda` expressions are created only for used variables. If `usedLetOnly == false` then `let` expressions are created only for used (let-) variables. -/ @[specialize] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (e : Expr) (usedOnly : Bool) (usedLetOnly : Bool) : M (Expr × Nat) := do let e ← abstractRange xs xs.size e xs.size.foldRevM (fun i (p : Expr × Nat) => do let (e, num) := p; let x := xs[i] match lctx.getFVar! x with | LocalDecl.cdecl _ _ n type bi => if !usedOnly || e.hasLooseBVar 0 then let type := type.headBeta; let type ← abstractRange xs i type if isLambda then pure (Lean.mkLambda n bi type e, num + 1) else pure (Lean.mkForall n bi type e, num + 1) else pure (e.lowerLooseBVars 1 1, num) | LocalDecl.ldecl _ _ n type value nonDep => if !usedLetOnly || e.hasLooseBVar 0 then let type ← abstractRange xs i type let value ← abstractRange xs i value pure (mkLet n type value e nonDep, num + 1) else pure (e.lowerLooseBVars 1 1, num)) (e, 0) end MkBinding abbrev MkBindingM := ReaderT LocalContext MkBinding.MCore def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool) : MkBindingM Expr := fun _ => MkBinding.elimMVarDeps xs e preserveOrder def revert (xs : Array Expr) (mvarId : MVarId) (preserveOrder : Bool) : MkBindingM (Expr × Array Expr) := fun _ => MkBinding.revert xs mvarId preserveOrder def mkBinding (isLambda : Bool) (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM (Expr × Nat) := fun lctx => MkBinding.mkBinding isLambda lctx xs e usedOnly usedLetOnly false @[inline] def mkLambda (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := true) xs e usedOnly usedLetOnly pure e @[inline] def mkForall (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MkBindingM Expr := do let (e, _) ← mkBinding (isLambda := false) xs e usedOnly usedLetOnly pure e @[inline] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MkBindingM Expr := fun _ => MkBinding.abstractRange xs n e false /-- `isWellFormed mctx lctx e` return true if - All locals in `e` are declared in `lctx` - All metavariables `?m` in `e` have a local context which is a subprefix of `lctx` or are assigned, and the assignment is well-formed. -/ partial def isWellFormed (mctx : MetavarContext) (lctx : LocalContext) : Expr → Bool | Expr.mdata _ e _ => isWellFormed mctx lctx e | Expr.proj _ _ e _ => isWellFormed mctx lctx e | e@(Expr.app f a _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx f && isWellFormed mctx lctx a) | e@(Expr.lam _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.forallE _ d b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx d && isWellFormed mctx lctx b) | e@(Expr.letE _ t v b _) => (!e.hasExprMVar && !e.hasFVar) || (isWellFormed mctx lctx t && isWellFormed mctx lctx v && isWellFormed mctx lctx b) | Expr.const .. => true | Expr.bvar .. => true | Expr.sort .. => true | Expr.lit .. => true | Expr.mvar mvarId _ => let mvarDecl := mctx.getDecl mvarId; if mvarDecl.lctx.isSubPrefixOf lctx then true else match mctx.getExprAssignment? mvarId with | none => false | some v => isWellFormed mctx lctx v | Expr.fvar fvarId _ => lctx.contains fvarId namespace LevelMVarToParam structure Context where paramNamePrefix : Name alreadyUsedPred : Name → Bool structure State where mctx : MetavarContext paramNames : Array Name := #[] nextParamIdx : Nat cache : HashMap ExprStructEq Expr := {} abbrev M := ReaderT Context $ StateM State instance : MonadCache ExprStructEq Expr M where findCached? e := return (← get).cache.find? e cache e v := modify fun s => { s with cache := s.cache.insert e v } partial def mkParamName : M Name := do let ctx ← read let s ← get let newParamName := ctx.paramNamePrefix.appendIndexAfter s.nextParamIdx if ctx.alreadyUsedPred newParamName then modify fun s => { s with nextParamIdx := s.nextParamIdx + 1 } mkParamName else do modify fun s => { s with nextParamIdx := s.nextParamIdx + 1, paramNames := s.paramNames.push newParamName } pure newParamName partial def visitLevel (u : Level) : M Level := do match u with | Level.succ v _ => return u.updateSucc! (← visitLevel v) | Level.max v₁ v₂ _ => return u.updateMax! (← visitLevel v₁) (← visitLevel v₂) | Level.imax v₁ v₂ _ => return u.updateIMax! (← visitLevel v₁) (← visitLevel v₂) | Level.zero _ => pure u | Level.param .. => pure u | Level.mvar mvarId _ => let s ← get match s.mctx.getLevelAssignment? mvarId with | some v => visitLevel v | none => let p ← mkParamName let p := mkLevelParam p modify fun s => { s with mctx := s.mctx.assignLevel mvarId p } pure p partial def main (e : Expr) : M Expr := if !e.hasMVar then return e else checkCache { val := e : ExprStructEq } fun _ => do match e with | Expr.proj _ _ s _ => return e.updateProj! (← main s) | Expr.forallE _ d b _ => return e.updateForallE! (← main d) (← main b) | Expr.lam _ d b _ => return e.updateLambdaE! (← main d) (← main b) | Expr.letE _ t v b _ => return e.updateLet! (← main t) (← main v) (← main b) | Expr.app .. => e.withApp fun f args => visitApp f args | Expr.mdata _ b _ => return e.updateMData! (← main b) | Expr.const _ us _ => return e.updateConst! (← us.mapM visitLevel) | Expr.sort u _ => return e.updateSort! (← visitLevel u) | Expr.mvar .. => visitApp e #[] | e => return e where visitApp (f : Expr) (args : Array Expr) : M Expr := do match f with | Expr.mvar mvarId .. => match (← get).mctx.getExprAssignment? mvarId with | some v => return (← visitApp v args).headBeta | none => return mkAppN f (← args.mapM main) | _ => return mkAppN (← main f) (← args.mapM main) end LevelMVarToParam structure UnivMVarParamResult where mctx : MetavarContext newParamNames : Array Name nextParamIdx : Nat expr : Expr def levelMVarToParam (mctx : MetavarContext) (alreadyUsedPred : Name → Bool) (e : Expr) (paramNamePrefix : Name := `u) (nextParamIdx : Nat := 1) : UnivMVarParamResult := let (e, s) := LevelMVarToParam.main e { paramNamePrefix := paramNamePrefix, alreadyUsedPred := alreadyUsedPred } { mctx := mctx, nextParamIdx := nextParamIdx } { mctx := s.mctx, newParamNames := s.paramNames, nextParamIdx := s.nextParamIdx, expr := e } def getExprAssignmentDomain (mctx : MetavarContext) : Array MVarId := mctx.eAssignment.foldl (init := #[]) fun a mvarId _ => Array.push a mvarId end MetavarContext end Lean
fb7ab0819e97de5a5abc18f98476e61e1e8787a8
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/ppbug.lean
2d05286affdee3a7b8918e5edbe476205da6f8f2
[ "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
19
lean
#check list.rec_on
72931842359a565644bb69f8fca909cd69a047c8
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/structure.lean
c00bd5bdaab7e8a69794835990194c3488077eb9
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,184
lean
import Lean open Lean structure S1 := (x y : Nat) structure S2 extends S1 := (z : Nat) structure S3 := (w : Nat) structure S4 extends S2, S3 := (s : Nat) def check (b : Bool) : CoreM Unit := unless b $ throwError "check failed" class S5 := (x y : Nat) inductive D | mk (x y z : Nat) : D def tst : CoreM Unit := do env ← getEnv; IO.println (getStructureFields env `Lean.Environment); check $ getStructureFields env `S4 == #[`toS2, `toS3, `s]; check $ getStructureFields env `S1 == #[`x, `y]; check $ isSubobjectField? env `S4 `toS2 == some `S2; check $ getParentStructures env `S4 == #[`S2, `S3]; check $ findField? env `S4 `x == some `S1; check $ findField? env `S4 `x1 == none; check $ isStructure env `S1; check $ isStructure env `S2; check $ isStructure env `S3; check $ isStructure env `S4; check $ isStructure env `S5; check $ !isStructure env `Nat; check $ !isStructure env `D; IO.println (getStructureFieldsFlattened env `S4); IO.println (getStructureFields env `D); IO.println (getPathToBaseStructure? env `S1 `S4); check $ getPathToBaseStructure? env `S1 `S4 == some [`S4.toS2, `S2.toS1]; pure () #eval tst
550c4a3eec815352b3e382750897c17a95b596c6
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Server/FileWorker.lean
6010e8f49fb050b389fa6d36f74eee425dd4858f
[ "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
17,804
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList import Lean.Server.FileWorker.Utils import Lean.Server.FileWorker.RequestHandling /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Std (RBMap RBMap.empty) open JsonRpc /- Asynchronous snapshot elaboration. -/ section Elab /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) : ExceptT ElabTaskError IO Snapshot := do cancelTk.check publishProgressAtPos m parentSnap.endPos hOut let maybeSnap ← compileNextCmd m.text.source parentSnap -- TODO(MH): check for interrupt with increased precision cancelTk.check match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ publishMessages m snap.msgLog hOut snap | Sum.inr msgLog => publishMessages m msgLog hOut publishProgressDone m hOut throw ElabTaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (hOut : FS.Stream) (initial : Bool) : IO (AsyncList ElabTaskError Snapshot) := do if initial && initSnap.msgLog.hasErrors then -- treat header processing errors as fatal so users aren't swamped with followup errors AsyncList.nil else AsyncList.unfoldAsync (nextCmdSnap m . cancelTk hOut) initSnap end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare structure WorkerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream srcSearchPath : SearchPath docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev WorkerM := ReaderT WorkerContext IO /- Worker initialization sequence. -/ section Initialization /-- Use `leanpkg print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def leanpkgSetupSearchPath (leanpkgPath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let leanpkgProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := leanpkgPath.toString args := #["print-paths"] ++ imports.map (toString ·.module) } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← leanpkgProc.stderr.getLine if line == "" then return acc else publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← leanpkgProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get if (← leanpkgProc.wait) == 0 then let leanpkgLines := stdout.split (· == '\n') -- ignore any output up to the last two lines -- TODO: leanpkg should instead redirect nested stdout output to stderr let leanpkgLines := leanpkgLines.drop (leanpkgLines.length - 2) match leanpkgLines with | [""] => pure [] -- e.g. no leanpkg.toml | [leanPath, leanSrcPath] => let sp ← getBuiltinSearchPath let sp ← addSearchPathFromEnv sp let sp := System.SearchPath.parse leanPath ++ sp searchPathRef.set sp let srcPath := System.SearchPath.parse leanSrcPath srcPath.mapM realPathNormalized | _ => throwServerError s!"unexpected output from `leanpkg print-paths`:\n{stdout}\nstderr:\n{stderr}" else throwServerError s!"`leanpkg print-paths` failed:\n{stdout}\nstderr:\n{stderr}" def compileHeader (m : DocumentMeta) (hOut : FS.Stream) : IO (Snapshot × SearchPath) := do let opts := {} -- TODO let inputCtx := Parser.mkInputContext m.text.source "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let leanpkgPath ← match (← IO.getEnv "LEAN_SYSROOT") with | some path => pure <| System.FilePath.mk path / "bin" / "leanpkg" | _ => pure <| (← appDir) / "leanpkg" let leanpkgPath := leanpkgPath.withExtension System.FilePath.exeExtension let mut srcSearchPath := [(← appDir) / ".." / "lib" / "lean" / "src"] if let some p := (← IO.getEnv "LEAN_SRC_PATH") then srcSearchPath := srcSearchPath ++ System.SearchPath.parse p let (headerEnv, msgLog) ← try -- NOTE: leanpkg does not exist in stage 0 (yet?) if (← System.FilePath.pathExists leanpkgPath) then let pkgSearchPath ← leanpkgSetupSearchPath leanpkgPath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath := srcSearchPath ++ pkgSearchPath Elab.processHeader headerStx opts msgLog inputCtx catch e => -- should be from `leanpkg print-paths` let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString } pure (← mkEmptyEnvironment, msgs) publishMessages m msgLog hOut let cmdState := Elab.Command.mkState headerEnv msgLog opts let cmdState := { cmdState with infoState.enabled := true, scopes := [{ header := "", opts := opts }] } let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState cmdState := cmdState } return (headerSnap, srcSearchPath) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) : IO WorkerContext := do /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let (headerSnap, srcSearchPath) ← compileHeader meta o let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk o (initial := true) let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩ return { hIn := i hOut := o hLog := e srcSearchPath := srcSearchPath docRef := ←IO.mkRef doc pendingRequestsRef := ←IO.mkRef RBMap.empty } end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : WorkerM Unit := do (←read).pendingRequestsRef.modify map /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : WorkerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some ElabTaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (ElabTaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.hOut (initial := true) st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk st.hOut (initial := false) let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff def handleCancelRequest (p : CancelParams) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : WorkerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleNotification (method : String) (params : Json) : WorkerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : WorkerM Unit := do let st ← read let rc : Requests.RequestContext := { srcSearchPath := st.srcSearchPath, docRef := st.docRef } let t? ← (ExceptT.run <| Requests.handleLspRequest method params rc : IO _) let t₁ ← match t? with | Except.error e => IO.asTask do st.hOut.writeLspResponseError <| e.toLspResponseError id | Except.ok t => (IO.mapTask · t) fun | Except.ok resp => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.error e => st.hOut.writeLspResponseError <| e.toLspResponseError id queueRequest id t₁ end MessageHandling section MainLoop partial def mainLoop : WorkerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : WorkerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc ← st.docRef.get doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let doc := param.textDocument let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let ctx ← initializeWorker meta i o e ReaderT.run (r := ctx) mainLoop return 0 catch e => IO.eprintln e publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o return 1 @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try let exitCode ← initAndRunWorker i o e -- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, but we definitely don't -- want to do that in the case of the worker processes, which can produce non-terminating tasks evaluating user code o.flush e.flush IO.Process.exit exitCode.toUInt8 catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
207769164f194c5bb5a6dd8dda5ac4ab6062beb1
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/group_theory/subgroup.lean
96589bef7453cbe837c99ea6e96dc3daf726cb9a
[ "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
29,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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro, Michael Howes -/ import group_theory.submonoid open set function variables {G : Type*} {H : Type*} {A : Type*} {a a₁ a₂ b c: G} section group variables [group G] [add_group A] @[to_additive] lemma injective_mul {a : G} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this section prio set_option default_priority 100 -- see Note [default priority] /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set A) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ @[to_additive is_add_subgroup] class is_subgroup (s : set G) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) end prio lemma additive.is_add_subgroup (s : set G) [is_subgroup s] : @is_add_subgroup (additive G) _ s := @is_add_subgroup.mk (additive G) _ _ (additive.is_add_submonoid _) (@is_subgroup.inv_mem _ _ _ _) theorem additive.is_add_subgroup_iff {s : set G} : @is_add_subgroup (additive G) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk G _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI additive.is_add_subgroup _⟩ lemma multiplicative.is_subgroup (s : set A) [is_add_subgroup s] : @is_subgroup (multiplicative A) _ s := @is_subgroup.mk (multiplicative A) _ _ (multiplicative.is_submonoid _) (@is_add_subgroup.neg_mem _ _ _ _) theorem multiplicative.is_subgroup_iff {s : set A} : @is_subgroup (multiplicative A) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk A _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI multiplicative.is_subgroup _⟩ @[to_additive add_group] instance subtype.group {s : set G} [is_subgroup s] : group s := { inv := λ x, ⟨(x:G)⁻¹, is_subgroup.inv_mem x.2⟩, mul_left_inv := λ x, subtype.eq $ mul_left_inv x.1, .. subtype.monoid } @[to_additive add_comm_group] instance subtype.comm_group {G : Type*} [comm_group G] {s : set G} [is_subgroup s] : comm_group s := { .. subtype.group, .. subtype.comm_monoid } @[simp, to_additive] lemma is_subgroup.coe_inv {s : set G} [is_subgroup s] (a : s) : ((a⁻¹ : s) : G) = a⁻¹ := rfl @[simp] lemma is_subgroup.coe_gpow {s : set G} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : G) = a ^ n := by induction n; simp [is_submonoid.coe_pow a] @[simp] lemma is_add_subgroup.gsmul_coe {s : set A} [is_add_subgroup s] (a : s) (n : ℤ) : ((gsmul n a : s) : A) = gsmul n a := by induction n; simp [is_add_submonoid.smul_coe a] attribute [to_additive gsmul_coe] is_subgroup.coe_gpow @[to_additive of_add_neg] theorem is_subgroup.of_div (s : set G) (one_mem : (1:G) ∈ s) (div_mem : ∀{a b:G}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s) : is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set A) (zero_mem : (0:A) ∈ s) (sub_mem : ∀{a b:A}, a ∈ s → b ∈ s → a - b ∈ s) : is_add_subgroup s := is_add_subgroup.of_add_neg s zero_mem (λ x y hx hy, sub_mem hx hy) @[to_additive] instance is_subgroup.inter (s₁ s₂ : set G) [is_subgroup s₁] [is_subgroup s₂] : is_subgroup (s₁ ∩ s₂) := { inv_mem := λ x hx, ⟨is_subgroup.inv_mem hx.1, is_subgroup.inv_mem hx.2⟩ } @[to_additive] instance is_subgroup.Inter {ι : Sort*} (s : ι → set G) [h : ∀ y : ι, is_subgroup (s y)] : is_subgroup (set.Inter s) := { inv_mem := λ x h, set.mem_Inter.2 $ λ y, is_subgroup.inv_mem (set.mem_Inter.1 h y) } @[to_additive is_add_subgroup_Union_of_directed] lemma is_subgroup_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set G) [∀ i, is_subgroup (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subgroup (⋃i, s i) := { inv_mem := λ a ha, let ⟨i, hi⟩ := set.mem_Union.1 ha in set.mem_Union.2 ⟨i, is_subgroup.inv_mem hi⟩, to_is_submonoid := is_submonoid_Union_of_directed s directed } def gpowers (x : G) : set G := set.range ((^) x : ℤ → G) def gmultiples (x : A) : set A := set.range (λ i, gsmul i x) attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : G) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : A) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : A} {s : set A} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative A) _ _ _ (multiplicative.is_subgroup _) lemma gpowers_subset {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : gpowers a ⊆ s := λ x hx, match x, hx with _, ⟨i, rfl⟩ := is_subgroup.gpow_mem h end lemma gmultiples_subset {a : A} {s : set A} [is_add_subgroup s] (h : a ∈ s) : gmultiples a ⊆ s := @gpowers_subset (multiplicative A) _ _ _ (multiplicative.is_subgroup _) h attribute [to_additive gmultiples_subset] gpowers_subset lemma mem_gpowers {a : G} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : A} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group G] (s : set G) [is_subgroup s] @[to_additive] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup theorem is_add_subgroup.sub_mem {A} [add_group A] (s : set A) [is_add_subgroup s] (a b : A) (ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s := is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb) section prio set_option default_priority 100 -- see Note [default priority] class normal_add_subgroup [add_group A] (s : set A) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : A, g + n - g ∈ s) @[to_additive normal_add_subgroup] class normal_subgroup [group G] (s : set G) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : G, g * n * g⁻¹ ∈ s) end prio @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group G] (s : set G) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } lemma additive.normal_add_subgroup [group G] (s : set G) [normal_subgroup s] : @normal_add_subgroup (additive G) _ s := @normal_add_subgroup.mk (additive G) _ _ (@additive.is_add_subgroup G _ _ _) (@normal_subgroup.normal _ _ _ _) theorem additive.normal_add_subgroup_iff [group G] {s : set G} : @normal_add_subgroup (additive G) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk G _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by exactI additive.normal_add_subgroup _⟩ lemma multiplicative.normal_subgroup [add_group A] (s : set A) [normal_add_subgroup s] : @normal_subgroup (multiplicative A) _ s := @normal_subgroup.mk (multiplicative A) _ _ (@multiplicative.is_subgroup A _ _ _) (@normal_add_subgroup.normal _ _ _ _) theorem multiplicative.normal_subgroup_iff [add_group A] {s : set A} : @normal_subgroup (multiplicative A) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk A _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by exactI multiplicative.normal_subgroup _⟩ namespace is_subgroup variable [group G] -- Normal subgroup properties @[to_additive] lemma mem_norm_comm {s : set G} [normal_subgroup s] {a b : G} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h @[to_additive] lemma mem_norm_comm_iff {s : set G} [normal_subgroup s] {a b : G} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ @[to_additive] def trivial (G : Type*) [group G] : set G := {1} @[simp, to_additive] lemma mem_trivial {g : G} : g ∈ trivial G ↔ g = 1 := mem_singleton_iff @[to_additive] instance trivial_normal : normal_subgroup (trivial G) := by refine {..}; simp [trivial] {contextual := tt} @[to_additive] lemma eq_trivial_iff {s : set G} [is_subgroup s] : s = trivial G ↔ (∀ x ∈ s, x = (1 : G)) := by simp only [set.ext_iff, is_subgroup.mem_trivial]; exact ⟨λ h x, (h x).1, λ h x, ⟨h x, λ hx, hx.symm ▸ is_submonoid.one_mem s⟩⟩ @[to_additive] instance univ_subgroup : normal_subgroup (@univ G) := by refine {..}; simp @[to_additive add_center] def center (G : Type*) [group G] : set G := {z | ∀ g, g * z = z * g} @[to_additive mem_add_center] lemma mem_center {a : G} : a ∈ center G ↔ ∀g, g * a = a * g := iff.rfl @[to_additive add_center_normal] instance center_normal : normal_subgroup (center G) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } @[to_additive add_normalizer] def normalizer (s : set G) : set G := {g : G | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s} @[to_additive normalizer_is_add_subgroup] instance normalizer_is_subgroup (s : set G) : is_subgroup (normalizer s) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) (hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } @[to_additive subset_add_normalizer] lemma subset_normalizer (s : set G) [is_subgroup s] : s ⊆ normalizer s := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] /-- Every subgroup is a normal subgroup of its normalizer -/ @[to_additive add_normal_in_add_normalizer] instance normal_in_normalizer (s : set G) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) := { one_mem := show (1 : G) ∈ s, from is_submonoid.one_mem _, mul_mem := λ a b ha hb, show (a * b : G) ∈ s, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ s, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup open is_mul_hom (map_mul) @[to_additive] def ker [group H] (f : G → H) : set G := preimage f (trivial H) @[to_additive] lemma mem_ker [group H] (f : G → H) {x : G} : x ∈ ker f ↔ f x = 1 := mem_trivial variables [group G] [group H] @[to_additive] lemma one_ker_inv (f : G → H) [is_group_hom f] {a b : G} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive] lemma one_ker_inv' (f : G → H) [is_group_hom f] {a b : G} (h : f (a⁻¹ * b) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, apply eq_of_inv_eq_inv, rw eq_inv_of_mul_eq_one h end @[to_additive] lemma inv_ker_one (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma inv_ker_one' (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a⁻¹ * b) = 1 := have (f a)⁻¹ * f b = 1, by rw [h, mul_left_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma one_iff_ker_inv (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive] lemma one_iff_ker_inv' (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a⁻¹ * b) = 1 := ⟨inv_ker_one' f, one_ker_inv' f⟩ @[to_additive] lemma inv_iff_ker (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ @[to_additive] lemma inv_iff_ker' (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a⁻¹ * b ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv' _ _ _ @[to_additive image_add_subgroup] instance image_subgroup (f : G → H) [is_group_hom f] (s : set G) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, map_mul f]⟩, one_mem := ⟨1, one_mem s, map_one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw map_inv f; simp *⟩ } @[to_additive range_add_subgroup] instance range_subgroup (f : G → H) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal @[to_additive] instance preimage (f : G → H) [is_group_hom f] (s : set H) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [map_mul f, map_one f, map_inv f, @inv_mem H _ s] {contextual:=tt} @[to_additive] instance preimage_normal (f : G → H) [is_group_hom f] (s : set H) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [map_mul f, map_inv f] {contextual:=tt}⟩ @[to_additive] instance normal_subgroup_ker (f : G → H) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial H) @[to_additive] lemma inj_of_trivial_ker (f : G → H) [is_group_hom f] (h : ker f = trivial G) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end @[to_additive] lemma trivial_ker_of_inj (f : G → H) [is_group_hom f] (h : function.injective f) : ker f = trivial G := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [map_one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.map_one f] {contextual := tt}) @[to_additive] lemma inj_iff_trivial_ker (f : G → H) [is_group_hom f] : function.injective f ↔ ker f = trivial G := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ @[to_additive] lemma trivial_ker_iff_eq_one (f : G → H) [is_group_hom f] : ker f = trivial G ↔ ∀ x, f x = 1 → x = 1 := by rw set.ext_iff; simp [ker]; exact ⟨λ h x hx, (h x).1 hx, λ h x, ⟨h x, λ hx, by rw [hx, map_one f]⟩⟩ end is_group_hom @[to_additive is_add_group_hom] instance subtype_val.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (subtype.val : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance coe.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (coe : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance subtype_mk.is_group_hom [group G] [group H] {s : set G} [is_subgroup s] (f : H → G) [is_group_hom f] (h : ∀ x, f x ∈ s) : is_group_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_monoid_hom f h } @[to_additive is_add_group_hom] instance set_inclusion.is_group_hom [group G] {s t : set G} [is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) := subtype_mk.is_group_hom _ _ /-- `subtype.val : set.range f → H` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`subtype.val : set.range f → H` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_subtype_val [monoid G] [monoid H] (f : G →* H) : (set.range f) →* H := monoid_hom.of subtype.val /-- `set.range_factorization f : G → set.range f` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`set.range_factorization f : G → set.range f` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_factorization [monoid G] [monoid H] (f : G →* H) : G →* (set.range f) := { to_fun := set.range_factorization f, map_one' := by { dsimp [set.range_factorization], simp, refl, }, map_mul' := by { intros, dsimp [set.range_factorization], simp, refl, } } namespace add_group variables [add_group A] inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | neg {a : A} : in_closure a → in_closure (-a) | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_group namespace group open is_submonoid is_subgroup variables [group G] {s : set G} @[to_additive] inductive in_closure (s : set G) : G → Prop | basic {a : G} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : G} : in_closure a → in_closure a⁻¹ | mul {a b : G} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ @[to_additive] def closure (s : set G) : set G := {a | in_closure s a } @[to_additive] lemma mem_closure {a : G} : a ∈ s → a ∈ closure s := in_closure.basic @[to_additive is_add_subgroup] instance closure.is_subgroup (s : set G) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } @[to_additive] theorem subset_closure {s : set G} : s ⊆ closure s := λ a, mem_closure @[to_additive] theorem closure_subset {s t : set G} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] @[to_additive] lemma closure_subset_iff (s t : set G) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t := ⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩ @[to_additive] theorem closure_mono {s t : set G} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure @[simp, to_additive closure_add_subgroup] lemma closure_subgroup (s : set G) [is_subgroup s] : closure s = s := set.subset.antisymm (closure_subset $ set.subset.refl s) subset_closure @[to_additive] theorem exists_list_of_mem_closure {s : set G} {a : G} (h : a ∈ closure s) : (∃l:list G, (∀x∈l, x ∈ s ∨ x⁻¹ ∈ s) ∧ l.prod = a) := in_closure.rec_on h (λ x hxs, ⟨[x], list.forall_mem_singleton.2 $ or.inl hxs, one_mul _⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x _ ⟨L, HL1, HL2⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, hy1, hy2⟩ := list.exists_of_mem_map hx in hy2 ▸ or.imp id (by rw [inv_inv]; exact id) (HL1 _ $ list.mem_reverse.1 hy1).symm, HL2 ▸ list.rec_on L one_inv.symm (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih, list.map_singleton, list.prod_cons, list.prod_nil, mul_one, list.prod_cons, mul_inv_rev])⟩) (λ x y hx hy ⟨L1, HL1, HL2⟩ ⟨L2, HL3, HL4⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL3⟩, by rw [list.prod_append, HL2, HL4]⟩) @[to_additive] lemma image_closure [group H] (f : G → H) [is_group_hom f] (s : set G) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_group_hom.map_inv f], apply is_subgroup.inv_mem, assumption }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) @[to_additive] theorem mclosure_subset {s : set G} : monoid.closure s ⊆ closure s := monoid.closure_subset $ subset_closure @[to_additive] theorem mclosure_inv_subset {s : set G} : monoid.closure (has_inv.inv ⁻¹' s) ⊆ closure s := monoid.closure_subset $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx) @[to_additive] theorem closure_eq_mclosure {s : set G} : closure s = monoid.closure (s ∪ has_inv.inv ⁻¹' s) := set.subset.antisymm (@closure_subset _ _ _ (monoid.closure (s ∪ has_inv.inv ⁻¹' s)) { inv_mem := λ x hx, monoid.in_closure.rec_on hx (λ x hx, or.cases_on hx (λ hx, monoid.subset_closure $ or.inr $ show x⁻¹⁻¹ ∈ s, from (inv_inv x).symm ▸ hx) (λ hx, monoid.subset_closure $ or.inl hx)) ((@one_inv G _).symm ▸ is_submonoid.one_mem _) (λ x y hx hy ihx ihy, (mul_inv_rev x y).symm ▸ is_submonoid.mul_mem ihy ihx) } (set.subset.trans (set.subset_union_left _ _) monoid.subset_closure)) (monoid.closure_subset $ set.union_subset subset_closure $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx)) @[to_additive] theorem mem_closure_union_iff {G : Type*} [comm_group G] {s t : set G} {x : G} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := begin simp only [closure_eq_mclosure, monoid.mem_closure_union_iff, exists_prop, preimage_union], split, { rintro ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨_, hys, _, hzs, rfl⟩, _, ⟨_, hyt, _, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm zs], refl }, { rintro ⟨_, ⟨ys, hys, zs, hzs, rfl⟩, _, ⟨yt, hyt, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm yt], refl } end @[to_additive gmultiples_eq_closure] theorem gpowers_eq_closure {a : G} : gpowers a = closure {a} := subset.antisymm (gpowers_subset $ mem_closure $ by simp) (closure_subset $ by simp [mem_gpowers]) end group namespace is_subgroup variable [group G] @[to_additive] lemma trivial_eq_closure : trivial G = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) end is_subgroup /-The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ namespace group variables {s : set G} [group G] /-- Given an element a, conjugates a is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set s, conjugates_of_set s is the set of all conjugates of the elements of s. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset {t : set G} [normal_subgroup t] {a : G} (h : a ∈ t) : conjugates a ⊆ t := λ x ⟨c,w⟩, begin have H := normal_subgroup.normal a h c, rwa ←w, end theorem conjugates_of_set_subset {s t : set G} [normal_subgroup t] (h : s ⊆ t) : conjugates_of_set s ⊆ t := set.bUnion_subset (λ x H, conjugates_subset (h H)) /-- The set of conjugates of s is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end /-- The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ def normal_closure (s : set G) : set G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of a set is a subgroup. -/ instance normal_closure.is_subgroup (s : set G) : is_subgroup (normal_closure s) := closure.is_subgroup (conjugates_of_set s) /-- The normal closure of s is a normal subgroup. -/ instance normal_closure.is_normal : normal_subgroup (normal_closure s) := ⟨ λ n h g, begin induction h with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx))}, {simpa using (normal_closure.is_subgroup s).one_mem}, {rw ←conj_inv, exact (is_subgroup.inv_mem ihx)}, {rw ←conj_mul, exact (is_submonoid.mul_mem ihx ihy)}, end ⟩ /-- The normal closure of s is the smallest normal subgroup containing s. -/ theorem normal_closure_subset {s t : set G} [normal_subgroup t] (h : s ⊆ t) : normal_closure s ⊆ t := λ a w, begin induction w with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset h $ hx)}, {exact is_submonoid.one_mem t}, {exact is_subgroup.inv_mem ihx}, {exact is_submonoid.mul_mem ihx ihy} end lemma normal_closure_subset_iff {s t : set G} [normal_subgroup t] : s ⊆ t ↔ normal_closure s ⊆ t := ⟨normal_closure_subset, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} : s ⊆ t → normal_closure s ⊆ normal_closure t := λ h, normal_closure_subset (set.subset.trans h (subset_normal_closure)) end group section simple_group class simple_group (G : Type*) [group G] : Prop := (simple : ∀ (N : set G) [normal_subgroup N], N = is_subgroup.trivial G ∨ N = set.univ) class simple_add_group (A : Type*) [add_group A] : Prop := (simple : ∀ (N : set A) [normal_add_subgroup N], N = is_add_subgroup.trivial A ∨ N = set.univ) attribute [to_additive simple_add_group] simple_group theorem additive.simple_add_group_iff [group G] : simple_add_group (additive G) ↔ simple_group G := ⟨λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.1 h)⟩⟩ instance additive.simple_add_group [group G] [simple_group G] : simple_add_group (additive G) := additive.simple_add_group_iff.2 (by apply_instance) theorem multiplicative.simple_group_iff [add_group A] : simple_group (multiplicative A) ↔ simple_add_group A := ⟨λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.1 h)⟩⟩ instance multiplicative.simple_group [add_group A] [simple_add_group A] : simple_group (multiplicative A) := multiplicative.simple_group_iff.2 (by apply_instance) @[to_additive simple_add_group_of_surjective] lemma simple_group_of_surjective [group G] [group H] [simple_group G] (f : G → H) [is_group_hom f] (hf : function.surjective f) : simple_group H := ⟨λ H iH, have normal_subgroup (f ⁻¹' H), by resetI; apply_instance, begin resetI, cases simple_group.simple (f ⁻¹' H) with h h, { refine or.inl (is_subgroup.eq_trivial_iff.2 (λ x hx, _)), cases hf x with y hy, rw ← hy at hx, rw [← hy, is_subgroup.eq_trivial_iff.1 h y hx, is_group_hom.map_one f] }, { refine or.inr (set.eq_univ_of_forall (λ x, _)), cases hf x with y hy, rw set.eq_univ_iff_forall at h, rw ← hy, exact h y } end⟩ end simple_group
dfbc4a1d8f3002eb22f6425eafb4e7985b321bf2
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/complex/isometry.lean
c20b7eb7f6ec9375e2fd6583cc6ff465c81b951a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
6,723
lean
/- Copyright (c) 2021 François Sunatori. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: François Sunatori -/ import analysis.complex.circle import linear_algebra.determinant import linear_algebra.matrix.general_linear_group /-! # Isometries of the Complex Plane The lemma `linear_isometry_complex` states the classification of isometries in the complex plane. Specifically, isometries with rotations but without translation. The proof involves: 1. creating a linear isometry `g` with two fixed points, `g(0) = 0`, `g(1) = 1` 2. applying `linear_isometry_complex_aux` to `g` The proof of `linear_isometry_complex_aux` is separated in the following parts: 1. show that the real parts match up: `linear_isometry.re_apply_eq_re` 2. show that I maps to either I or -I 3. every z is a linear combination of a + b * I ## References * [Isometries of the Complex Plane](http://helmut.knaust.info/mediawiki/images/b/b5/Iso.pdf) -/ noncomputable theory open complex open_locale complex_conjugate local notation (name := complex.abs) `|` x `|` := complex.abs x /-- An element of the unit circle defines a `linear_isometry_equiv` from `ℂ` to itself, by rotation. -/ def rotation : circle →* (ℂ ≃ₗᵢ[ℝ] ℂ) := { to_fun := λ a, { norm_map' := λ x, show |a * x| = |x|, by rw [map_mul, abs_coe_circle, one_mul], ..distrib_mul_action.to_linear_equiv ℝ ℂ a }, map_one' := linear_isometry_equiv.ext $ one_smul _, map_mul' := λ _ _, linear_isometry_equiv.ext $ mul_smul _ _ } @[simp] lemma rotation_apply (a : circle) (z : ℂ) : rotation a z = a * z := rfl @[simp] lemma rotation_symm (a : circle) : (rotation a).symm = rotation a⁻¹ := linear_isometry_equiv.ext $ λ x, rfl @[simp] lemma rotation_trans (a b : circle) : (rotation a).trans (rotation b) = rotation (b * a) := by { ext1, simp } lemma rotation_ne_conj_lie (a : circle) : rotation a ≠ conj_lie := begin intro h, have h1 : rotation a 1 = conj 1 := linear_isometry_equiv.congr_fun h 1, have hI : rotation a I = conj I := linear_isometry_equiv.congr_fun h I, rw [rotation_apply, ring_hom.map_one, mul_one] at h1, rw [rotation_apply, conj_I, ← neg_one_mul, mul_left_inj' I_ne_zero, h1, eq_neg_self_iff] at hI, exact one_ne_zero hI, end /-- Takes an element of `ℂ ≃ₗᵢ[ℝ] ℂ` and checks if it is a rotation, returns an element of the unit circle. -/ @[simps] def rotation_of (e : ℂ ≃ₗᵢ[ℝ] ℂ) : circle := ⟨(e 1) / complex.abs (e 1), by simp⟩ @[simp] lemma rotation_of_rotation (a : circle) : rotation_of (rotation a) = a := subtype.ext $ by simp lemma rotation_injective : function.injective rotation := function.left_inverse.injective rotation_of_rotation lemma linear_isometry.re_apply_eq_re_of_add_conj_eq (f : ℂ →ₗᵢ[ℝ] ℂ) (h₃ : ∀ z, z + conj z = f z + conj (f z)) (z : ℂ) : (f z).re = z.re := by simpa [ext_iff, add_re, add_im, conj_re, conj_im, ←two_mul, (show (2 : ℝ) ≠ 0, by simp [two_ne_zero])] using (h₃ z).symm lemma linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h₂ : ∀ z, (f z).re = z.re) (z : ℂ) : (f z).im = z.im ∨ (f z).im = -z.im := begin have h₁ := f.norm_map z, simp only [complex.abs_def, norm_eq_abs] at h₁, rwa [real.sqrt_inj (norm_sq_nonneg _) (norm_sq_nonneg _), norm_sq_apply (f z), norm_sq_apply z, h₂, add_left_cancel_iff, mul_self_eq_mul_self_iff] at h₁, end lemma linear_isometry.im_apply_eq_im {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : z + conj z = f z + conj (f z) := begin have : ‖f z - 1‖ = ‖z - 1‖ := by rw [← f.norm_map (z - 1), f.map_sub, h], apply_fun λ x, x ^ 2 at this, simp only [norm_eq_abs, ←norm_sq_eq_abs] at this, rw [←of_real_inj, ←mul_conj, ←mul_conj] at this, rw [ring_hom.map_sub, ring_hom.map_sub] at this, simp only [sub_mul, mul_sub, one_mul, mul_one] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs, linear_isometry.norm_map] at this, rw [mul_conj, norm_sq_eq_abs, ←norm_eq_abs] at this, simp only [sub_sub, sub_right_inj, mul_one, of_real_pow, ring_hom.map_one, norm_eq_abs] at this, simp only [add_sub, sub_left_inj] at this, rw [add_comm, ←this, add_comm], end lemma linear_isometry.re_apply_eq_re {f : ℂ →ₗᵢ[ℝ] ℂ} (h : f 1 = 1) (z : ℂ) : (f z).re = z.re := begin apply linear_isometry.re_apply_eq_re_of_add_conj_eq, intro z, apply linear_isometry.im_apply_eq_im h, end lemma linear_isometry_complex_aux {f : ℂ ≃ₗᵢ[ℝ] ℂ} (h : f 1 = 1) : f = linear_isometry_equiv.refl ℝ ℂ ∨ f = conj_lie := begin have h0 : f I = I ∨ f I = -I, { have : |f I| = 1 := by simpa using f.norm_map complex.I, simp only [ext_iff, ←and_or_distrib_left, neg_re, I_re, neg_im, neg_zero], split, { rw ←I_re, exact @linear_isometry.re_apply_eq_re f.to_linear_isometry h I, }, { apply @linear_isometry.im_apply_eq_im_or_neg_of_re_apply_eq_re f.to_linear_isometry, intro z, rw @linear_isometry.re_apply_eq_re f.to_linear_isometry h } }, refine h0.imp (λ h' : f I = I, _) (λ h' : f I = -I, _); { apply linear_isometry_equiv.to_linear_equiv_injective, apply complex.basis_one_I.ext', intros i, fin_cases i; simp [h, h'] } end lemma linear_isometry_complex (f : ℂ ≃ₗᵢ[ℝ] ℂ) : ∃ a : circle, f = rotation a ∨ f = conj_lie.trans (rotation a) := begin let a : circle := ⟨f 1, by simpa using f.norm_map 1⟩, use a, have : (f.trans (rotation a).symm) 1 = 1, { simpa using rotation_apply a⁻¹ (f 1) }, refine (linear_isometry_complex_aux this).imp (λ h₁, _) (λ h₂, _), { simpa using eq_mul_of_inv_mul_eq h₁ }, { exact eq_mul_of_inv_mul_eq h₂ } end /-- The matrix representation of `rotation a` is equal to the conformal matrix `!![re a, -im a; im a, re a]`. -/ lemma to_matrix_rotation (a : circle) : linear_map.to_matrix basis_one_I basis_one_I (rotation a).to_linear_equiv = matrix.plane_conformal_matrix (re a) (im a) (by simp [pow_two, ←norm_sq_apply]) := begin ext i j, simp [linear_map.to_matrix_apply], fin_cases i; fin_cases j; simp end /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (a : circle) : ((rotation a).to_linear_equiv : ℂ →ₗ[ℝ] ℂ).det = 1 := begin rw [←linear_map.det_to_matrix basis_one_I, to_matrix_rotation, matrix.det_fin_two], simp [←norm_sq_apply] end /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (a : circle) : (rotation a).to_linear_equiv.det = 1 := by rw [←units.eq_iff, linear_equiv.coe_det, det_rotation, units.coe_one]
2f8680362d7106122e0db491db0b82c0677bc007
8f209eb34c0c4b9b6be5e518ebfc767a38bed79c
/code/src/internal/phi/utils.lean
e4cbb9d4497bf647e942f1eeb39d36592b13c632
[]
no_license
hediet/masters-thesis
13e3bcacb6227f25f7ec4691fb78cb0363f2dfb5
dc40c14cc4ed073673615412f36b4e386ee7aac9
refs/heads/master
1,680,591,056,302
1,617,710,887,000
1,617,710,887,000
311,762,038
4
0
null
null
null
null
UTF-8
Lean
false
false
2,427
lean
import tactic import ...definitions import data.finset meta def stable_macro: tactic unit := `[ rw stable, assume ty1 ty2 h, ext env, simp [Φ.eval, h] ] variable [GuardModule] open GuardModule def stable (f: Φ → Φ) := ∀ ty1 ty2: Φ, (ty1.eval = ty2.eval) → (f ty1).eval = (f ty2).eval lemma stable.id: stable id := by simp [stable] lemma stable.and_left { ty: Φ }: stable (λ ty', ty'.and ty) := by stable_macro lemma stable.and_right { ty: Φ }: stable ty.and := by stable_macro lemma stable.or_right { ty: Φ }: stable ty.or := by stable_macro lemma stable.tgrd_in (tgrd: TGrd): stable (Φ.tgrd_in tgrd) := by stable_macro lemma stable.app { f: Φ → Φ } (f_stable: stable f) { ty1 ty2: Φ } (h: ty1.eval = ty2.eval): (f ty1).eval = (f ty2).eval := by finish [stable] lemma stable.comp { f1 f2: Φ → Φ } (f1_stable: stable f1) (f2_stable: stable f2): stable (f1 ∘ f2) := by finish [stable] def hom (f: Φ → Φ) := (∀ ty1 ty2: Φ, (f (ty1.or ty2)).eval = ((f ty1).or (f ty2)).eval ∧ (f (ty1.and ty2)).eval = ((f ty1).and (f ty2)).eval) ∧ (f Φ.false).eval = Φ.false.eval lemma hom.id: hom id := by simp [hom] lemma hom.and_right { ty: Φ }: hom ty.and := begin rw hom, split, { assume ty1 ty2, split; ext env; cases c1: ty.eval env; cases c2: ty1.eval env; cases c3: ty2.eval env; simp [*, Φ.eval], }, cases ty; ext env; simp [Φ.eval], end lemma hom.tgrd_in (grd: TGrd): hom (Φ.tgrd_in grd) := begin rw hom, split, { assume ty1 ty2, split; ext env; cases c: tgrd_eval grd env; simp [*, Φ.eval], }, ext env; cases c: tgrd_eval grd env; simp [Φ.eval, Φ.eval._match_1, c], end lemma hom.comp { f1 f2: Φ → Φ } (f1_hom: hom f1) (f1_stable: stable f1) (f2_hom: hom f2) (f2_stable: stable f2): hom (f1 ∘ f2) := begin unfold hom, split, { assume ty1 ty2, unfold function.comp, have h1: (f2 (ty1.or ty2)).eval = ((f2 ty1).or (f2 ty2)).eval := by simp [f2_hom.1 _ _], have h2: (f2 (ty1.and ty2)).eval = ((f2 ty1).and (f2 ty2)).eval := by simp [f2_hom.1 _ _], rw stable.app f1_stable h1, rw stable.app f1_stable h2, rw (f1_hom.1 _ _).1, rw (f1_hom.1 _ _).2, simp, }, simp [f1_stable _ _ f2_hom.2, f1_hom.2], end
a8cb458e074b7b269f631c8132a94a583cff73a4
94935fb4ab68d4ce640296d02911624a93282575
/src/hints/thursday/afternoon/category_theory/exercise18/hint2.lean
3ca3ce5a3362f966df1977e48dc6f5534ed151a9
[]
permissive
marius-leonhardt/lftcm2020
41c0d7fe3457c1cf3b72cbb1c312b48fc94b85d2
a3eb53f18d9be9a5be748dfe8fe74d0d31a0c1f7
refs/heads/master
1,668,623,789,936
1,594,710,949,000
1,594,710,949,000
279,514,936
0
0
MIT
1,594,711,916,000
1,594,711,916,000
null
UTF-8
Lean
false
false
1,324
lean
import category_theory.limits.shapes.pullbacks /-! Thanks to Markus Himmel for suggesting this question. -/ open category_theory open category_theory.limits /-! Let C be a category, X and Y be objects and f : X ⟶ Y be a morphism. Show that f is an epimorphism if and only if the diagram X --f--→ Y | | f 𝟙 | | ↓ ↓ Y --𝟙--→ Y is a pushout. -/ universes v u variables {C : Type u} [category.{v} C] def pushout_of_epi {X Y : C} (f : X ⟶ Y) [epi f] : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) := -- Hint: you can start a proof with `fapply pushout_cocone.is_colimit.mk` -- to save a little bit of work over just building a `is_colimit` structure directly. begin fapply pushout_cocone.is_colimit.mk, { intro s, apply s.ι.app walking_span.left, }, { tidy, }, { tidy, /- we clearly need to use that `f` is an epi here!-/ sorry }, { tidy, specialize w walking_span.left, tidy, } end theorem epi_of_pushout {X Y : C} (f : X ⟶ Y) (is_colim : is_colimit (pushout_cocone.mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f := { left_cancellation := λ Z g h hf, begin let a := pushout_cocone.mk _ _ hf, have hg : is_colim.desc a = g, sorry, have hh : is_colim.desc a = h, sorry, rw [←hg, ←hh], end }
8b91e5242255941c0119a19e3f0bed4eb19ff8ed
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/1315b.lean
f4cad702ab827d92d1e3bb4e18c309aaf763aade
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,239
lean
open nat def k : ℕ := 0 def fails : Π (n : ℕ) (m : ℕ), ℕ | 0 m := 0 | (succ n) m := match k with | 0 := 0 | (succ i) := let val := m+1 in match fails n val with | 0 := 0 | (succ l) := 0 end end def test (k : ℕ) : Π (n : ℕ) (m : ℕ), ℕ | 0 m := 0 | (succ n) m := match k with | 0 := 1 | (succ i) := let val := m+1 in match test n val with | 0 := 2 | (succ l) := 3 end end example (k m : ℕ) : test k 0 m = 0 := rfl example (m n : ℕ) : test 0 (succ n) m = 1 := rfl example (k m : ℕ) : test (succ k) 1 m = 2 := rfl example (k m : ℕ) : test (succ k) 2 m = 3 := rfl example (k m : ℕ) : test (succ k) 3 m = 3 := rfl open tactic meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (expr.alpha_eqv t e) meta def check_target (p : pexpr) : tactic unit := do t ← target, check_expr p t run_cmd do t ← to_expr `(test._match_2) >>= infer_type, trace t, check_expr `(nat → nat) t example (k m n : ℕ) : test (succ k) (succ (succ n)) m = 3 := begin revert m, induction n with n', {intro, reflexivity}, {intro, simp [test] {zeta := ff}, dsimp, simp [ih_1], simp [nat.bit1_eq_succ_bit0, test]} end
17adcd3f8054e6789da4ad79265bebc17540ca2e
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/measure_theory/integration.lean
4db136f0419d466f17cb9078f80eae57d2a9bd0a
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
54,754
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances measure_theory.measure_space measure_theory.borel_space noncomputable theory open lattice set filter open_locale classical topological_space section sequence_of_directed variables {α : Type*} {β : Type*} [encodable α] [inhabited α] open encodable noncomputable def sequence_of_directed (r : β → β → Prop) (f : α → β) (hf : directed r f) : ℕ → α | 0 := default α | (n + 1) := let p := sequence_of_directed n in match decode α n with | none := p | (some a) := classical.some (hf p a) end lemma monotone_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) : monotone (f ∘ sequence_of_directed (≤) f hf) := monotone_of_monotone_nat $ assume n, begin dsimp [sequence_of_directed], generalize eq : sequence_of_directed (≤) f hf n = p, cases h : decode α n with a, { refl }, { exact (classical.some_spec (hf p a)).1 } end lemma le_sequence_of_directed [partial_order β] (f : α → β) (hf : directed (≤) f) (a : α) : f a ≤ f (sequence_of_directed (≤) f hf (encode a + 1)) := begin simp [sequence_of_directed, -add_comm, encodek], exact (classical.some_spec (hf _ a)).2 end end sequence_of_directed namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H protected def range (f : α →ₛ β) := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := iff.intro (by simp [set.eq_empty_iff_forall_not_mem, mem_range]) (by simp [set.eq_empty_iff_forall_not_mem, mem_range]) def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measurable_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], exact ⟨assume ⟨_, h⟩, h.symm, assume h, ne.elim $ λa, ⟨a, h.symm⟩⟩ end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨_, ⟨a, rfl⟩, h, rfl⟩, λ ⟨_, ⟨a', rfl⟩, h', e⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨_, ⟨a, rfl⟩, _, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp [preimage]; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp only [mem_range, exists_prop, mem_range, finset.mem_image, map_apply], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = (⋃b∈f.range.filter (λb, g b ∈ s), f ⁻¹' {b}) := begin /- True because `f` only takes finitely many values. -/ ext a', simp only [mem_Union, set.mem_preimage, exists_prop, set.mem_preimage, map_apply, finset.mem_filter, mem_range, mem_singleton_iff, exists_eq_right'], split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } end lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = (⋃b∈f.range.filter (λb, g b = c), f ⁻¹' {b}) := begin rw map_preimage, have : (λb, g b = c) = λb, g b ∈ _root_.singleton c, funext, rw [eq_iff_iff, mem_singleton_iff], rw this end def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← prod_singleton_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := { add_comm := λ f g, ext (λa, add_comm _ _), .. simple_func.add_monoid } instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ instance [add_group β] : add_group (α →ₛ β) := { neg := has_neg.neg, add_left_neg := λf, ext (λa, add_left_neg _), .. simple_func.add_monoid } instance [add_comm_group β] : add_comm_group (α →ₛ β) := { add_comm := λ f g, ext (λa, add_comm _ _) , .. simple_func.add_group } variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map (λb, k • b)⟩ instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := { one_smul := λ f, ext (λa, one_smul _ _), mul_smul := λ x y f, ext (λa, mul_smul _ _ _), smul_add := λ r f g, ext (λa, smul_add _ _ _), smul_zero := λ r, ext (λa, smul_zero _), add_smul := λ r s f, ext (λa, add_smul _ _ _), zero_smul := λ f, ext (λa, zero_smul _ _) } instance [ring K] [add_comm_group β] [module K β] : module K (α →ₛ β) := { .. simple_func.semimodule } instance [discrete_field K] [add_comm_group β] [module K β] : vector_space K (α →ₛ β) := { .. simple_func.module } lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map (λb, k • b) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice.lattice, .. simple_func.lattice.order_bot, .. simple_func.lattice.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [semilattice_sup_bot β] [has_zero β] def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [ordered_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [ordered_topology β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : _root_.measurable f) (hg : _root_.measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [ordered_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : _root_.measurable f) (hg : _root_.measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measure_space α] lemma volume_bUnion_preimage (s : finset β) (f : α →ₛ β) : volume (⋃b ∈ s, f ⁻¹' {b}) = s.sum (λb, volume (f ⁻¹' {b})) := begin /- Taking advantage of the fact that `f ⁻¹' {b}` are disjoint for `b ∈ s`. -/ rw [volume_bUnion_finset], { simp only [pairwise_on, (on), finset.mem_coe, ne.def], rintros _ _ _ _ ne _ ⟨h₁, h₂⟩, simp only [mem_singleton_iff, mem_preimage] at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end /-- Integral of a simple function whose codomain is `ennreal`. -/ def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, volume_bUnion_preimage, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h } end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0) : (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_exists_mem.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : {a | f a = g a} ∈ (@measure_space.μ α _).a_e) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end lemma integral_map {β} [measure_space β] (f : α →ₛ ennreal) (g : β →ₛ ennreal)(m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → volume s = volume (m ⁻¹' s)) : f.integral = g.integral := have f_eq : (f : α → ennreal) = g ∘ m := funext eq, have vol_f : ∀r, volume (f ⁻¹' {r}) = volume (g ⁻¹' {r}), by { assume r, rw [h, f_eq, preimage_comp], exact measurable_sn _ _ }, begin simp [integral, vol_f], refine finset.sum_subset _ _, { simp [finset.subset_iff, f_eq], rintros r a rfl, exact ⟨_, rfl⟩ }, { assume r hrg hrf, rw [simple_func.mem_range, not_exists] at hrf, have : f ⁻¹' {r} = ∅ := set.eq_empty_of_subset_empty (assume a, by simpa using hrf a), simp [(vol_f _).symm, this] } end end measure section fin_vol_supp variables [measure_space α] [has_zero β] [has_zero γ] open finset ennreal protected def fin_vol_supp (f : α →ₛ β) : Prop := ∀b ≠ 0, volume (f ⁻¹' {b}) < ⊤ lemma fin_vol_supp_map {f : α →ₛ β} {g : β → γ} (hf : f.fin_vol_supp) (hg : g 0 = 0) : (f.map g).fin_vol_supp := begin assume c hc, simp only [map_preimage, volume_bUnion_preimage], apply sum_lt_top, intro b, simp only [mem_filter, mem_range, mem_singleton_iff, and_imp, exists_imp_distrib], intros a fab gbc, apply hf, intro b0, rw [b0, hg] at gbc, rw gbc at hc, contradiction end lemma fin_vol_supp_of_fin_vol_supp_map (f : α →ₛ β) {g : β → γ} (h : (f.map g).fin_vol_supp) (hg : ∀b, g b = 0 → b = 0) : f.fin_vol_supp := begin assume b hb, by_cases b_mem : b ∈ f.range, { have gb0 : g b ≠ 0, { assume h, have := hg b h, contradiction }, have : f ⁻¹' {b} ⊆ (f.map g) ⁻¹' {g b}, rw [coe_map, @preimage_comp _ _ _ f g, preimage_subset_preimage_iff], { simp only [set.mem_preimage, set.mem_singleton, set.singleton_subset_iff] }, { rw singleton_subset_iff, rw mem_range at b_mem, exact b_mem }, exact lt_of_le_of_lt (volume_mono this) (h (g b) gb0) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, volume_empty], exact with_top.zero_lt_top } end lemma fin_vol_supp_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_vol_supp) (hg : g.fin_vol_supp) : (pair f g).fin_vol_supp := begin rintros ⟨b, c⟩ hbc, rw [pair_preimage_singleton], rw [ne.def, prod.eq_iff_fst_eq_snd_eq, not_and_distrib] at hbc, refine or.elim hbc (λ h : b≠0, _) (λ h : c≠0, _), { calc _ ≤ volume (f ⁻¹' {b}) : volume_mono (set.inter_subset_left _ _) ... < ⊤ : hf _ h }, { calc _ ≤ volume (g ⁻¹' {c}) : volume_mono (set.inter_subset_right _ _) ... < ⊤ : hg _ h }, end lemma integral_lt_top_of_fin_vol_supp {f : α →ₛ ennreal} (h₁ : ∀ₘ a, f a < ⊤) (h₂ : f.fin_vol_supp) : integral f < ⊤ := begin rw integral, apply sum_lt_top, intros a ha, have : f ⁻¹' {⊤} = -{a : α | f a < ⊤}, { ext, simp }, have vol_top : volume (f ⁻¹' {⊤}) = 0, { rw [this, volume, ← measure.mem_a_e_iff], exact h₁ }, by_cases hat : a = ⊤, { rw [hat, vol_top, mul_zero], exact with_top.zero_lt_top }, { by_cases haz : a = 0, { rw [haz, zero_mul], exact with_top.zero_lt_top }, apply mul_lt_top, { rw ennreal.lt_top_iff_ne_top, exact hat }, apply h₂, exact haz } end lemma fin_vol_supp_of_integral_lt_top {f : α →ₛ ennreal} (h : integral f < ⊤) : f.fin_vol_supp := begin assume b hb, rw [integral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, volume_empty], exact with_top.zero_lt_top } end /-- A technical lemma dealing with the definition of `integrable` in `l1_space.lean`. -/ lemma integral_map_coe_lt_top {f : α →ₛ β} {g : β → nnreal} (h : f.fin_vol_supp) (hg : g 0 = 0) : integral (f.map ((coe : nnreal → ennreal) ∘ g)) < ⊤ := integral_lt_top_of_fin_vol_supp (by { filter_upwards[], assume a, simp only [mem_set_of_eq, map_apply], exact ennreal.coe_lt_top}) (by { apply fin_vol_supp_map h, simp only [hg, function.comp_app, ennreal.coe_zero] }) end fin_vol_supp end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases {a | s a ≠ ⊤} ∈ (@measure_space.μ α _).a_e, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure.a_e, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable_add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, s.sum (λb, f b a)) = s.sum (λb, ∫⁻ a, f b a) := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp [has], rw [lintegral_add (hf _) (measurable_finset_sum s hf), ih] } end lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a) ≤ (∫⁻ a, r * f a) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_integral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs] end lemma lintegral_le_lintegral_ae {f g : α → ennreal} (h : ∀ₘ a, f a ≤ g a) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : - t ∈ (@measure_space.μ α _).a_e, { rw [measure.mem_a_e_iff, lattice.neg_neg, ht0] }, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict (- t)) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, simple_func.restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (s.integral_congr _ _), filter_upwards [this], refine assume a hnt, _, by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : ∀ₘ a, f a = g a) : (∫⁻ a, f a) = (∫⁻ a, g a) := le_antisymm (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h) (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h.symm) -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : ∀ₘ a, f a = f' a) (g : β → ennreal) : (∫⁻ a, g (f a)) = (∫⁻ a, g (f' a)) := begin apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h end -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : ∀ₘ a, f₁ a = f₁' a) (h₂ : ∀ₘ a, f₂ a = f₂' a) (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a)) = (∫⁻ a, g (f₁' a) (f₂' a)) := begin apply lintegral_congr_ae, filter_upwards [h₁, h₂], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h } end lemma simple_func.lintegral_map (f : α →ₛ β) (g : β → ennreal) : (∫⁻ a, (f.map g) a) = ∫⁻ a, g (f a) := by { apply lintegral_congr_ae, filter_upwards [], assume a, exact map_apply _ _ _ } lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : lintegral f = 0 ↔ (∀ₘ a, f a = 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ₘ a, f a < n⁻¹, { assume n, have : is_measurable {a : α | f a ≥ n⁻¹ }, { exact hf _ (is_measurable_of_is_closed $ is_closed_ge' _) }, have : (n : ennreal)⁻¹ * volume {a | f a ≥ n⁻¹ } = 0, { rw [← simple_func.restrict_const_integral _ _ this, ← le_zero_iff_eq, ← simple_func.lintegral_eq_integral], refine le_trans (lintegral_le_lintegral _ _ _) (le_of_eq h), assume a, by_cases h : (n : ennreal)⁻¹ ≤ f a; simp [h, (≥), this] }, rw [ennreal.mul_eq_zero, ennreal.inv_eq_zero] at this, simpa [ennreal.nat_ne_top, all_ae_iff] using this }, filter_upwards [all_ae_all_iff.2 this], dsimp, assume a ha, by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc lintegral f = lintegral (λa:α, 0) : lintegral_congr_ae h ... = 0 : lintegral_zero } end /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ₘ a, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (all_ae_iff.1 (all_ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ₘ a, ∀n, g n a = f n a, begin have := hs.2.2, rw [← compl_compl s] at this, filter_upwards [(measure.mem_a_e_iff (-s)).2 this] assume a ha n, if_neg ha end, calc (∫⁻ a, ⨆n, f n a) = (∫⁻ a, ⨆n, g n a) : lintegral_congr_ae begin filter_upwards [g_eq_f], assume a ha, congr, funext, exact (ha n).symm end ... = ⨆n, (∫⁻ a, g n a) : lintegral_supr (assume n, measurable.if hs.2.1 measurable_const (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a) : begin congr, funext, apply lintegral_congr_ae, filter_upwards [g_eq_f] assume a ha, ha n end lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : lintegral g < ⊤) (h_le : ∀ₘ a, g a ≤ f a) : (∫⁻ a, f a - g a) = (∫⁻ a, f a) - (∫⁻ a, g a) := begin rw [← ennreal.add_right_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_le_lintegral_ae h_le), ← lintegral_add (ennreal.measurable_sub hf hg) hg], show (∫⁻ (a : α), f a - g a + g a) = ∫⁻ (a : α), f a, apply lintegral_congr_ae, filter_upwards [h_le], simp only [add_comm, mem_set_of_eq], assume a ha, exact ennreal.add_sub_cancel_of_le ha end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, ∀ₘ a, f n.succ a ≤ f n a) (h_fin : lintegral (f 0) < ⊤) : (∫⁻ a, ⨅n, f n a) = (⨅n, ∫⁻ a, f n a) := have fn_le_f0 : (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0), from lintegral_le_lintegral _ _ (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a) ≤ lintegral (f 0), from infi_le_of_le 0 (le_refl _), (ennreal.sub_left_inj h_fin fn_le_f0 fn_le_f0').1 $ show lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = lintegral (f 0) - (⨅n, ∫⁻ a, f n a), from calc lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = ∫⁻ a, f 0 a - ⨅n, f n a : (lintegral_sub (h_meas 0) (measurable.infi h_meas) (calc (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0) : lintegral_le_lintegral _ _ (assume a, infi_le _ _) ... < ⊤ : h_fin ) (all_ae_of_all $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a : lintegral_supr_ae (assume n, ennreal.measurable_sub (h_meas 0) (h_meas n)) (assume n, by filter_upwards [h_mono n] assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, lintegral (f 0) - ∫⁻ a, f n a : have h_mono : ∀ₘ a, ∀n:ℕ, f n.succ a ≤ f n a := all_ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ₘa, f n a ≤ f 0 a := assume n, begin filter_upwards [h_mono], simp only [mem_set_of_eq], assume a, assume h, induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc (∫⁻ a, f n a) ≤ ∫⁻ a, f 0 a : lintegral_le_lintegral_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = lintegral (f 0) - (⨅n, ∫⁻ a, f n a) : ennreal.sub_infi.symm section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : (∫⁻ a, liminf at_top (λ n, f n a)) ≤ liminf at_top (λ n, lintegral (f n)) := calc (∫⁻ a, liminf at_top (λ n, f n a)) = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a : congr rfl (funext (assume a, liminf_eq_supr_infi_of_nat)) ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a : lintegral_supr begin assume n, apply measurable.infi, assume i, by_cases h : i ≥ n, {convert h_meas i, simp [h]}, {convert measurable_const, simp [h]} end begin assume n m hnm a, simp only [le_infi_iff], assume i hi, refine infi_le_of_le i (infi_le_of_le (le_trans hnm hi) (le_refl _)) end ... ≤ ⨆n:ℕ, ⨅i≥n, lintegral (f i) : supr_le_supr $ assume n, le_infi $ assume i, le_infi $ assume hi, lintegral_le_lintegral _ _ $ assume a, infi_le_of_le i $ infi_le_of_le hi $ le_refl _ ... = liminf at_top (λ n, lintegral (f n)) : liminf_eq_supr_infi_of_nat.symm end priority lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, ∀ₘa, f n a ≤ g a) (h_fin : lintegral g < ⊤) : limsup at_top (λn, lintegral (f n)) ≤ ∫⁻ a, limsup at_top (λn, f n a) := calc limsup at_top (λn, lintegral (f n)) = ⨅n:ℕ, ⨆i≥n, lintegral (f i) : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a : infi_le_infi $ assume n, supr_le $ assume i, supr_le $ assume hi, lintegral_le_lintegral _ _ $ assume a, le_supr_of_le i $ le_supr_of_le hi (le_refl _) ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a : (lintegral_infi_ae (assume n, @measurable.supr _ _ _ _ _ _ _ _ _ (λ i a, supr (λ (h : i ≥ n), f i a)) (assume i, measurable.supr_Prop (hf_meas i))) (assume n, all_ae_of_all $ assume a, begin simp only [supr_le_iff], assume i hi, refine le_supr_of_le i _, rw [supr_pos _], exact le_refl _, exact nat.le_of_succ_le hi end ) (lt_of_le_of_lt (lintegral_le_lintegral_ae begin filter_upwards [all_ae_all_iff.2 h_bound], simp only [supr_le_iff, mem_set_of_eq], assume a ha i hi, exact ha i end ) h_fin)).symm ... = ∫⁻ a, limsup at_top (λn, f n a) : lintegral_congr_ae $ all_ae_of_all $ assume a, limsup_eq_infi_supr_of_nat.symm /-- Dominated convergence theorem for nonnegative functions -/ lemma dominated_convergence_nn {F : ℕ → α → ennreal} {f : α → ennreal} {g : α → ennreal} (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, ∀ₘ a, F n a ≤ g a) (h_fin : lintegral g < ⊤) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, lintegral (F n)) at_top (𝓝 (lintegral f)) := begin have limsup_le_lintegral := calc limsup at_top (λ (n : ℕ), lintegral (F n)) ≤ ∫⁻ (a : α), limsup at_top (λn, F n a) : limsup_lintegral_le hF_meas h_bound h_fin ... = lintegral f : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, limsup_eq_of_tendsto at_top_ne_bot h, have lintegral_le_liminf := calc lintegral f = ∫⁻ (a : α), liminf at_top (λ (n : ℕ), F n a) : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, (liminf_eq_of_tendsto at_top_ne_bot h).symm ... ≤ liminf at_top (λ n, lintegral (F n)) : lintegral_liminf_le hF_meas, have liminf_eq_limsup := le_antisymm (liminf_le_limsup (map_ne_bot at_top_ne_bot)) (le_trans limsup_le_lintegral lintegral_le_liminf), have liminf_eq_lintegral : liminf at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm (by convert limsup_le_lintegral) lintegral_le_liminf, have limsup_eq_lintegral : limsup at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm limsup_le_lintegral begin convert lintegral_le_liminf, exact liminf_eq_limsup.symm end, exact tendsto_of_liminf_eq_limsup ⟨liminf_eq_lintegral, limsup_eq_lintegral⟩ end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : (∫⁻ a, ⨆b, f b a) = (⨆b, ∫⁻ a, f b a) := begin by_cases hβ : ¬ nonempty β, { have : ∀f : β → ennreal, (⨆(b : β), f b) = 0 := assume f, supr_eq_bot.2 (assume b, (hβ ⟨b⟩).elim), simp [this] }, cases of_not_not hβ with b, haveI iβ : inhabited β := ⟨b⟩, clear hβ b, have : ∀a, (⨆ b, f b a) = (⨆ n, f (sequence_of_directed (≤) f h_directed n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (le_sequence_of_directed f h_directed b a) }, calc (∫⁻ a, ⨆ b, f b a) = (∫⁻ a, ⨆ n, f (sequence_of_directed (≤) f h_directed n) a) : by simp only [this] ... = (⨆ n, ∫⁻ a, f (sequence_of_directed (≤) f h_directed n) a) : lintegral_supr (assume n, hf _) (monotone_sequence_of_directed f h_directed) ... = (⨆ b, ∫⁻ a, f b a) : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, lintegral (f b)) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_le_lintegral _ _ $ le_sequence_of_directed f h_directed b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (∫⁻ a, ∑ i, f i a) = (∑ i, ∫⁻ a, f i a) := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact measurable_finset_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end end lintegral namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f variables [measurable_space α] {m : measure α} @[simp] lemma integral_zero : m.integral (λa, 0) = 0 := @lintegral_zero α { μ := m } lemma integral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : (map g m).integral f = m.integral (f ∘ g) := begin rw [integral, integral, lintegral_eq_supr_eapprox_integral, lintegral_eq_supr_eapprox_integral], { congr, funext n, symmetry, apply simple_func.integral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, exact hf.comp hg, assumption end lemma integral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : (dirac a).integral f = f a := have ∀f:α →ₛ ennreal, @simple_func.integral α {μ := dirac a} f = f a, begin assume f, have : ∀r, @volume α { μ := dirac a } (⇑f ⁻¹' {r}) = ⨆ h : f a = r, 1, { assume r, transitivity, apply dirac_apply, apply simple_func.measurable_sn, refine supr_congr_Prop _ _; simp }, transitivity, apply finset.sum_eq_single (f a), { assume b hb h, simp [this, ne.symm h], }, { assume h, simp at h, exact (h a rfl).elim }, { rw [this], simp } end, begin rw [integral, lintegral_eq_supr_eapprox_integral], { simp [this, simple_func.supr_eapprox_apply f hf] }, assumption end def with_density (m : measure α) (f : α → ennreal) : measure α := if hf : measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) (by simp) begin assume s hs hd, have : ∀a, (⨆ (h : a ∈ ⋃i, s i), f a) = (∑i, (⨆ (h : a ∈ s i), f a)), { assume a, by_cases ha : ∃j, a ∈ s j, { rcases ha with ⟨j, haj⟩, have : ∀i, a ∈ s i ↔ j = i := assume i, iff.intro (assume hai, by_contradiction $ assume hij, hd j i hij ⟨haj, hai⟩) (by rintros rfl; assumption), simp [this, ennreal.tsum_supr_eq] }, { have : ∀i, ¬ a ∈ s i, { simpa using ha }, simp [this] } }, simp only [this], apply lintegral_tsum, { assume i, simp [supr_eq_if], exact measurable.if (hs i) hf measurable_const } end else 0 lemma with_density_apply {m : measure α} {f : α → ennreal} {s : set α} (hf : measurable f) (hs : is_measurable s) : m.with_density f s = m.integral (λa, ⨆(h : a ∈ s), f a) := by rw [with_density, dif_pos hf]; exact measure.of_measurable_apply s hs end measure end measure_theory
b07515d96a9cfa1df3bbed412858f035e45edb63
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/rbtree/find_auto.lean
dc1982c4bf5bdb599f95416310c2747dc07162ea
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,613
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.rbtree.basic universes u namespace Mathlib namespace rbnode theorem find.induction {α : Type u} {p : rbnode α → Prop} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) (x : α) (h₁ : p leaf) (h₂ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.lt → p l → p (red_node l y r)) (h₃ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.eq → p (red_node l y r)) (h₄ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.gt → p r → p (red_node l y r)) (h₅ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.lt → p l → p (black_node l y r)) (h₆ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.eq → p (black_node l y r)) (h₇ : ∀ (l : rbnode α) (y : α) (r : rbnode α), cmp_using lt x y = ordering.gt → p r → p (black_node l y r)) : p t := sorry theorem find_correct {α : Type u} {t : rbnode α} {lt : α → α → Prop} {x : α} [DecidableRel lt] [is_strict_weak_order α lt] {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) : mem lt x t ↔ ∃ (y : α), find lt t x = some y ∧ strict_weak_order.equiv x y := sorry theorem mem_of_mem_exact {α : Type u} {lt : α → α → Prop} [is_irrefl α lt] {x : α} {t : rbnode α} : mem_exact x t → mem lt x t := sorry theorem find_correct_exact {α : Type u} {t : rbnode α} {lt : α → α → Prop} {x : α} [DecidableRel lt] [is_strict_weak_order α lt] {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) : mem_exact x t ↔ find lt t x = some x := sorry theorem eqv_of_find_some {α : Type u} {t : rbnode α} {lt : α → α → Prop} {x : α} {y : α} [DecidableRel lt] [is_strict_weak_order α lt] {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) (he : find lt t x = some y) : strict_weak_order.equiv x y := sorry theorem find_eq_find_of_eqv {α : Type u} {lt : α → α → Prop} {a : α} {b : α} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {lo : Option α} {hi : Option α} (hs : is_searchable lt t lo hi) (heqv : strict_weak_order.equiv a b) : find lt t a = find lt t b := sorry end Mathlib
f85a67d5746fec6745b7bead25aeb349210f12c5
4f9ca1935adf84f1bae9c5740ec1f2ad406716fa
/src/analysis/asymptotics.lean
b34fa1fd85589d2fbcd7850e42858ac4ca76379d
[ "Apache-2.0" ]
permissive
matthew-hilty/mathlib
36fd7db866365e9ee4a0ba1d6f8ad34d068cec6c
585e107f9811719832c6656f49e1263a8eef5380
refs/heads/master
1,607,100,509,178
1,578,151,707,000
1,578,151,707,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,725
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import analysis.normed_space.basic /-! # Asymptotics We introduce these relations: `is_O f g l` : "f is big O of g along l" `is_o f g l` : "f is little o of g along l" Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter open_locale topological_space namespace asymptotics variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {𝕜 : Type*} {𝕜' : Type*} section variables [has_norm β] [has_norm γ] [has_norm δ] /-- The Landau notation `is_O f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ def is_O (f : α → β) (g : α → γ) (l : filter α) : Prop := ∃ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l /-- The Landau notation `is_o f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ def is_o (f : α → β) (g : α → γ) (l : filter α) : Prop := ∀ c > 0, { x | ∥ f x ∥ ≤ c * ∥ g x ∥ } ∈ l theorem is_O_refl (f : α → β) (l : filter α) : is_O f f l := ⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩ theorem is_O.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_O f g l) {δ : Type*} (k : δ → α) : is_O (f ∘ k) (g ∘ k) (l.comap k) := let ⟨c, cpos, hfgc⟩ := hfg in ⟨c, cpos, mem_comap_sets.mpr ⟨_, hfgc, set.subset.refl _⟩⟩ theorem is_o.comp {f : α → β} {g : α → γ} {l : filter α} (hfg : is_o f g l) {δ : Type*} (k : δ → α) : is_o (f ∘ k) (g ∘ k) (l.comap k) := λ c cpos, mem_comap_sets.mpr ⟨_, hfg c cpos, set.subset.refl _⟩ theorem is_O.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂) (h' : is_O f g l₂) : is_O f g l₁ := let ⟨c, cpos, h'c⟩ := h' in ⟨c, cpos, h (h'c)⟩ theorem is_o.mono {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h : l₁ ≤ l₂) (h' : is_o f g l₂) : is_o f g l₁ := λ c cpos, h (h' c cpos) theorem is_o.to_is_O {f : α → β} {g : α → γ} {l : filter α} (hgf : is_o f g l) : is_O f g l := ⟨1, zero_lt_one, hgf 1 zero_lt_one⟩ theorem is_O.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_O f g l) (h₂ : is_O g k l) : is_O f k l := let ⟨c, cpos, hc⟩ := h₁, ⟨c', c'pos, hc'⟩ := h₂ in begin use [c * c', mul_pos cpos c'pos], filter_upwards [hc, hc'], dsimp, intros x h₁x h₂x, rw mul_assoc, exact le_trans h₁x (mul_le_mul_of_nonneg_left h₂x (le_of_lt cpos)) end theorem is_o.trans_is_O {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_o f g l) (h₂ : is_O g k l) : is_o f k l := begin intros c cpos, rcases h₂ with ⟨c', c'pos, hc'⟩, have cc'pos := div_pos cpos c'pos, filter_upwards [h₁ (c / c') cc'pos, hc'], dsimp, intros x h₁x h₂x, refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt cc'pos)) _), rw [←mul_assoc, div_mul_cancel _ (ne_of_gt c'pos)] end theorem is_O.trans_is_o {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_O f g l) (h₂ : is_o g k l) : is_o f k l := begin intros c cpos, rcases h₁ with ⟨c', c'pos, hc'⟩, have cc'pos := div_pos cpos c'pos, filter_upwards [hc', h₂ (c / c') cc'pos], dsimp, intros x h₁x h₂x, refine le_trans h₁x (le_trans (mul_le_mul_of_nonneg_left h₂x (le_of_lt c'pos)) _), rw [←mul_assoc, mul_div_cancel' _ (ne_of_gt c'pos)] end theorem is_o.trans {f : α → β} {g : α → γ} {k : α → δ} {l : filter α} (h₁ : is_o f g l) (h₂ : is_o g k l) : is_o f k l := h₁.to_is_O.trans_is_o h₂ theorem is_o_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h₁ : is_o f g l₁) (h₂ : is_o f g l₂) : is_o f g (l₁ ⊔ l₂) := begin intros c cpos, rw mem_sup_sets, exact ⟨h₁ c cpos, h₂ c cpos⟩ end theorem is_O_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := bex_congr $ λ c _, filter.congr_sets $ by filter_upwards [hf, hg] λ x e₁ e₂, by dsimp at e₁ e₂ ⊢; rw [e₁, e₂] theorem is_o_congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : {x | f₁ x = f₂ x} ∈ l) (hg : {x | g₁ x = g₂ x} ∈ l) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr $ λ c _, filter.congr_sets $ by filter_upwards [hf, hg] λ x e₁ e₂, by dsimp at e₁ e₂ ⊢; rw [e₁, e₂] theorem is_O.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1 theorem is_o.congr {f₁ f₂ : α → β} {g₁ g₂ : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr (univ_mem_sets' hf) (univ_mem_sets' hg)).1 theorem is_O_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : {x | f₁ x = f₂ x} ∈ l) : is_O f₁ g l ↔ is_O f₂ g l := is_O_congr h (univ_mem_sets' $ λ _, rfl) theorem is_o_congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : {x | f₁ x = f₂ x} ∈ l) : is_o f₁ g l ↔ is_o f₂ g l := is_o_congr h (univ_mem_sets' $ λ _, rfl) theorem is_O.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_o.congr_left {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_O_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (h : {x | g₁ x = g₂ x} ∈ l) : is_O f g₁ l ↔ is_O f g₂ l := is_O_congr (univ_mem_sets' $ λ _, rfl) h theorem is_o_congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (h : {x | g₁ x = g₂ x} ∈ l) : is_o f g₁ l ↔ is_o f g₂ l := is_o_congr (univ_mem_sets' $ λ _, rfl) h theorem is_O.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o.congr_right {f : α → β} {g₁ g₂ : α → γ} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg end section variables [has_norm β] [normed_group γ] [normed_group δ] @[simp] theorem is_O_norm_right {f : α → β} {g : α → γ} {l : filter α} : is_O f (λ x, ∥g x∥) l ↔ is_O f g l := by simp only [is_O, norm_norm] @[simp] theorem is_o_norm_right {f : α → β} {g : α → γ} {l : filter α} : is_o f (λ x, ∥g x∥) l ↔ is_o f g l := by simp only [is_o, norm_norm] @[simp] theorem is_O_neg_right {f : α → β} {g : α → γ} {l : filter α} : is_O f (λ x, -(g x)) l ↔ is_O f g l := by { rw ←is_O_norm_right, simp only [norm_neg], rw is_O_norm_right } @[simp] theorem is_o_neg_right {f : α → β} {g : α → γ} {l : filter α} : is_o f (λ x, -(g x)) l ↔ is_o f g l := by { rw ←is_o_norm_right, simp only [norm_neg], rw is_o_norm_right } theorem is_O_iff {f : α → β} {g : α → γ} {l : filter α} : is_O f g l ↔ ∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l := suffices (∃ c, { x | ∥f x∥ ≤ c * ∥g x∥ } ∈ l) → is_O f g l, from ⟨λ ⟨c, cpos, hc⟩, ⟨c, hc⟩, this⟩, assume ⟨c, hc⟩, or.elim (lt_or_ge 0 c) (assume : c > 0, ⟨c, this, hc⟩) (assume h'c : c ≤ 0, have {x : α | ∥f x∥ ≤ 1 * ∥g x∥} ∈ l, begin filter_upwards [hc], intros x, show ∥f x∥ ≤ c * ∥g x∥ → ∥f x∥ ≤ 1 * ∥g x∥, { intro hx, apply le_trans hx, apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), show c ≤ 1, from le_trans h'c zero_le_one } end, ⟨1, zero_lt_one, this⟩) theorem is_O_join {f : α → β} {g : α → γ} {l₁ l₂ : filter α} (h₁ : is_O f g l₁) (h₂ : is_O f g l₂) : is_O f g (l₁ ⊔ l₂) := begin rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, rcases h₂ with ⟨c₂, c₂pos, hc₂⟩, have : 0 < max c₁ c₂, by { rw lt_max_iff, left, exact c₁pos }, use [max c₁ c₂, this], rw mem_sup_sets, split, { filter_upwards [hc₁], dsimp, intros x hx, exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _)) }, filter_upwards [hc₂], dsimp, intros x hx, exact le_trans hx (mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg _)) end lemma is_O.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_O f g₁ l) : is_O f (λx, (g₁ x, g₂ x)) l := begin have : is_O g₁ (λx, (g₁ x, g₂ x)) l := ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩, exact is_O.trans h this end lemma is_O.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_O f g₂ l) : is_O f (λx, (g₁ x, g₂ x)) l := begin have : is_O g₂ (λx, (g₁ x, g₂ x)) l := ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, by simp [norm, le_refl])⟩, exact is_O.trans h this end lemma is_o.prod_rightl {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_o f g₁ l) : is_o f (λx, (g₁ x, g₂ x)) l := is_o.trans_is_O h (is_O.prod_rightl (is_O_refl g₁ l)) lemma is_o.prod_rightr {f : α → β} {g₁ : α → γ} {g₂ : α → δ} {l : filter α} (h : is_o f g₂ l) : is_o f (λx, (g₁ x, g₂ x)) l := is_o.trans_is_O h (is_O.prod_rightr (is_O_refl g₂ l)) end section variables [normed_group β] [normed_group δ] [has_norm γ] @[simp] theorem is_O_norm_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, ∥f x∥) g l ↔ is_O f g l := by simp only [is_O, norm_norm] @[simp] theorem is_o_norm_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, ∥f x∥) g l ↔ is_o f g l := by simp only [is_o, norm_norm] @[simp] theorem is_O_neg_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, -f x) g l ↔ is_O f g l := by { rw ←is_O_norm_left, simp only [norm_neg], rw is_O_norm_left } @[simp] theorem is_o_neg_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, -f x) g l ↔ is_o f g l := by { rw ←is_o_norm_left, simp only [norm_neg], rw is_o_norm_left } theorem is_O.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := let ⟨c₁, c₁pos, hc₁⟩ := h₁, ⟨c₂, c₂pos, hc₂⟩ := h₂ in begin use [c₁ + c₂, add_pos c₁pos c₂pos], filter_upwards [hc₁, hc₂], intros x hx₁ hx₂, show ∥f₁ x + f₂ x∥ ≤ (c₁ + c₂) * ∥g x∥, rw add_mul, exact norm_add_le_of_le hx₁ hx₂ end theorem is_o.add {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := begin intros c cpos, filter_upwards [h₁ (c / 2) (half_pos cpos), h₂ (c / 2) (half_pos cpos)], intros x hx₁ hx₂, dsimp at hx₁ hx₂, apply le_trans (norm_add_le_of_le hx₁ hx₂), rw [←mul_add, ←two_mul, ←mul_assoc, div_mul_cancel _ two_ne_zero] end theorem is_O.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := h₁.add (is_O_neg_left.mpr h₂) theorem is_o.sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := h₁.add (is_o_neg_left.mpr h₂) theorem is_O_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := by simpa using @is_O_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l theorem is_O.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f₁ x - f₂ x) g l → is_O (λ x, f₂ x - f₁ x) g l := is_O_comm.1 theorem is_O.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α} (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left (by simp) theorem is_O.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o_comm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := by simpa using @is_o_neg_left _ _ _ _ _ (λ x, f₂ x - f₁ x) g l theorem is_o.symm {f₁ f₂ : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f₁ x - f₂ x) g l → is_o (λ x, f₂ x - f₁ x) g l := is_o_comm.1 theorem is_o.tri {f₁ f₂ f₃ : α → β} {g : α → γ} {l : filter α} (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left (by simp) theorem is_o.congr_of_sub {f₁ f₂ : α → β} {g : α → γ} {l : filter α} (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ @[simp] theorem is_O_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} : is_O (λx, (f₁ x, f₂ x)) g l ↔ is_O f₁ g l ∧ is_O f₂ g l := begin split, { assume h, split, { exact is_O.trans (is_O.prod_rightl (is_O_refl f₁ l)) h }, { exact is_O.trans (is_O.prod_rightr (is_O_refl f₂ l)) h } }, { rintros ⟨h₁, h₂⟩, have : is_O (λx, ∥f₁ x∥ + ∥f₂ x∥) g l := is_O.add (is_O_norm_left.2 h₁) (is_O_norm_left.2 h₂), apply is_O.trans _ this, refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩, simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq], split; exact le_trans (by simp) (le_abs_self _) } end @[simp] theorem is_o_prod_left {f₁ : α → β} {f₂ : α → δ} {g : α → γ} {l : filter α} : is_o (λx, (f₁ x, f₂ x)) g l ↔ is_o f₁ g l ∧ is_o f₂ g l := begin split, { assume h, split, { exact is_O.trans_is_o (is_O.prod_rightl (is_O_refl f₁ l)) h }, { exact is_O.trans_is_o (is_O.prod_rightr (is_O_refl f₂ l)) h } }, { rintros ⟨h₁, h₂⟩, have : is_o (λx, ∥f₁ x∥ + ∥f₂ x∥) g l := is_o.add (is_o_norm_left.2 h₁) (is_o_norm_left.2 h₂), apply is_O.trans_is_o _ this, refine ⟨1, zero_lt_one, filter.univ_mem_sets' (λx, _)⟩, simp only [norm, max_le_iff, one_mul, set.mem_set_of_eq], split; exact le_trans (by simp) (le_abs_self _) } end end section variables [normed_group β] [normed_group γ] theorem is_O_zero (g : α → γ) (l : filter α) : is_O (λ x, (0 : β)) g l := ⟨1, zero_lt_one, by { filter_upwards [univ_mem_sets], intros x _, simp }⟩ theorem is_O_refl_left {f : α → β} {g : α → γ} {l : filter α} : is_O (λ x, f x - f x) g l := by simpa using is_O_zero g l theorem is_O_zero_right_iff {f : α → β} {l : filter α} : is_O f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l := begin rw [is_O_iff], split, { rintros ⟨c, hc⟩, filter_upwards [hc], dsimp, intro x, rw [norm_zero, mul_zero], intro hx, rw ←norm_eq_zero, exact le_antisymm hx (norm_nonneg _) }, intro h, use 0, filter_upwards [h], dsimp, intros x hx, rw [hx, norm_zero, zero_mul] end theorem is_o_zero (g : α → γ) (l : filter α) : is_o (λ x, (0 : β)) g l := λ c cpos, by { filter_upwards [univ_mem_sets], intros x _, simp, exact mul_nonneg (le_of_lt cpos) (norm_nonneg _)} theorem is_o_refl_left {f : α → β} {g : α → γ} {l : filter α} : is_o (λ x, f x - f x) g l := by simpa using is_o_zero g l theorem is_o_zero_right_iff {f : α → β} (l : filter α) : is_o f (λ x, (0 : γ)) l ↔ {x | f x = 0} ∈ l := begin split, { intro h, exact is_O_zero_right_iff.mp h.to_is_O }, intros h c cpos, filter_upwards [h], dsimp, intros x hx, rw [hx, norm_zero, norm_zero, mul_zero] end end section variables [has_norm β] [normed_field 𝕜] open normed_field theorem is_O_const_one (c : β) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : 𝕜)) l := begin rw is_O_iff, refine ⟨∥c∥, _⟩, simp only [norm_one, mul_one], apply univ_mem_sets', simp [le_refl], end end section variables [normed_field 𝕜] [normed_group γ] theorem is_O_const_mul_left {f : α → 𝕜} {g : α → γ} {l : filter α} (h : is_O f g l) (c : 𝕜) : is_O (λ x, c * f x) g l := begin cases classical.em (c = 0) with h'' h'', { simp [h''], apply is_O_zero }, rcases h with ⟨c', c'pos, h'⟩, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), refine ⟨∥c∥ * c', mul_pos cpos c'pos, _⟩, filter_upwards [h'], dsimp, intros x h₀, rw [normed_field.norm_mul, mul_assoc], exact mul_le_mul_of_nonneg_left h₀ (norm_nonneg _) end theorem is_O_const_mul_left_iff {f : α → 𝕜} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := begin split, { intro h, convert is_O_const_mul_left h c⁻¹, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] }, intro h, apply is_O_const_mul_left h end theorem is_o_const_mul_left {f : α → 𝕜} {g : α → γ} {l : filter α} (h : is_o f g l) (c : 𝕜) : is_o (λ x, c * f x) g l := begin cases classical.em (c = 0) with h'' h'', { simp [h''], apply is_o_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h'', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), intros c' c'pos, dsimp, filter_upwards [h (c' / ∥c∥) (div_pos c'pos cpos)], dsimp, intros x hx, rw [normed_field.norm_mul], apply le_trans (mul_le_mul_of_nonneg_left hx (le_of_lt cpos)), rw [←mul_assoc, mul_div_cancel' _ cne0] end theorem is_o_const_mul_left_iff {f : α → 𝕜} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := begin split, { intro h, convert is_o_const_mul_left h c⁻¹, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] }, intro h', apply is_o_const_mul_left h' end end section variables [normed_group β] [normed_field 𝕜] theorem is_O_of_is_O_const_mul_right {f : α → β} {g : α → 𝕜} {l : filter α} {c : 𝕜} (h : is_O f (λ x, c * g x) l) : is_O f g l := begin cases classical.em (c = 0) with h' h', { simp [h', is_O_zero_right_iff] at h, rw is_O_congr_left h, apply is_O_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), rcases h with ⟨c', c'pos, h''⟩, refine ⟨c' * ∥c∥, mul_pos c'pos cpos, _⟩, convert h'', ext x, dsimp, rw [normed_field.norm_mul, mul_assoc] end theorem is_O_const_mul_right_iff {f : α → β} {g : α → 𝕜} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := begin split, { intro h, exact is_O_of_is_O_const_mul_right h }, intro h, apply is_O_of_is_O_const_mul_right, show is_O f (λ (x : α), c⁻¹ * (c * g x)) l, convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] end theorem is_o_of_is_o_const_mul_right {f : α → β} {g : α → 𝕜} {l : filter α} {c : 𝕜} (h : is_o f (λ x, c * g x) l) : is_o f g l := begin cases classical.em (c = 0) with h' h', { simp [h', is_o_zero_right_iff] at h, rw is_o_congr_left h, apply is_o_zero }, have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp h', have cpos : ∥c∥ > 0, from lt_of_le_of_ne (norm_nonneg _) (ne.symm cne0), intros c' c'pos, convert h (c' / ∥c∥) (div_pos c'pos cpos), dsimp, ext x, rw [normed_field.norm_mul, ←mul_assoc, div_mul_cancel _ cne0] end theorem is_o_const_mul_right {f : α → β} {g : α → 𝕜} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := begin split, { intro h, exact is_o_of_is_o_const_mul_right h }, intro h, apply is_o_of_is_o_const_mul_right, show is_o f (λ (x : α), c⁻¹ * (c * g x)) l, convert h, ext, rw [←mul_assoc, inv_mul_cancel hc, one_mul] end theorem is_o_one_iff {f : α → β} {l : filter α} : is_o f (λ x, (1 : 𝕜)) l ↔ tendsto f l (𝓝 0) := begin rw [normed_group.tendsto_nhds_zero, is_o], split, { intros h e epos, filter_upwards [h (e / 2) (half_pos epos)], simp, intros x hx, exact lt_of_le_of_lt hx (half_lt_self epos) }, intros h e epos, filter_upwards [h e epos], simp, intros x hx, exact le_of_lt hx end theorem is_O_one_of_tendsto {f : α → β} {l : filter α} {y : β} (h : tendsto f l (𝓝 y)) : is_O f (λ x, (1 : 𝕜)) l := begin have Iy : ∥y∥ < ∥y∥ + 1 := lt_add_one _, refine ⟨∥y∥ + 1, lt_of_le_of_lt (norm_nonneg _) Iy, _⟩, simp only [mul_one, normed_field.norm_one], have : tendsto (λx, ∥f x∥) l (𝓝 ∥y∥) := (continuous_norm.tendsto _).comp h, exact this (ge_mem_nhds Iy) end end section variables [normed_group β] [normed_group γ] theorem is_O.trans_tendsto {f : α → β} {g : α → γ} {l : filter α} (h₁ : is_O f g l) (h₂ : tendsto g l (𝓝 0)) : tendsto f l (𝓝 0) := (@is_o_one_iff _ _ ℝ _ _ _ _).1 $ h₁.trans_is_o $ is_o_one_iff.2 h₂ theorem is_o.trans_tendsto {f : α → β} {g : α → γ} {l : filter α} (h₁ : is_o f g l) : tendsto g l (𝓝 0) → tendsto f l (𝓝 0) := h₁.to_is_O.trans_tendsto end section variables [normed_field 𝕜] [normed_field 𝕜'] theorem is_O_mul {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} {l : filter α} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, rcases h₂ with ⟨c₂, c₂pos, hc₂⟩, refine ⟨c₁ * c₂, mul_pos c₁pos c₂pos, _⟩, filter_upwards [hc₁, hc₂], dsimp, intros x hx₁ hx₂, rw [normed_field.norm_mul, normed_field.norm_mul, mul_assoc, mul_left_comm c₂, ←mul_assoc], exact mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _)) end theorem is_o_mul_left {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} {l : filter α} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁ with ⟨c₁, c₁pos, hc₁⟩, filter_upwards [hc₁, h₂ (c / c₁) (div_pos cpos c₁pos)], dsimp, intros x hx₁ hx₂, rw [normed_field.norm_mul, normed_field.norm_mul], apply le_trans (mul_le_mul hx₁ hx₂ (norm_nonneg _) (mul_nonneg (le_of_lt c₁pos) (norm_nonneg _))), rw [mul_comm c₁, mul_assoc, mul_left_comm c₁, ←mul_assoc _ c₁, div_mul_cancel _ (ne_of_gt c₁pos)], rw [mul_left_comm] end theorem is_o_mul_right {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} {l : filter α} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := by convert is_o_mul_left h₂ h₁; simp only [mul_comm] theorem is_o_mul {f₁ f₂ : α → 𝕜} {g₁ g₂ : α → 𝕜'} {l : filter α} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := is_o_mul_left h₁.to_is_O h₂ end /- Note: the theorems in the next two sections can also be used for the integers, since scalar multiplication is multiplication. -/ section variables [normed_field 𝕜] [normed_group β] [normed_space 𝕜 β] [normed_group γ] set_option class.instance_max_depth 43 theorem is_O_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) (c : 𝕜) : is_O (λ x, c • f x) g l := begin rw [←is_O_norm_left], simp only [norm_smul], apply is_O_const_mul_left, rw [is_O_norm_left], apply h end theorem is_O_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c • f x) g l ↔ is_O f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left] end theorem is_o_const_smul_left {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) (c : 𝕜) : is_o (λ x, c • f x) g l := begin rw [←is_o_norm_left], simp only [norm_smul], apply is_o_const_mul_left, rw [is_o_norm_left], apply h end theorem is_o_const_smul_left_iff {f : α → β} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c • f x) g l ↔ is_o f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end end section variables [normed_group β] [normed_field 𝕜] [normed_group γ] [normed_space 𝕜 γ] set_option class.instance_max_depth 43 theorem is_O_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c • g x) l ↔ is_O f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {f : α → β} {g : α → γ} {l : filter α} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c • g x) l ↔ is_o f g l := begin have cne0 : ∥c∥ ≠ 0, from mt (norm_eq_zero _).mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right cne0, is_o_norm_right] end end section variables [normed_field 𝕜] [normed_group β] [normed_space 𝕜 β] [normed_group γ] [normed_space 𝕜 γ] set_option class.instance_max_depth 43 theorem is_O_smul {k : α → 𝕜} {f : α → β} {g : α → γ} {l : filter α} (h : is_O f g l) : is_O (λ x, k x • f x) (λ x, k x • g x) l := begin rw [←is_O_norm_left, ←is_O_norm_right], simp only [norm_smul], apply is_O_mul (is_O_refl _ _), rw [is_O_norm_left, is_O_norm_right], exact h end theorem is_o_smul {k : α → 𝕜} {f : α → β} {g : α → γ} {l : filter α} (h : is_o f g l) : is_o (λ x, k x • f x) (λ x, k x • g x) l := begin rw [←is_o_norm_left, ←is_o_norm_right], simp only [norm_smul], apply is_o_mul_left (is_O_refl _ _), rw [is_o_norm_left, is_o_norm_right], exact h end end section variables [normed_field 𝕜] theorem tendsto_nhds_zero_of_is_o {f g : α → 𝕜} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (𝓝 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from is_o_mul_right h (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : 𝕜)) l, begin use [1, zero_lt_one], filter_upwards [univ_mem_sets], simp, intro x, cases classical.em (∥g x∥ = 0) with h' h'; simp [h'], exact zero_le_one end, is_o_one_iff.mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : 𝕜)) l, from is_o_one_iff.mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert is_o_mul_right eq₁ (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin use [1, zero_lt_one], refine filter.univ_mem_sets' (assume x, _), suffices : ∥f x∥ ≤ ∥f x∥ / ∥g x∥ * ∥g x∥, { simpa }, by_cases g x = 0, { simp only [h, hgf x h, norm_zero, mul_zero] }, { rw [div_mul_cancel], exact mt (norm_eq_zero _).1 h } end, eq₃.trans_is_o eq₂ theorem is_o_iff_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro tendsto_nhds_zero_of_is_o (is_o_of_tendsto hgf) theorem is_o_pow_pow {m n : ℕ} (h : m < n) : is_o (λ(x : 𝕜), x^n) (λx, x^m) (𝓝 0) := begin let p := n - m, have nmp : n = m + p := (nat.add_sub_cancel' (le_of_lt h)).symm, have : (λ(x : 𝕜), x^m) = (λx, x^m * 1), by simp, simp only [this, pow_add, nmp], refine is_o_mul_left (is_O_refl _ _) (is_o_one_iff.2 _), convert (continuous_pow p).tendsto (0 : 𝕜), exact (zero_pow (nat.sub_pos_of_lt h)).symm end theorem is_o_pow_id {n : ℕ} (h : 1 < n) : is_o (λ(x : 𝕜), x^n) (λx, x) (𝓝 0) := by { convert is_o_pow_pow h, simp } end end asymptotics
32b0d4ec30f551bd7bd04b61af039738f7fe1eda
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/pp_links.lean
44e5293689c908a054d9e1bfbcc631602501c2c1
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
192
lean
open tactic structure point (α : Type*) := (x : α) (y : α) example : ∀ i : ℤ, (i, i).snd = i + 0 + (point.mk 0 i).x := by do os ← get_options, set_options (os.set_bool `pp.links tt)
20755b66d4b1cbd44a973c7702b8ffa09371ee16
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/complex/exponential.lean
4f3692187f89ffce09bc6bcc6ae3e550d09b9083
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
47,503
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.archimedean import data.nat.choose data.complex.basic import tactic.linarith local attribute [instance, priority 0] nat.cast_coe local attribute [instance, priority 0] classical.prop_decidable local notation `abs'` := _root_.abs open is_absolute_value section open real is_absolute_value finset lemma forall_ge_le_of_forall_le_succ {α : Type*} [preorder α] (f : ℕ → α) {m : ℕ} (h : ∀ n ≥ m, f n.succ ≤ f n) : ∀ {l}, ∀ k ≥ m, k ≤ l → f l ≤ f k := begin assume l k hkm hkl, generalize hp : l - k = p, have : l = k + p := add_comm p k ▸ (nat.sub_eq_iff_eq_add hkl).1 hp, subst this, clear hkl hp, induction p with p ih, { simp }, { exact le_trans (h _ (le_trans hkm (nat.le_add_right _ _))) ih } end variables {α : Type*} {β : Type*} [ring β] [discrete_linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - add_monoid.smul l ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - add_monoid.smul (k + (k + 1)) ε < -abs (f n), from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_monoid.add_smul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_left _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - add_monoid.smul l ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m (le_refl _)) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases classical.not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := forall_ge_le_of_forall_le_succ f hnm _ hi.1 hj, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], exact calc f i ≤ a - add_monoid.smul (nat.pred l) ε : hi.2 ... = a - add_monoid.smul l ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_smul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, abs (f n) ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, (range n).sum g) → is_cau_seq abv (λ n, (range n).sum f) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le ((range j).sum g) ((range i).sum g) ((range (max n i)).sum g), have := add_lt_add hi₁ hi₂, rw [abs_sub ((range (max n i)).sum g), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw nat.sub_eq_iff_eq_add ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { dsimp at *, rw [nat.succ_add, sum_range_succ, sum_range_succ, add_assoc, add_assoc], refine le_trans (abv_add _ _ _) _, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, (range m).sum (λ n, abv (f n))) → is_cau_seq abv (λ m, (range m).sum f) := is_cau_series_of_abv_le_cau 0 (λ n h, le_refl _) lemma is_cau_geo_series {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, (range n).sum (λ m, x ^ m)) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv, geom_sum hx1'] {eta := ff}, conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le_of_pos (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)) (sub_pos.2 hx1), refine div_nonneg (sub_nonneg.2 _) (sub_pos.2 hx1), clear hn, induction n with n ih, { simp }, { rw [_root_.pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le_of_pos (sub_le_sub_left _ _) (sub_pos.2 hx1), rw [← one_mul (_ ^ n), _root_.pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : abs x < 1) : is_cau_seq abs (λ m, (range m).sum (λ n, a * x ^ n)) := have is_cau_seq abs (λ m, a * (range m).sum (λ n, x ^ n)) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, (range m).sum f) := have har1 : abs r < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (nat.sub_eq_iff_eq_add hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, ← pow_inv _ _ r_ne_zero, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) = (range n).sum (λ m, (range (n - m)).sum (f m)) := have h₁ : ((range n).sigma (range ∘ nat.succ)).sum (λ (a : Σ m, ℕ), f (a.2) (a.1 - a.2)) = (range n).sum (λ m, (range (m + 1)).sum (λ k, f k (m - k))) := sum_sigma, have h₂ : ((range n).sigma (λ m, range (n - m))).sum (λ a : Σ (m : ℕ), ℕ, f (a.1) (a.2)) = (range n).sum (λ m, sum (range (n - m)) (f m)) := sum_sigma, h₁ ▸ h₂ ▸ sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((nat.sub_lt_sub_right_iff (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (nat.sub_eq_iff_eq_add ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨nat.sub_add_cancel hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (nat.lt_sub_right_iff_add_lt.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (nat.add_sub_cancel _ _).symm⟩⟩⟩) lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (s.sum f) ≤ s.sum (abv ∘ f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) lemma sum_range_sub_sum_range {α : Type*} [add_comm_group α] {f : ℕ → α} {n m : ℕ} (hnm : n ≤ m) : (range m).sum f - (range n).sum f = ((range m).filter (λ k, n ≤ k)).sum f := begin rw [← sum_sdiff (@filter_subset _ (λ k, n ≤ k) _ (range m)), sub_eq_iff_eq_add, ← eq_sub_iff_add_eq, add_sub_cancel'], refine finset.sum_congr (finset.ext.2 $ λ a, ⟨λ h, by simp at *; finish, λ h, have ham : a < m := lt_of_lt_of_le (mem_range.1 h) hnm, by simp * at *⟩) (λ _ _, rfl), end lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, (range m).sum (λ n, abv (a n)))) (hb : is_cau_seq abv (λ m, (range m).sum b)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((range j).sum a * (range j).sum b - (range j).sum (λ n, (range (n + 1)).sum (λ m, a m * b (n - m)))) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : sum (range K) (λ m, (range (m + 1)).sum (λ k, a k * b (m - k))) = sum (range K) (λ m, sum (range (K - m)) (λ n, a m * b n)), by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, (range (K - i)).sum (λ k, a i * b k)) = (λ i, a i * (range (K - i)).sum b), by simp [finset.mul_sum], have h₃ : (range K).sum (λ i, a i * (range (K - i)).sum b) = (range K).sum (λ i, a i * ((range (K - i)).sum b - (range K).sum b)) + (range K).sum (λ i, a i * (range K).sum b), by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div_eq_div_mul, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div_eq_div_mul, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : (range (max N M + 1)).sum (λ i, abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) ≤ (range (max N M + 1)).sum (λ i, abv (a i) * (ε / (2 * P))), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) K (nat.le_sub_left_of_add_le (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : sum (range (max N M + 1)) (λ n, abv (a n)) < P := calc sum (range (max N M + 1)) (λ n, abv (a n)) = abs (sum (range (max N M + 1)) (λ n, abv (a n))) : eq.symm (abs_of_nonneg (zero_le_sum (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : (range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) + ((range K).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b)) -(range (max N M + 1)).sum (λ (i : ℕ), abv (a i) * abv ((range (K - i)).sum b - (range K).sum b))) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), exact calc sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * abv (sum (range (K - i)) b - sum (range K) b)) ≤ sum ((range K).filter (λ k, max N M + 1 ≤ k)) (λ i, abv (a i) * (2 * Q)) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq _root_.abs (λ n, (range n).sum (λ m, abs (z ^ m / nat.fact m))) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg_of_nonneg_of_pos (complex.abs_nonneg _) hn0) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.fact_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div_eq_div_mul, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) (nat.cast_pos.2 (nat.succ_pos _)) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, (range n).sum (λ m, z ^ m / nat.fact m)) := is_cau_series_of_abv_cau (is_cau_abs_exp z) def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, (range n).sum (λ m, z ^ m / nat.fact m), is_cau_exp z⟩ def exp (z : ℂ) : ℂ := lim (exp' z) def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 def tan (z : ℂ) : ℂ := sin z / cos z def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex def exp (x : ℝ) : ℝ := (exp x).re def sin (x : ℝ) : ℝ := (sin x).re def cos (x : ℝ) : ℝ := (cos x).re def tan (x : ℝ) : ℝ := (tan x).re def sinh (x : ℝ) : ℝ := (sinh x).re def cosh (x : ℝ) : ℝ := (cosh x).re def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, (range j).sum (λ m, (x + y) ^ m / m.fact) = (range j).sum (λ i, (range (i + 1)).sum (λ k, x ^ k / k.fact * (y ^ (i - k) / (i - k).fact))), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (nat.choose m i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_fact_mul_fact (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv', mul_inv'], simp only [mul_left_comm (nat.choose m i : ℂ), mul_assoc, mul_left_comm (nat.choose m i : ℂ)⁻¹, mul_comm (nat.choose m i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, @zero_ne_one ℂ _ $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← domain.mul_left_inj (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw ← sum_hom conj, refine sum_congr rfl (λ n hn, _), rw [conj_div, conj_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (exp x)).1 (by rw [← exp_conj, conj_of_real]) in by rw [hr, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := complex.ext (by simp) (by simp) @[simp] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := complex.ext (by simp [real.exp]) (by simp [real.exp]) @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos], simp [mul_add, add_mul, exp_add], ring end @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sin, cos], apply complex.ext; simp [mul_add, add_mul, exp_add]; ring end lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma sin_conj : sin (conj x) = conj (sin x) := begin rw [sin, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul, exp_conj, exp_conj, ← conj_sub, sin, conj_div, conj_two, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)], apply complex.ext; simp [sin, neg_add], end @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (sin x)).1 (by rw [← sin_conj, conj_of_real]) in by rw [hr, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := by apply complex.ext; simp @[simp] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := by simp [real.sin] lemma cos_conj : cos (conj x) = conj (cos x) := begin rw [cos, ← conj_neg_I, ← conj_mul, ← conj_neg, ← conj_mul, exp_conj, exp_conj, cos, conj_div, conj_two, ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _)], apply complex.ext; simp end @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (cos x)).1 (by rw [← cos_conj, conj_of_real]) in by rw [hr, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := by apply complex.ext; simp @[simp] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := by simp [real.cos, -cos_of_real_re] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← conj_div, tan] @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (tan x)).1 (by rw [← tan_conj, conj_of_real]) in by rw [hr, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := by apply complex.ext; simp @[simp] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := by simp [real.tan, -tan_of_real_re] lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 := begin simp only [pow_two, mul_sub, sub_mul, mul_add, add_mul, div_eq_mul_inv, neg_mul_eq_neg_mul_symm, exp_neg, mul_comm (exp _), mul_left_comm (exp _), mul_assoc, mul_left_comm (exp _)⁻¹, inv_mul_cancel (exp_ne_zero _), mul_inv', mul_one, one_mul, sin, cos], apply complex.ext; simp [norm_sq]; ring end lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [two_mul, cos_add, ← pow_two, ← pow_two, eq_sub_iff_add_eq.2 (sin_pow_two_add_cos_pow_two x)]; simp [two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_pow_two_add_cos_pow_two x], simp } lemma exp_mul_I : exp (x * I) = cos x + sin x * I := by rw [cos, sin, mul_comm (_ / 2) I, ← mul_div_assoc, mul_left_comm I, I_mul_I, ← add_div]; simp lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh], simp [mul_add, add_mul, exp_add], ring end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _), ← domain.mul_left_inj (@two_ne_zero' ℂ _ _ _)], simp only [mul_add, add_mul, mul_sub, sub_mul, exp_add, div_mul_div, div_add_div_same, mul_assoc, (div_div_eq_div_mul _ _ _).symm, mul_div_cancel' _ (@two_ne_zero' ℂ _ _ _), sinh, cosh], apply complex.ext; simp [mul_add, add_mul, exp_add]; ring end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← conj_neg, exp_conj, exp_conj, ← conj_sub, sinh, conj_div, conj_two] @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (sinh x)).1 (by rw [← sinh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := by apply complex.ext; simp @[simp] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := by simp [real.sinh] lemma cosh_conj : cosh (conj x) = conj (cosh x) := by rw [cosh, ← conj_neg, exp_conj, exp_conj, ← conj_add, cosh, conj_div, conj_two] @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (cosh x)).1 (by rw [← cosh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl @[simp] lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := by apply complex.ext; simp @[simp] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := by simp [real.cosh] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← conj_div, tanh] @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := let ⟨r, hr⟩ := (eq_conj_iff_real (tanh x)).1 (by rw [← tanh_conj, conj_of_real]) in by rw [hr, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := by apply complex.ext; simp @[simp] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := by simp [real.tanh] end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [cos_add, sin_neg, cos_neg] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := if h : complex.cos x = 0 then by simp [sin, cos, tan, *, complex.tan, div_eq_mul_inv] at * else by rw [sin, cos, tan, complex.tan, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma sin_pow_two_add_cos_pow_two : sin x ^ 2 + cos x ^ 2 = 1 := by rw ← of_real_inj; simpa [sin, of_real_pow] using sin_pow_two_add_cos_pow_two x lemma abs_sin_le_one : abs' (sin x) ≤ 1 := not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ) (calc 1 * 1 < abs' (sin x) * abs' (sin x) : mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h)) ... = sin x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two] ... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_right (pow_two_nonneg _) ... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul]) lemma abs_cos_le_one : abs' (cos x) ≤ 1 := not_lt.1 $ λ h, lt_irrefl (1 * 1 : ℝ) (calc 1 * 1 < abs' (cos x) * abs' (cos x) : mul_lt_mul h (le_of_lt h) zero_lt_one (le_trans zero_le_one (le_of_lt h)) ... = cos x ^ 2 : by rw [← _root_.abs_mul, abs_mul_self, pow_two] ... ≤ sin x ^ 2 + cos x ^ 2 : le_add_of_nonneg_left (pow_two_nonneg _) ... = 1 * 1 : by rw [sin_pow_two_add_cos_pow_two, one_mul]) lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma sin_pow_two_le_one : sin x ^ 2 ≤ 1 := by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one (abs_sin_le_one _) (abs_nonneg _) (abs_sin_le_one _) lemma cos_pow_two_le_one : cos x ^ 2 ≤ 1 := by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one (abs_cos_le_one _) (abs_nonneg _) (abs_cos_le_one _) lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul, cos, pow_two] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul, sin, pow_two] lemma cos_square : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero, -one_div_eq_inv] lemma sin_square : sin x ^ 2 = 1 - cos x ^ 2 := by { rw [←sin_pow_two_add_cos_pow_two x], simp } @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh, sinh_add] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [cosh, exp_neg] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh, cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := if h : complex.cosh x = 0 then by simp [sinh, cosh, tanh, *, complex.tanh, div_eq_mul_inv] at * else by rw [sinh, cosh, tanh, complex.tanh, ← of_real_inj, div_eq_mul_inv, mul_re]; simp [norm_sq, (div_div_eq_div_mul _ _ _).symm, div_self h]; refl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] open is_absolute_value /- TODO make this private and prove ∀ x -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ abs') : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ ((range j).sum (λ m, (x ^ m / m.fact : ℂ))).re, from have h₁ : (((λ m : ℕ, (x ^ m / m.fact : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / nat.fact 0).re = 1, by simp, begin rw [← nat.sub_add_cancel hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← @sum_hom _ _ _ _ _ _ _ complex.re (is_add_group_hom.to_is_add_monoid_hom _)], refine le_add_of_nonneg_of_le (zero_le_sum (λ m hm, _)) (le_refl _), dsimp [-nat.fact_succ], rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_pos.2 (nat.fact_pos _)), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith using [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : abs' (exp x) = exp x := abs_of_nonneg (le_of_lt (exp_pos _)) lemma exp_lt_exp {x y : ℝ} (h : x < y) : exp x < exp y := by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) lemma exp_le_exp {x y : ℝ} : real.exp x ≤ real.exp y ↔ x ≤ y := ⟨λ h, le_of_not_gt $ mt exp_lt_exp $ by simpa, λ h, by rw [←sub_add_cancel y x, real.exp_add]; exact (le_mul_iff_one_le_left (exp_pos _)).2 (one_le_exp (sub_nonneg.2 h))⟩ lemma exp_injective : function.injective exp := λ x y h, begin rcases lt_trichotomy x y with h₁ | h₁ | h₁, { exact absurd h (ne_of_lt (exp_lt_exp h₁)) }, { exact h₁ }, { exact absurd h (ne.symm (ne_of_lt (exp_lt_exp h₁))) } end @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := ⟨by rw ← exp_zero; exact λ h, exp_injective h, λ h, by rw [h, exp_zero]⟩ end real namespace complex lemma sum_div_fact_le {α : Type*} [discrete_linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : (sum (filter (λ k, n ≤ k) (range j)) (λ m : ℕ, (1 / m.fact : α))) ≤ n.succ * (n.fact * n)⁻¹ := calc (filter (λ k, n ≤ k) (range j)).sum (λ m : ℕ, (1 / m.fact : α)) = (range (j - n)).sum (λ m, 1 / (m + n).fact) : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (nat.sub_lt_sub_right_iff (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw nat.sub_add_cancel; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [nat.sub_eq_iff_eq_add, ← nat.sub_add_comm, eq_comm, nat.sub_eq_iff_eq_add, add_right_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ nat.add_lt_of_lt_sub_right (mem_range.1 hb), nat.le_add_left _ _⟩, by rw nat.add_sub_cancel⟩) ... ≤ (range (j - n)).sum (λ m, (nat.fact n * n.succ ^ m)⁻¹) : begin refine sum_le_sum (assume m n, _), rw [one_div_eq_inv, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.fact_mul_pow_le_fact }, { exact nat.cast_pos.2 (nat.fact_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.fact_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = (nat.fact n)⁻¹ * (range (j - n)).sum (λ m, n.succ⁻¹ ^ m) : by simp [mul_inv', mul_sum.symm, sum_mul.symm, -nat.fact_succ, mul_comm, inv_pow'] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n.fact * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ _ ▸ mt nat.cast_inj.1 (mt nat.succ_inj (nat.pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n.fact * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 (nat.fact_pos _))) (nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq _ _ h₃, mul_comm _ (n.fact * n : α), ← mul_assoc (n.fact⁻¹ : α), ← mul_inv', h₄, ← mul_assoc (n.fact * n : α), mul_comm (n : α) n.fact, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n.fact * n) : begin refine (div_le_div_right (mul_pos _ _)).2 _, exact nat.cast_pos.2 (nat.fact_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) := begin rw [← lim_const ((range n).sum _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), show abs ((range j).sum (λ m, x ^ m / m.fact) - (range n).sum (λ m, x ^ m / m.fact)) ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹), rw sum_range_sub_sum_range hj, exact calc abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ m / m.fact : ℂ))) = abs (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (x ^ n * (x ^ (m - n) / m.fact) : ℂ))) : congr_arg abs (sum_congr rfl (λ m hm, by rw [← mul_div_assoc, ← pow_add, nat.add_sub_cancel']; simp at hm; tauto)) ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs (x ^ n * (_ / m.fact))) : abv_sum_le_sum_abv _ _ ... ≤ sum (filter (λ k, n ≤ k) (range j)) (λ m, abs x ^ n * (1 / m.fact)) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, exact nat.cast_pos.2 (nat.fact_pos _), rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), exact pow_nonneg (abs_nonneg _) _ end ... = abs x ^ n * (((range j).filter (λ k, n ≤ k)).sum (λ m : ℕ, (1 / m.fact : ℝ))) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n.fact * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_fact_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - (range 1).sum (λ m, x ^ m / m.fact)) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (nat.fact 1 * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] end complex namespace real open complex finset lemma cos_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (cos x - (1 - x ^ 2 / 2)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (cos x - (1 - x ^ 2 / 2)) = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _ _)] ... = abs (((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) + ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) / 2) + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : abs' x ≤ 1) : abs' (sin x - (x - x ^ 3 / 6)) ≤ abs' x ^ 4 * (5 / 96) := calc abs' (sin x - (x - x ^ 3 / 6)) = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _ _), div_div_eq_div_mul, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) - (complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact)) * I / 2) + abs (-((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact)) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - (range 4).sum (λ m, (x * I) ^ m / m.fact))) / 2 + abs ((complex.exp (-x * I) - (range 4).sum (λ m, (-x * I) ^ m / m.fact))) / 2) : by simp [complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (nat.fact 4 * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (exp_bound (by simpa) dec_trivial)) ... ≤ abs' x ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : abs' x ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - abs' x ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc abs' x ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc abs' x ^ 4 ≤ abs' x ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from div_le_of_le_mul (by norm_num) (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ abs' (1 : ℝ) ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (by simp) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by rw [pow_two, pow_two]; exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le) (by norm_num)) _ ... < 0 : by norm_num end real namespace complex lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_pow_two_add_cos_pow_two x, by simp [abs, norm_sq, pow_two, *, sin_of_real_re, cos_of_real_re, mul_re] at * lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y, abs_mul, abs_mul, abs_cos_add_sin_mul_I, abs_cos_add_sin_mul_I, ← of_real_exp, ← of_real_exp, abs_of_nonneg (le_of_lt (real.exp_pos _)), abs_of_nonneg (le_of_lt (real.exp_pos _)), mul_one, mul_one]; exact ⟨λ h, real.exp_injective h, congr_arg _⟩ @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) end complex
879d5746fe9c51e7d32ffb5f3f77819671802959
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/direct_sum/finsupp.lean
279482cfa0cb2a0751f06418664600c03844109c
[ "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,469
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.direct_sum.module import data.finsupp.to_dfinsupp /-! # Results on direct sums and finitely supported functions. 1. The linear equivalence between finitely supported functions `ι →₀ M` and the direct sum of copies of `M` indexed by `ι`. -/ universes u v w noncomputable theory open_locale direct_sum open linear_map submodule variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] section finsupp_lequiv_direct_sum variables (R M) (ι : Type*) [decidable_eq ι] /-- The finitely supported functions `ι →₀ M` are in linear equivalence with the direct sum of copies of M indexed by ι. -/ def finsupp_lequiv_direct_sum : (ι →₀ M) ≃ₗ[R] ⨁ i : ι, M := by haveI : Π m : M, decidable (m ≠ 0) := classical.dec_pred _; exact finsupp_lequiv_dfinsupp R @[simp] theorem finsupp_lequiv_direct_sum_single (i : ι) (m : M) : finsupp_lequiv_direct_sum R M ι (finsupp.single i m) = direct_sum.lof R ι _ i m := finsupp.to_dfinsupp_single i m @[simp] theorem finsupp_lequiv_direct_sum_symm_lof (i : ι) (m : M) : (finsupp_lequiv_direct_sum R M ι).symm (direct_sum.lof R ι _ i m) = finsupp.single i m := begin letI : Π m : M, decidable (m ≠ 0) := classical.dec_pred _, exact (dfinsupp.to_finsupp_single i m), end end finsupp_lequiv_direct_sum
87230473cdf431cd8a5965ecb6bb52c55398f59d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/star/star_alg_hom.lean
93139df49b5415f636ac1ae2d03af63eddc18de9
[ "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
28,351
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.hom.non_unital_alg import algebra.star.prod import algebra.algebra.prod /-! # Morphisms of star algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines morphisms between `R`-algebras (unital or non-unital) `A` and `B` where both `A` and `B` are equipped with a `star` operation. These morphisms, namely `star_alg_hom` and `non_unital_star_alg_hom` are direct extensions of their non-`star`red counterparts with a field `map_star` which guarantees they preserve the star operation. We keep the type classes as generic as possible, in keeping with the definition of `non_unital_alg_hom` in the non-unital case. In this file, we only assume `has_star` unless we want to talk about the zero map as a `non_unital_star_alg_hom`, in which case we need `star_add_monoid`. Note that the scalar ring `R` is not required to have a star operation, nor do we need `star_ring` or `star_module` structures on `A` and `B`. As with `non_unital_alg_hom`, in the non-unital case the multiplications are not assumed to be associative or unital, or even to be compatible with the scalar actions. In a typical application, the operations will satisfy compatibility conditions making them into algebras (albeit possibly non-associative and/or non-unital) but such conditions are not required here for the definitions. The primary impetus for defining these types is that they constitute the morphisms in the categories of unital C⋆-algebras (with `star_alg_hom`s) and of C⋆-algebras (with `non_unital_star_alg_hom`s). TODO: add `star_alg_equiv`. ## Main definitions * `non_unital_alg_hom` * `star_alg_hom` ## Tags non-unital, algebra, morphism, star -/ set_option old_structure_cmd true /-! ### Non-unital star algebra homomorphisms -/ /-- A *non-unital ⋆-algebra homomorphism* is a non-unital algebra homomorphism between non-unital `R`-algebras `A` and `B` equipped with a `star` operation, and this homomorphism is also `star`-preserving. -/ structure non_unital_star_alg_hom (R A B : Type*) [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] extends A →ₙₐ[R] B := (map_star' : ∀ a : A, to_fun (star a) = star (to_fun a)) infixr ` →⋆ₙₐ `:25 := non_unital_star_alg_hom _ notation A ` →⋆ₙₐ[`:25 R `] ` B := non_unital_star_alg_hom R A B /-- Reinterpret a non-unital star algebra homomorphism as a non-unital algebra homomorphism by forgetting the interaction with the star operation. -/ add_decl_doc non_unital_star_alg_hom.to_non_unital_alg_hom /-- `non_unital_star_alg_hom_class F R A B` asserts `F` is a type of bundled non-unital ⋆-algebra homomorphisms from `A` to `B`. -/ class non_unital_star_alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*) [monoid R] [has_star A] [has_star B] [non_unital_non_assoc_semiring A] [non_unital_non_assoc_semiring B] [distrib_mul_action R A] [distrib_mul_action R B] extends non_unital_alg_hom_class F R A B, star_hom_class F A B -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] non_unital_star_alg_hom_class.to_star_hom_class namespace non_unital_star_alg_hom_class variables {F R A B : Type*} [monoid R] variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] instance [non_unital_star_alg_hom_class F R A B] : has_coe_t F (A →⋆ₙₐ[R] B) := { coe := λ f, { to_fun := f, map_star' := map_star f, .. (f : A →ₙₐ[R] B) }} end non_unital_star_alg_hom_class namespace non_unital_star_alg_hom section basic variables {R A B C D : Type*} [monoid R] variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] variables [non_unital_non_assoc_semiring C] [distrib_mul_action R C] [has_star C] variables [non_unital_non_assoc_semiring D] [distrib_mul_action R D] [has_star D] instance : non_unital_star_alg_hom_class (A →⋆ₙₐ[R] B) R A B := { coe := to_fun, coe_injective' := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr, map_smul := λ f, f.map_smul', map_add := λ f, f.map_add', map_zero := λ f, f.map_zero', map_mul := λ f, f.map_mul', map_star := λ f, f.map_star' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (A →⋆ₙₐ[R] B) (λ _, A → B) := fun_like.has_coe_to_fun initialize_simps_projections non_unital_star_alg_hom (to_fun → apply) @[simp, protected] lemma coe_coe {F : Type*} [non_unital_star_alg_hom_class F R A B] (f : F) : ⇑(f : A →⋆ₙₐ[R] B) = f := rfl @[simp] lemma coe_to_non_unital_alg_hom {f : A →⋆ₙₐ[R] B} : (f.to_non_unital_alg_hom : A → B) = f := rfl @[ext] lemma ext {f g : A →⋆ₙₐ[R] B} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `non_unital_star_alg_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : A →⋆ₙₐ[R] B := { to_fun := f', map_smul' := h.symm ▸ map_smul f, map_zero' := h.symm ▸ map_zero f, map_add' := h.symm ▸ map_add f, map_mul' := h.symm ▸ map_mul f, map_star' := h.symm ▸ map_star f } @[simp] lemma coe_copy (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : A →⋆ₙₐ[R] B) (f' : A → B) (h : f' = f) : f.copy f' h = f := fun_like.ext' h @[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄ h₅) : ((⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →⋆ₙₐ[R] B) : A → B) = f := rfl @[simp] lemma mk_coe (f : A →⋆ₙₐ[R] B) (h₁ h₂ h₃ h₄ h₅) : (⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →⋆ₙₐ[R] B) = f := by { ext, refl, } section variables (R A) /-- The identity as a non-unital ⋆-algebra homomorphism. -/ protected def id : A →⋆ₙₐ[R] A := { map_star' := λ x, rfl, .. (1 : A →ₙₐ[R] A) } @[simp] lemma coe_id : ⇑(non_unital_star_alg_hom.id R A) = id := rfl end /-- The composition of non-unital ⋆-algebra homomorphisms, as a non-unital ⋆-algebra homomorphism. -/ def comp (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) : A →⋆ₙₐ[R] C := { map_star' := by simp only [map_star, non_unital_alg_hom.to_fun_eq_coe, eq_self_iff_true, non_unital_alg_hom.coe_comp, coe_to_non_unital_alg_hom, function.comp_app, forall_const], .. f.to_non_unital_alg_hom.comp g.to_non_unital_alg_hom } @[simp] lemma coe_comp (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) : ⇑(comp f g) = f ∘ g := rfl @[simp] lemma comp_apply (f : B →⋆ₙₐ[R] C) (g : A →⋆ₙₐ[R] B) (a : A) : comp f g a = f (g a) := rfl @[simp] lemma comp_assoc (f : C →⋆ₙₐ[R] D) (g : B →⋆ₙₐ[R] C) (h : A →⋆ₙₐ[R] B) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma id_comp (f : A →⋆ₙₐ[R] B) : (non_unital_star_alg_hom.id _ _).comp f = f := ext $ λ _, rfl @[simp] lemma comp_id (f : A →⋆ₙₐ[R] B) : f.comp (non_unital_star_alg_hom.id _ _) = f := ext $ λ _, rfl instance : monoid (A →⋆ₙₐ[R] A) := { mul := comp, mul_assoc := comp_assoc, one := non_unital_star_alg_hom.id R A, one_mul := id_comp, mul_one := comp_id, } @[simp] lemma coe_one : ((1 : A →⋆ₙₐ[R] A) : A → A) = id := rfl lemma one_apply (a : A) : (1 : A →⋆ₙₐ[R] A) a = a := rfl end basic section zero -- the `zero` requires extra type class assumptions because we need `star_zero` variables {R A B C D : Type*} [monoid R] variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [star_add_monoid A] variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [star_add_monoid B] instance : has_zero (A →⋆ₙₐ[R] B) := ⟨{ map_star' := by simp, .. (0 : non_unital_alg_hom R A B) }⟩ instance : inhabited (A →⋆ₙₐ[R] B) := ⟨0⟩ instance : monoid_with_zero (A →⋆ₙₐ[R] A) := { zero_mul := λ f, ext $ λ x, rfl, mul_zero := λ f, ext $ λ x, map_zero f, .. non_unital_star_alg_hom.monoid, .. non_unital_star_alg_hom.has_zero } @[simp] lemma coe_zero : ((0 : A →⋆ₙₐ[R] B) : A → B) = 0 := rfl lemma zero_apply (a : A) : (0 : A →⋆ₙₐ[R] B) a = 0 := rfl end zero end non_unital_star_alg_hom /-! ### Unital star algebra homomorphisms -/ section unital /-- A *⋆-algebra homomorphism* is an algebra homomorphism between `R`-algebras `A` and `B` equipped with a `star` operation, and this homomorphism is also `star`-preserving. -/ structure star_alg_hom (R A B: Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A] [semiring B] [algebra R B] [has_star B] extends alg_hom R A B := (map_star' : ∀ x : A, to_fun (star x) = star (to_fun x)) infixr ` →⋆ₐ `:25 := star_alg_hom _ notation A ` →⋆ₐ[`:25 R `] ` B := star_alg_hom R A B /-- Reinterpret a unital star algebra homomorphism as a unital algebra homomorphism by forgetting the interaction with the star operation. -/ add_decl_doc star_alg_hom.to_alg_hom /-- `star_alg_hom_class F R A B` states that `F` is a type of ⋆-algebra homomorphisms. You should also extend this typeclass when you extend `star_alg_hom`. -/ class star_alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A] [semiring B] [algebra R B] [has_star B] extends alg_hom_class F R A B, star_hom_class F A B -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] star_alg_hom_class.to_star_hom_class namespace star_alg_hom_class variables (F R A B : Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A] variables [semiring B] [algebra R B] [has_star B] [hF : star_alg_hom_class F R A B] include hF @[priority 100] /- See note [lower instance priority] -/ instance to_non_unital_star_alg_hom_class : non_unital_star_alg_hom_class F R A B := { map_smul := map_smul, .. star_alg_hom_class.to_alg_hom_class F R A B, .. star_alg_hom_class.to_star_hom_class F R A B, } instance : has_coe_t F (A →⋆ₐ[R] B) := { coe := λ f, { to_fun := f, map_star' := map_star f, ..(f : A →ₐ[R] B) } } end star_alg_hom_class namespace star_alg_hom variables {F R A B C D : Type*} [comm_semiring R] [semiring A] [algebra R A] [has_star A] [semiring B] [algebra R B] [has_star B] [semiring C] [algebra R C] [has_star C] [semiring D] [algebra R D] [has_star D] instance : star_alg_hom_class (A →⋆ₐ[R] B) R A B := { coe := λ f, f.to_fun, coe_injective' := λ f g h, begin obtain ⟨_, _, _, _, _, _, _⟩ := f; obtain ⟨_, _, _, _, _, _, _⟩ := g; congr' end, map_mul := map_mul', map_one := map_one', map_add := map_add', map_zero := map_zero', commutes := commutes', map_star := map_star' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (A →⋆ₐ[R] B) (λ _, A → B) := fun_like.has_coe_to_fun @[simp, protected] lemma coe_coe {F : Type*} [star_alg_hom_class F R A B] (f : F) : ⇑(f : A →⋆ₐ[R] B) = f := rfl initialize_simps_projections star_alg_hom (to_fun → apply) @[simp] lemma coe_to_alg_hom {f : A →⋆ₐ[R] B} : (f.to_alg_hom : A → B) = f := rfl @[ext] lemma ext {f g : A →⋆ₐ[R] B} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h /-- Copy of a `star_alg_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : A →⋆ₐ[R] B := { to_fun := f', map_one' := h.symm ▸ map_one f , map_mul' := h.symm ▸ map_mul f, map_zero' := h.symm ▸ map_zero f, map_add' := h.symm ▸ map_add f, commutes' := h.symm ▸ alg_hom_class.commutes f, map_star' := h.symm ▸ map_star f } @[simp] lemma coe_copy (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : A →⋆ₐ[R] B) (f' : A → B) (h : f' = f) : f.copy f' h = f := fun_like.ext' h @[simp] lemma coe_mk (f : A → B) (h₁ h₂ h₃ h₄ h₅ h₆) : ((⟨f, h₁, h₂, h₃, h₄, h₅, h₆⟩ : A →⋆ₐ[R] B) : A → B) = f := rfl @[simp] lemma mk_coe (f : A →⋆ₐ[R] B) (h₁ h₂ h₃ h₄ h₅ h₆) : (⟨f, h₁, h₂, h₃, h₄, h₅, h₆⟩ : A →⋆ₐ[R] B) = f := by { ext, refl, } section variables (R A) /-- The identity as a `star_alg_hom`. -/ protected def id : A →⋆ₐ[R] A := { map_star' := λ x, rfl, .. alg_hom.id _ _ } @[simp] lemma coe_id : ⇑(star_alg_hom.id R A) = id := rfl end instance : inhabited (A →⋆ₐ[R] A) := ⟨star_alg_hom.id R A⟩ /-- The composition of ⋆-algebra homomorphisms, as a ⋆-algebra homomorphism. -/ def comp (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) : A →⋆ₐ[R] C := { map_star' := by simp only [map_star, alg_hom.to_fun_eq_coe, alg_hom.coe_comp, coe_to_alg_hom, function.comp_app, eq_self_iff_true, forall_const], .. f.to_alg_hom.comp g.to_alg_hom } @[simp] lemma coe_comp (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) : ⇑(comp f g) = f ∘ g := rfl @[simp] lemma comp_apply (f : B →⋆ₐ[R] C) (g : A →⋆ₐ[R] B) (a : A) : comp f g a = f (g a) := rfl @[simp] lemma comp_assoc (f : C →⋆ₐ[R] D) (g : B →⋆ₐ[R] C) (h : A →⋆ₐ[R] B) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma id_comp (f : A →⋆ₐ[R] B) : (star_alg_hom.id _ _).comp f = f := ext $ λ _, rfl @[simp] lemma comp_id (f : A →⋆ₐ[R] B) : f.comp (star_alg_hom.id _ _) = f := ext $ λ _, rfl instance : monoid (A →⋆ₐ[R] A) := { mul := comp, mul_assoc := comp_assoc, one := star_alg_hom.id R A, one_mul := id_comp, mul_one := comp_id } /-- A unital morphism of ⋆-algebras is a `non_unital_star_alg_hom`. -/ def to_non_unital_star_alg_hom (f : A →⋆ₐ[R] B) : A →⋆ₙₐ[R] B := { map_smul' := map_smul f, .. f, } @[simp] lemma coe_to_non_unital_star_alg_hom (f : A →⋆ₐ[R] B) : (f.to_non_unital_star_alg_hom : A → B) = f := rfl end star_alg_hom end unital /-! ### Operations on the product type Note that this is copied from [`algebra/hom/non_unital_alg`](non_unital_alg). -/ namespace non_unital_star_alg_hom section prod variables (R A B C : Type*) [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] [non_unital_non_assoc_semiring C] [distrib_mul_action R C] [has_star C] /-- The first projection of a product is a non-unital ⋆-algebra homomoprhism. -/ @[simps] def fst : A × B →⋆ₙₐ[R] A := { map_star' := λ x, rfl, .. non_unital_alg_hom.fst R A B } /-- The second projection of a product is a non-unital ⋆-algebra homomorphism. -/ @[simps] def snd : A × B →⋆ₙₐ[R] B := { map_star' := λ x, rfl, .. non_unital_alg_hom.snd R A B } variables {R A B C} /-- The `pi.prod` of two morphisms is a morphism. -/ @[simps] def prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : (A →⋆ₙₐ[R] B × C) := { map_star' := λ x, by simp [map_star, prod.star_def], .. f.to_non_unital_alg_hom.prod g.to_non_unital_alg_hom } lemma coe_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : (fst R B C).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : A →⋆ₙₐ[R] B) (g : A →⋆ₙₐ[R] C) : (snd R B C).comp (prod f g) = g := by ext; refl @[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 := fun_like.coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. -/ @[simps] def prod_equiv : ((A →⋆ₙₐ[R] B) × (A →⋆ₙₐ[R] C)) ≃ (A →⋆ₙₐ[R] B × C) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl } end prod section inl_inr variables (R A B C : Type*) [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [star_add_monoid A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [star_add_monoid B] [non_unital_non_assoc_semiring C] [distrib_mul_action R C] [star_add_monoid C] /-- The left injection into a product is a non-unital algebra homomorphism. -/ def inl : A →⋆ₙₐ[R] A × B := prod 1 0 /-- The right injection into a product is a non-unital algebra homomorphism. -/ def inr : B →⋆ₙₐ[R] A × B := prod 0 1 variables {R A B} @[simp] theorem coe_inl : (inl R A B : A → A × B) = λ x, (x, 0) := rfl theorem inl_apply (x : A) : inl R A B x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R A B : B → A × B) = prod.mk 0 := rfl theorem inr_apply (x : B) : inr R A B x = (0, x) := rfl end inl_inr end non_unital_star_alg_hom namespace star_alg_hom variables (R A B C : Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A] [semiring B] [algebra R B] [has_star B] [semiring C] [algebra R C] [has_star C] /-- The first projection of a product is a ⋆-algebra homomoprhism. -/ @[simps] def fst : A × B →⋆ₐ[R] A := { map_star' := λ x, rfl, .. alg_hom.fst R A B } /-- The second projection of a product is a ⋆-algebra homomorphism. -/ @[simps] def snd : A × B →⋆ₐ[R] B := { map_star' := λ x, rfl, .. alg_hom.snd R A B } variables {R A B C} /-- The `pi.prod` of two morphisms is a morphism. -/ @[simps] def prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : (A →⋆ₐ[R] B × C) := { map_star' := λ x, by simp [prod.star_def, map_star], .. f.to_alg_hom.prod g.to_alg_hom } lemma coe_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : (fst R B C).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : A →⋆ₐ[R] B) (g : A →⋆ₐ[R] C) : (snd R B C).comp (prod f g) = g := by ext; refl @[simp] theorem prod_fst_snd : prod (fst R A B) (snd R A B) = 1 := fun_like.coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. -/ @[simps] def prod_equiv : ((A →⋆ₐ[R] B) × (A →⋆ₐ[R] C)) ≃ (A →⋆ₐ[R] B × C) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl } end star_alg_hom /-! ### Star algebra equivalences -/ /-- A *⋆-algebra* equivalence is an equivalence preserving addition, multiplication, scalar multiplication and the star operation, which allows for considering both unital and non-unital equivalences with a single structure. Currently, `alg_equiv` requires unital algebras, which is why this structure does not extend it. -/ structure star_alg_equiv (R A B : Type*) [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B] [has_mul B] [has_smul R B] [has_star B] extends A ≃+* B := (map_star' : ∀ a : A, to_fun (star a) = star (to_fun a)) (map_smul' : ∀ (r : R) (a : A), to_fun (r • a) = r • to_fun a) infixr ` ≃⋆ₐ `:25 := star_alg_equiv _ notation A ` ≃⋆ₐ[`:25 R `] ` B := star_alg_equiv R A B /-- Reinterpret a star algebra equivalence as a `ring_equiv` by forgetting the interaction with the star operation and scalar multiplication. -/ add_decl_doc star_alg_equiv.to_ring_equiv /-- `star_alg_equiv_class F R A B` asserts `F` is a type of bundled ⋆-algebra equivalences between `A` and `B`. You should also extend this typeclass when you extend `star_alg_equiv`. -/ class star_alg_equiv_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*) [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B] [has_mul B] [has_smul R B] [has_star B] extends ring_equiv_class F A B := (map_star : ∀ (f : F) (a : A), f (star a) = star (f a)) (map_smul : ∀ (f : F) (r : R) (a : A), f (r • a) = r • f a) -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] star_alg_equiv_class.to_ring_equiv_class namespace star_alg_equiv_class @[priority 50] -- See note [lower instance priority] instance {F R A B : Type*} [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B] [has_mul B] [has_smul R B] [has_star B] [hF : star_alg_equiv_class F R A B] : star_hom_class F A B := { coe := λ f, f, coe_injective' := fun_like.coe_injective, .. hF } -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] star_alg_equiv_class.star_hom_class @[priority 50] -- See note [lower instance priority] instance {F R A B : Type*} [has_add A] [has_mul A] [has_star A] [has_smul R A] [has_add B] [has_mul B] [has_smul R B] [has_star B] [hF : star_alg_equiv_class F R A B] : smul_hom_class F R A B := { coe := λ f, f, coe_injective' := fun_like.coe_injective, .. hF } -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] star_alg_equiv_class.smul_hom_class @[priority 100] -- See note [lower instance priority] instance {F R A B : Type*} [monoid R] [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] [hF : star_alg_equiv_class F R A B] : non_unital_star_alg_hom_class F R A B := { coe := λ f, f, coe_injective' := fun_like.coe_injective, map_zero := map_zero, .. hF } @[priority 100] -- See note [lower instance priority] instance (F R A B : Type*) [comm_semiring R] [semiring A] [algebra R A] [has_star A] [semiring B] [algebra R B] [has_star B] [hF : star_alg_equiv_class F R A B] : star_alg_hom_class F R A B := { coe := λ f, f, coe_injective' := fun_like.coe_injective, map_one := map_one, map_zero := map_zero, commutes := λ f r, by simp only [algebra.algebra_map_eq_smul_one, map_smul, map_one], .. hF} end star_alg_equiv_class namespace star_alg_equiv section basic variables {F R A B C : Type*} [has_add A] [has_mul A] [has_smul R A] [has_star A] [has_add B] [has_mul B] [has_smul R B] [has_star B] [has_add C] [has_mul C] [has_smul R C] [has_star C] instance : star_alg_equiv_class (A ≃⋆ₐ[R] B) R A B := { coe := to_fun, inv := inv_fun, left_inv := left_inv, right_inv := right_inv, coe_injective' := λ f g h₁ h₂, by { cases f, cases g, congr' }, map_mul := map_mul', map_add := map_add', map_star := map_star', map_smul := map_smul' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (A ≃⋆ₐ[R] B) (λ _, A → B) := ⟨star_alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A ≃⋆ₐ[R] B} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h lemma ext_iff {f g : A ≃⋆ₐ[R] B} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff /-- Star algebra equivalences are reflexive. -/ @[refl] def refl : A ≃⋆ₐ[R] A := { map_smul' := λ r a, rfl, map_star' := λ a, rfl, ..ring_equiv.refl A } instance : inhabited (A ≃⋆ₐ[R] A) := ⟨refl⟩ @[simp] lemma coe_refl : ⇑(refl : A ≃⋆ₐ[R] A) = id := rfl /-- Star algebra equivalences are symmetric. -/ @[symm] def symm (e : A ≃⋆ₐ[R] B) : B ≃⋆ₐ[R] A := { map_star' := λ b, by simpa only [e.left_inv (star (e.inv_fun b)), e.right_inv b] using congr_arg e.inv_fun (e.map_star' (e.inv_fun b)).symm, map_smul' := λ r b, by simpa only [e.left_inv (r • e.inv_fun b), e.right_inv b] using congr_arg e.inv_fun (e.map_smul' r (e.inv_fun b)).symm, ..e.to_ring_equiv.symm, } /-- See Note [custom simps projection] -/ def simps.symm_apply (e : A ≃⋆ₐ[R] B) : B → A := e.symm initialize_simps_projections star_alg_equiv (to_fun → apply, inv_fun → simps.symm_apply) @[simp] lemma inv_fun_eq_symm {e : A ≃⋆ₐ[R] B} : e.inv_fun = e.symm := rfl @[simp] lemma symm_symm (e : A ≃⋆ₐ[R] B) : e.symm.symm = e := by { ext, refl, } lemma symm_bijective : function.bijective (symm : (A ≃⋆ₐ[R] B) → (B ≃⋆ₐ[R] A)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : A ≃⋆ₐ[R] B) (f h₁ h₂ h₃ h₄ h₅ h₆) : (⟨f, e, h₁, h₂, h₃, h₄, h₅, h₆⟩ : B ≃⋆ₐ[R] A) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] lemma symm_mk (f f') (h₁ h₂ h₃ h₄ h₅ h₆) : (⟨f, f', h₁, h₂, h₃, h₄, h₅, h₆⟩ : A ≃⋆ₐ[R] B).symm = { to_fun := f', inv_fun := f, ..(⟨f, f', h₁, h₂, h₃, h₄, h₅, h₆⟩ : A ≃⋆ₐ[R] B).symm } := rfl @[simp] lemma refl_symm : (star_alg_equiv.refl : A ≃⋆ₐ[R] A).symm = star_alg_equiv.refl := rfl -- should be a `simp` lemma, but causes a linter timeout lemma to_ring_equiv_symm (f : A ≃⋆ₐ[R] B) : (f : A ≃+* B).symm = f.symm := rfl @[simp] lemma symm_to_ring_equiv (e : A ≃⋆ₐ[R] B) : (e.symm : B ≃+* A) = (e : A ≃+* B).symm := rfl /-- Star algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) : A ≃⋆ₐ[R] C := { map_smul' := λ r a, show e₂.to_fun (e₁.to_fun (r • a)) = r • e₂.to_fun (e₁.to_fun a), by rw [e₁.map_smul', e₂.map_smul'], map_star' := λ a, show e₂.to_fun (e₁.to_fun (star a)) = star (e₂.to_fun (e₁.to_fun a)), by rw [e₁.map_star', e₂.map_star'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A ≃⋆ₐ[R] B) : ∀ x, e (e.symm x) = x := e.to_ring_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A ≃⋆ₐ[R] B) : ∀ x, e.symm (e x) = x := e.to_ring_equiv.symm_apply_apply @[simp] lemma symm_trans_apply (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) (x : C) : (e₁.trans e₂).symm x = e₁.symm (e₂.symm x) := rfl @[simp] lemma coe_trans (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp] lemma trans_apply (e₁ : A ≃⋆ₐ[R] B) (e₂ : B ≃⋆ₐ[R] C) (x : A) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl theorem left_inverse_symm (e : A ≃⋆ₐ[R] B) : function.left_inverse e.symm e := e.left_inv theorem right_inverse_symm (e : A ≃⋆ₐ[R] B) : function.right_inverse e.symm e := e.right_inv end basic section bijective variables {F G R A B : Type*} [monoid R] variables [non_unital_non_assoc_semiring A] [distrib_mul_action R A] [has_star A] variables [non_unital_non_assoc_semiring B] [distrib_mul_action R B] [has_star B] variables [hF : non_unital_star_alg_hom_class F R A B] [non_unital_star_alg_hom_class G R B A] include hF /-- If a (unital or non-unital) star algebra morphism has an inverse, it is an isomorphism of star algebras. -/ @[simps] def of_star_alg_hom (f : F) (g : G) (h₁ : ∀ x, g (f x) = x) (h₂ : ∀ x, f (g x) = x) : A ≃⋆ₐ[R] B := { to_fun := f, inv_fun := g, left_inv := h₁, right_inv := h₂, map_add' := map_add f, map_mul' := map_mul f, map_smul' := map_smul f, map_star' := map_star f } /-- Promote a bijective star algebra homomorphism to a star algebra equivalence. -/ noncomputable def of_bijective (f : F) (hf : function.bijective f) : A ≃⋆ₐ[R] B := { to_fun := f, map_star' := map_star f, map_smul' := map_smul f, .. ring_equiv.of_bijective f (hf : function.bijective (f : A → B)), } @[simp] lemma coe_of_bijective {f : F} (hf : function.bijective f) : (star_alg_equiv.of_bijective f hf : A → B) = f := rfl lemma of_bijective_apply {f : F} (hf : function.bijective f) (a : A) : (star_alg_equiv.of_bijective f hf) a = f a := rfl end bijective end star_alg_equiv
af47dc0d9dbe41076f40f21c0b4a8c4da0658d61
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/measure_theory/outer_measure.lean
656d50417634b7d0398a735b66218a7e902a5ed1
[ "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
40,615
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 -/ import analysis.specific_limits import measure_theory.measurable_space import topology.algebra.infinite_sum /-! # Outer Measures An outer measure is a function `μ : set α → ennreal`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ennreal` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. We also define this for functions `m` defined on a subset of `set α`, by treating the function as having value `∞` outside its domain. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main definitions and statements * `outer_measure.bounded_by` is the greatest outer measure that is at most the given function. If you know that the given functions sends `∅` to `0`, then `outer_measure.of_function` is a special case. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. * `induced_outer_measure` is the measure induced by a function on a subset of `set α` ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑'i, measure_of (s i))) namespace outer_measure section basic variables {α : Type*} {β : Type*} {ms : set (outer_measure α)} {m : outer_measure α} instance : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ @[simp] lemma measure_of_eq_coe (m : outer_measure α) : m.measure_of = m := rfl @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑'i, m (s i)) := rel_supr_tsum m m.empty (≤) m.Union_nat s lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma Union_finset (m : outer_measure α) (s : β → set α) (t : finset β) : m (⋃i ∈ t, s i) ≤ ∑ i in t, m (s i) := rel_supr_sum m m.empty (≤) m.Union_nat s t protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := rel_sup_add m m.empty (≤) m.Union_nat s₁ s₂ lemma le_inter_add_diff {m : outer_measure α} {t : set α} (s : set α) : m t ≤ m (t ∩ s) + m (t \ s) := by { convert m.union _ _, rw inter_union_diff t s } lemma diff_null (m : outer_measure α) (s : set α) {t : set α} (ht : m t = 0) : m (s \ t) = m s := begin refine le_antisymm (m.mono $ diff_subset _ _) _, calc m s ≤ m (s ∩ t) + m (s \ t) : le_inter_add_diff _ ... ≤ m t + m (s \ t) : add_le_add_right (m.mono $ inter_subset_right _ _) _ ... = m (s \ t) : by rw [ht, zero_add] end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ lemma injective_coe_fn : injective (λ (μ : outer_measure α) (s : set α), μ s) := λ μ₁ μ₂ h, by { cases μ₁, cases μ₂, congr, exact h } @[ext] lemma ext {μ₁ μ₂ : outer_measure α} (h : ∀ s, μ₁ s = μ₂ s) : μ₁ = μ₂ := injective_coe_fn $ funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem coe_zero : ⇑(0 : outer_measure α) = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem coe_add (m₁ m₂ : outer_measure α) : ⇑(m₁ + m₂) = m₁ + m₂ := rfl theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), .. injective.add_comm_monoid (show outer_measure α → set α → ennreal, from coe_fn) injective_coe_fn rfl (λ _ _, rfl) } instance : has_scalar ennreal (outer_measure α) := ⟨λ c m, { measure_of := λ s, c * m s, empty := by simp, mono := λ s t h, ennreal.mul_left_mono $ m.mono h, Union_nat := λ s, by { rw [ennreal.tsum_mul_left], exact ennreal.mul_left_mono (m.Union _) } }⟩ @[simp] lemma coe_smul (c : ennreal) (m : outer_measure α) : ⇑(c • m) = c • m := rfl lemma smul_apply (c : ennreal) (m : outer_measure α) (s : set α) : (c • m) s = c * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul := (•), .. injective.semimodule ennreal ⟨show outer_measure α → set α → ennreal, from coe_fn, coe_zero, coe_add⟩ injective_coe_fn coe_smul } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆ m ∈ ms, (m : outer_measure α) s, empty := le_zero_iff_eq.1 $ bsupr_le $ λ m h, le_of_eq m.empty, mono := assume s₁ s₂ hs, bsupr_le_bsupr $ assume m hm, m.mono hs, Union_nat := assume f, bsupr_le $ assume m hm, calc m (⋃i, f i) ≤ (∑' (i : ℕ), m (f i)) : m.Union_nat _ ... ≤ (∑'i, ⨆ m ∈ ms, (m : outer_measure α) (f i)) : ennreal.tsum_le_tsum $ assume i, le_bsupr m hm }⟩ instance : complete_lattice (outer_measure α) := { .. outer_measure.order_bot, .. complete_lattice_of_Sup (outer_measure α) (λ ms, ⟨λ m hm s, le_bsupr m hm, λ m hm s, bsupr_le (λ m' hm', hm hm' s)⟩) } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m ∈ ms, (m : outer_measure α) s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := by rw [supr, Sup_apply, supr_range, supr] @[norm_cast] theorem coe_supr {ι} (f : ι → outer_measure α) : ⇑(⨆ i, f i) = ⨆ i, f i := funext $ λ s, by rw [supr_apply, _root_.supr_apply] @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) : outer_measure α →ₗ[ennreal] outer_measure β := { to_fun := λ m, { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) }, map_add' := λ m₁ m₂, injective_coe_fn rfl, map_smul' := λ c m, injective_coe_fn rfl } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β f, map f} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] /-- Pullback of an `outer_measure`: `comap f μ s = μ (f '' s)`. -/ def comap {β} (f : α → β) : outer_measure β →ₗ[ennreal] outer_measure α := { to_fun := λ m, { measure_of := λ s, m (f '' s), empty := by simp, mono := λ s t h, m.mono $ image_subset f h, Union_nat := λ s, by { rw [image_Union], apply m.Union_nat } }, map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } @[simp] lemma comap_apply {β} (f : α → β) (m : outer_measure β) (s : set α) : comap f m s = m (f '' s) := rfl /-- Restrict an `outer_measure` to a set. -/ def restrict (s : set α) : outer_measure α →ₗ[ennreal] outer_measure α := (map coe).comp (comap (coe : s → α)) @[simp] lemma restrict_apply (s t : set α) (m : outer_measure α) : restrict s m t = m (t ∩ s) := by simp [restrict] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := h in top_unique $ le_trans (by simp [smul_dirac_apply, as]) (le_bsupr ((⊤ : ennreal) • dirac a) trivial) end basic section of_function set_option eqn_compiler.zeta true variables {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) include m_empty /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑'i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left (le_of_lt hl) _), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑'i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← equiv.nat_prod_nat_equiv_nat.symm.tsum_eq], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } lemma of_function_apply (s : set α) : outer_measure.of_function m m_empty s = (⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, m (t n)) := rfl variables {m m_empty} theorem of_function_le (s : set α) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑'i, m (f i)) = ∑ i in {0}, m (f i) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem of_function_eq (s : set α) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ (∑'i, m (s i))) : outer_measure.of_function m m_empty s = m s := le_antisymm (of_function_le s) $ le_infi $ λ f, le_infi $ λ hf, le_trans (m_mono hf) (m_subadd f) theorem le_of_function {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H s) (of_function_le s), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section bounded_by variables {α : Type*} (m : set α → ennreal) /-- Given any function `m` assigning measures to sets, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. This is the same as `outer_measure.of_function`, except that it doesn't require `m ∅ = 0`. -/ def bounded_by : outer_measure α := outer_measure.of_function (λ s, ⨆ (h : s.nonempty), m s) (by simp [empty_not_nonempty]) variables {m} theorem bounded_by_le (s : set α) : bounded_by m s ≤ m s := (of_function_le _).trans supr_const_le theorem bounded_by_eq_of_function (m_empty : m ∅ = 0) (s : set α) : bounded_by m s = outer_measure.of_function m m_empty s := begin have : (λ s : set α, ⨆ (h : s.nonempty), m s) = m, { ext1 t, cases t.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty, m_empty] }, simp [bounded_by, this] end theorem bounded_by_apply (s : set α) : bounded_by m s = ⨅ (t : ℕ → set α) (h : s ⊆ Union t), ∑' n, ⨆ (h : (t n).nonempty), m (t n) := by simp [bounded_by, of_function_apply] theorem bounded_by_eq (s : set α) (m_empty : m ∅ = 0) (m_mono : ∀ ⦃t : set α⦄, s ⊆ t → m s ≤ m t) (m_subadd : ∀ (s : ℕ → set α), m (⋃i, s i) ≤ (∑'i, m (s i))) : bounded_by m s = m s := by rw [bounded_by_eq_of_function m_empty, of_function_eq s m_mono m_subadd] theorem le_bounded_by {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s, μ s ≤ m s := begin rw [bounded_by, le_of_function, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h, empty_not_nonempty] end theorem le_bounded_by' {μ : outer_measure α} : μ ≤ bounded_by m ↔ ∀ s : set α, s.nonempty → μ s ≤ m s := by { rw [le_bounded_by, forall_congr], intro s, cases s.eq_empty_or_nonempty with h h; simp [h] } end bounded_by section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ def is_caratheodory (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) lemma is_caratheodory_iff_le' {s : set α} : is_caratheodory s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ le_inter_add_diff _ @[simp] lemma is_caratheodory_empty : is_caratheodory ∅ := by simp [is_caratheodory, m.empty, diff_empty] lemma is_caratheodory_compl : is_caratheodory s₁ → is_caratheodory s₁ᶜ := by simp [is_caratheodory, diff_eq, add_comm] @[simp] lemma is_caratheodory_compl_iff : is_caratheodory sᶜ ↔ is_caratheodory s := ⟨λ h, by simpa using is_caratheodory_compl m h, is_caratheodory_compl⟩ lemma is_caratheodory_union (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : is_caratheodory s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] lemma is_caratheodory_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, is_caratheodory (s i)) → is_caratheodory (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact is_caratheodory_union m (h n (le_refl (n + 1))) (is_caratheodory_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) lemma is_caratheodory_inter (h₁ : is_caratheodory s₁) (h₂ : is_caratheodory s₂) : is_caratheodory (s₁ ∩ s₂) := by { rw [← is_caratheodory_compl_iff, compl_inter], exact is_caratheodory_union _ (is_caratheodory_compl _ h₁) (is_caratheodory_compl _ h₂) } lemma is_caratheodory_sum {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), is_caratheodory_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end lemma is_caratheodory_Union_nat {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : is_caratheodory (⋃i, s i) := is_caratheodory_iff_le'.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, is_caratheodory_sum m h hd] } }, refine le_trans (add_le_add_right hp _) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left _ _) (ge_of_eq (is_caratheodory_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end lemma f_Union {s : ℕ → set α} (h : ∀i, is_caratheodory (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @is_caratheodory_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ def caratheodory_dynkin : measurable_space.dynkin_system α := { has := is_caratheodory, has_empty := is_caratheodory_empty, has_compl := assume s, is_caratheodory_compl, has_Union_nat := assume f hf hn, is_caratheodory_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, is_caratheodory_inter lemma is_caratheodory_iff {s : set α} : caratheodory.is_measurable' s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_iff_le {s : set α} : caratheodory.is_measurable' s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := is_caratheodory_iff_le' protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable' (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma of_function_caratheodory {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable' s := begin apply (is_caratheodory_iff_le _).mpr, refine λ t, le_infi (λ f, le_infi $ λ hf, _), refine le_trans (add_le_add (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end lemma bounded_by_caratheodory {m : set α → ennreal} {s : set α} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (bounded_by m).caratheodory.is_measurable' s := begin apply of_function_caratheodory, intro t, cases t.eq_empty_or_nonempty with h h, { simp [h, empty_not_nonempty] }, { convert le_trans _ (hs t), { simp [h] }, exact add_le_add supr_const_le supr_const_le } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_iff_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s lemma Inf_gen_def (m : set (outer_measure α)) (t : set α) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := rfl lemma Inf_eq_bounded_by_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.bounded_by (Inf_gen m) := begin refine le_antisymm _ _, { refine (le_bounded_by.2 $ λ s, _), refine le_binfi _, intros μ hμ, refine (show Inf m ≤ μ, from Inf_le hμ) s }, { refine le_Inf _, intros μ hμ t, refine le_trans (bounded_by_le t) (binfi_le μ hμ) } end lemma supr_Inf_gen_nonempty {m : set (outer_measure α)} (h : m.nonempty) (t : set α) : (⨆ (h : t.nonempty), Inf_gen m t) = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin rcases t.eq_empty_or_nonempty with rfl|ht, { rcases h with ⟨μ, hμ⟩, rw [eq_false_intro empty_not_nonempty, supr_false, eq_comm], simp_rw [empty'], apply bot_unique, refine infi_le_of_le μ (infi_le _ hμ) }, { simp [ht, Inf_gen_def] } end /-- The value of the Infimum of a nonempty set of outer measures on a set is not simply the minimum value of a measure on that set: it is the infimum sum of measures of countable set of sets that covers that set, where a different measure can be used for each set in the cover. -/ lemma Inf_apply {m : set (outer_measure α)} {s : set α} (h : m.nonempty) : Inf m s = ⨅ (t : ℕ → set α) (h2 : s ⊆ Union t), ∑' n, ⨅ (μ : outer_measure α) (h3 : μ ∈ m), μ (t n) := by simp_rw [Inf_eq_bounded_by_Inf_gen, bounded_by_apply, supr_Inf_gen_nonempty h] /-- This proves that Inf and restrict commute for outer measures, so long as the set of outer measures is nonempty. -/ lemma restrict_Inf_eq_Inf_restrict (m : set (outer_measure α)) {s : set α} (hm : m.nonempty) : restrict s (Inf m) = Inf ((restrict s) '' m) := begin have hm2 : ((measure_theory.outer_measure.restrict s) '' m).nonempty := set.nonempty_image_iff.mpr hm, ext1 u, rw [restrict_apply, Inf_apply hm, Inf_apply hm2], apply le_antisymm; simp only [set.mem_image, infi_exists, le_infi_iff]; intros t hu, { refine infi_le_of_le (λ n, (t n) ∩ s) _, refine infi_le_of_le _ _, { rw [← Union_inter], exact inter_subset_inter hu subset.rfl }, apply ennreal.tsum_le_tsum (λ n, _) , simp only [and_imp, set.mem_image, infi_exists, le_infi_iff], rintro _ ⟨μ, h_μ_in_s, rfl⟩, refine infi_le_of_le μ _, refine infi_le_of_le h_μ_in_s _, simp_rw [restrict_apply, le_refl] }, { refine infi_le_of_le (λ n, (t n) ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [inter_subset, set.union_comm, Union_union] at hu }, apply ennreal.tsum_le_tsum (λ n, _), refine le_binfi (λ μ hμ, _), refine infi_le_of_le (restrict s μ) _, refine infi_le_of_le ⟨_, hμ, rfl⟩ _, rw [restrict_apply, union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, end end Inf_gen end outer_measure open outer_measure /-! ### Induced Outer Measure We can extend a function defined on a subset of `set α` to an outer measure. The underlying function is called `extend`, and the measure it induces is called `induced_outer_measure`. Some lemmas below are proven twice, once in the general case, and one where the function `m` is only defined on measurable sets (i.e. when `P = is_measurable`). In the latter cases, we can remove some hypotheses in the statement. The general version has the same name, but with a prime at the end. -/ section extend variables {α : Type*} {P : α → Prop} variables (m : Π (s : α), P s → ennreal) /-- We can trivially extend a function defined on a subclass of objects (with codomain `ennreal`) to all objects by defining it to be `∞` on the objects not in the class. -/ def extend (s : α) : ennreal := ⨅ h : P s, m s h lemma extend_eq {s : α} (h : P s) : extend m s = m s h := by simp [extend, h] lemma le_extend {s : α} (h : P s) : m s h ≤ extend m s := by { simp only [extend, le_infi_iff], intro, refl' } end extend section extend_set variables {α : Type*} {P : set α → Prop} variables {m : Π (s : set α), P s → ennreal} variables (P0 : P ∅) (m0 : m ∅ P0 = 0) variables (PU : ∀{{f : ℕ → set α}} (hm : ∀i, P (f i)), P (⋃i, f i)) variables (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), pairwise (disjoint on f) → m (⋃i, f i) (PU hm) = (∑'i, m (f i) (hm i))) variables (msU : ∀ {{f : ℕ → set α}} (hm : ∀i, P (f i)), m (⋃i, f i) (PU hm) ≤ (∑'i, m (f i) (hm i))) variables (m_mono : ∀⦃s₁ s₂ : set α⦄ (hs₁ : P s₁) (hs₂ : P s₂), s₁ ⊆ s₂ → m s₁ hs₁ ≤ m s₂ hs₂) lemma extend_empty : extend m ∅ = 0 := (extend_eq _ P0).trans m0 lemma extend_Union_nat {f : ℕ → set α} (hm : ∀i, P (f i)) (mU : m (⋃i, f i) (PU hm) = (∑'i, m (f i) (hm i))) : extend m (⋃i, f i) = (∑'i, extend m (f i)) := (extend_eq _ _).trans $ mU.trans $ by { congr' with i, rw extend_eq } section subadditive include PU msU lemma extend_Union_le_tsum_nat' (s : ℕ → set α) : extend m (⋃i, s i) ≤ (∑'i, extend m (s i)) := begin by_cases h : ∀i, P (s i), { rw [extend_eq _ (PU h), congr_arg tsum _], { apply msU h }, funext i, apply extend_eq _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end end subadditive section mono include m_mono lemma extend_mono' ⦃s₁ s₂ : set α⦄ (h₁ : P s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := by { refine le_infi _, intro h₂, rw [extend_eq m h₁], exact m_mono h₁ h₂ hs } end mono section unions include P0 m0 PU mU lemma extend_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, P (f i)) : extend m (⋃i, f i) = (∑'i, extend m (f i)) := begin rw [← encodable.Union_decode2, ← tsum_Union_decode2], { exact extend_Union_nat PU (λ n, encodable.Union_decode2_cases P0 hm) (mU _ (encodable.Union_decode2_disjoint_on hd)) }, { exact extend_empty P0 m0 } end lemma extend_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : P s₁) (h₂ : P s₂) : extend m (s₁ ∪ s₂) = extend m s₁ + extend m s₂ := begin rw [union_eq_Union, extend_Union P0 m0 PU mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], simp end end unions variable (m) /-- Given an arbitrary function on a subset of sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on the domain of `m`). -/ def induced_outer_measure : outer_measure α := outer_measure.of_function (extend m) (extend_empty P0 m0) variables {m P0 m0} include msU m_mono lemma induced_outer_measure_eq_extend' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = extend m s := of_function_eq s (λ t, extend_mono' m_mono hs) (extend_Union_le_tsum_nat' PU msU) lemma induced_outer_measure_eq' {s : set α} (hs : P s) : induced_outer_measure m P0 m0 s = m s hs := (induced_outer_measure_eq_extend' PU msU m_mono hs).trans $ extend_eq _ _ lemma induced_outer_measure_eq_infi (s : set α) : induced_outer_measure m P0 m0 s = ⨅ (t : set α) (ht : P t) (h : s ⊆ t), m t ht := begin apply le_antisymm, { simp only [le_infi_iff], intros t ht, simp only [le_infi_iff], intro hs, refine le_trans (mono' _ hs) _, exact le_of_eq (induced_outer_measure_eq' _ msU m_mono _) }, { refine le_infi _, intro f, refine le_infi _, intro hf, refine le_trans _ (extend_Union_le_tsum_nat' _ msU _), refine le_infi _, intro h2f, refine infi_le_of_le _ (infi_le_of_le h2f $ infi_le _ hf) } end lemma induced_outer_measure_preimage (f : α ≃ α) (Pm : ∀ (s : set α), P (f ⁻¹' s) ↔ P s) (mm : ∀ (s : set α) (hs : P s), m (f ⁻¹' s) ((Pm _).mpr hs) = m s hs) {A : set α} : induced_outer_measure m P0 m0 (f ⁻¹' A) = induced_outer_measure m P0 m0 A := begin simp only [induced_outer_measure_eq_infi _ msU m_mono], symmetry, refine infi_congr (preimage f) f.injective.preimage_surjective _, intro s, refine infi_congr_Prop (Pm s) _, intro hs, refine infi_congr_Prop f.surjective.preimage_subset_preimage_iff _, intro h2s, exact mm s hs end lemma induced_outer_measure_exists_set {s : set α} (hs : induced_outer_measure m P0 m0 s < ⊤) {ε : nnreal} (hε : 0 < ε) : ∃ (t : set α) (ht : P t), s ⊆ t ∧ induced_outer_measure m P0 m0 t ≤ induced_outer_measure m P0 m0 s + ε := begin have := ennreal.lt_add_right hs (ennreal.zero_lt_coe_iff.2 hε), conv at this {to_lhs, rw induced_outer_measure_eq_infi _ msU m_mono }, simp only [infi_lt_iff] at this, rcases this with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h1t, h2t, le_trans (le_of_eq $ induced_outer_measure_eq' _ msU m_mono h1t) (le_of_lt h3t)⟩ end /-- To test whether `s` is Carathéodory-measurable we only need to check the sets `t` for which `P t` holds. See `of_function_caratheodory` for another way to show the Carathéodory-measurability of `s`. -/ lemma induced_outer_measure_caratheodory (s : set α) : (induced_outer_measure m P0 m0).caratheodory.is_measurable' s ↔ ∀ (t : set α), P t → induced_outer_measure m P0 m0 (t ∩ s) + induced_outer_measure m P0 m0 (t \ s) ≤ induced_outer_measure m P0 m0 t := begin rw is_caratheodory_iff_le, split, { intros h t ht, exact h t }, { intros h u, conv_rhs { rw induced_outer_measure_eq_infi _ msU m_mono }, refine le_infi _, intro t, refine le_infi _, intro ht, refine le_infi _, intro h2t, refine le_trans _ (le_trans (h t ht) $ le_of_eq $ induced_outer_measure_eq' _ msU m_mono ht), refine add_le_add (mono' _ $ set.inter_subset_inter_left _ h2t) (mono' _ $ diff_subset_diff_left h2t) } end end extend_set /-! If `P` is `is_measurable` for some measurable space, then we can remove some hypotheses of the above lemmas. -/ section measurable_space variables {α : Type*} [measurable_space α] variables {m : Π (s : set α), is_measurable s → ennreal} variables (m0 : m ∅ is_measurable.empty = 0) variable (mU : ∀ {{f : ℕ → set α}} (hm : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) include m0 mU lemma extend_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) : extend m s₁ ≤ extend m s₂ := begin refine le_infi _, intro h₂, have := extend_union is_measurable.empty m0 is_measurable.Union mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← extend_eq m, exact le_iff_exists_add.2 ⟨_, this⟩, end lemma extend_Union_le_tsum_nat : ∀ (s : ℕ → set α), extend m (⋃i, s i) ≤ (∑'i, extend m (s i)) := begin refine extend_Union_le_tsum_nat' is_measurable.Union _, intros f h, simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (is_measurable.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← extend_eq m, ← extend_eq m], exact extend_mono m0 mU (is_measurable.disjointed h _) (inter_subset_left _ _) end lemma induced_outer_measure_eq_extend {s : set α} (hs : is_measurable s) : induced_outer_measure m is_measurable.empty m0 s = extend m s := of_function_eq s (λ t, extend_mono m0 mU hs) (extend_Union_le_tsum_nat m0 mU) lemma induced_outer_measure_eq {s : set α} (hs : is_measurable s) : induced_outer_measure m is_measurable.empty m0 s = m s hs := (induced_outer_measure_eq_extend m0 mU hs).trans $ extend_eq _ _ end measurable_space namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := induced_outer_measure (λ s _, m s) is_measurable.empty m.empty theorem le_trim : m ≤ m.trim := le_of_function.mpr $ λ s, le_infi $ λ _, le_refl _ theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s := induced_outer_measure_eq' is_measurable.Union (λ f hf, m.Union_nat f) (λ _ _ _ _ h, m.mono h) hs theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by { unfold trim, congr, funext s hs, exact H hs } theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim := λ s, binfi_le_binfi $ λ f hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, is_measurable s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t := by { simp only [infi_comm] {single_pass := tt}, exact induced_outer_measure_eq_infi is_measurable.Union (λ f _, m.Union_nat f) (λ _ _ _ _ h, m.mono h) s } theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (le_trim _) @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ is_measurable.univ) (zero_le _) theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := begin ext1 s, simp only [trim_eq_infi', add_apply], rw ennreal.infi_add_infi, rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩, exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩, add_le_add (m₁.mono' (inter_subset_left _ _)) (m₂.mono' (inter_subset_right _ _))⟩, end theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_is_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ m t = 0 := begin erw [trim_eq_infi, infi_eq_bot] at h, choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ m t < n⁻¹, { assume n, have : (0 : ennreal) < n⁻¹ := (ennreal.inv_pos.2 $ ennreal.nat_ne_top _), rcases h _ this with ⟨t, ht⟩, use [t], simpa only [infi_lt_iff, exists_prop] using ht }, refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩, refine le_antisymm _ (zero_le _), refine le_of_tendsto_of_tendsto tendsto_const_nhds ennreal.tendsto_inv_nat_nhds_zero (eventually_of_forall $ assume n, _), exact le_trans (m.mono' $ Inter_subset _ _) (le_of_lt (ht n).2.2) end theorem trim_smul (c : ennreal) (m : outer_measure α) : (c • m).trim = c • m.trim := begin ext1 s, simp only [trim_eq_infi', smul_apply], haveI : nonempty {t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ _, is_measurable.univ⟩⟩, refine ennreal.infi_mul_left (assume hc hs, _), rw ← trim_eq_infi' at hs, simpa [and_assoc] using exists_is_measurable_superset_of_trim_eq_zero hs end /-- The trimmed property of a measure μ states that `μ.to_outer_measure.trim = μ.to_outer_measure`. This theorem shows that a restricted trimmed outer measure is a trimmed outer measure. -/ lemma restrict_trim {μ : outer_measure α} {s : set α} (hs : is_measurable s) : (restrict s μ).trim = restrict s μ.trim := begin apply measure_theory.outer_measure.ext, intro t, simp_rw [restrict_apply, trim_eq_infi, restrict_apply], apply le_antisymm, { simp only [le_infi_iff], intros v h_subset hv, refine infi_le_of_le (v ∪ sᶜ) _, refine infi_le_of_le _ _, { rwa [set.union_comm, ← inter_subset] }, refine infi_le_of_le (hv.union hs.compl) _, rw [union_inter_distrib_right, compl_inter_self, set.union_empty], exact μ.mono (inter_subset_left _ _) }, { simp only [le_infi_iff], intros u h_subset hu, refine infi_le_of_le (u ∩ s) _, refine infi_le_of_le (set.inter_subset_inter_left _ h_subset) _, refine infi_le_of_le (hu.inter hs) le_rfl }, end end outer_measure end measure_theory
27dfa782bf2ecbfd085bfdeded35d8bce197fdb8
6214e13b31733dc9aeb4833db6a6466005763162
/src/eqdec.lean
a563f31ca8574129c4fa7b1e7b37ba66c2ac46ea
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
55,031
lean
-- decidable equality of values, terms, expressions, etc. import .syntax .etc .sizeof instance : decidable_eq unop := by tactic.mk_dec_eq_instance instance : decidable_eq binop := by tactic.mk_dec_eq_instance def wf_measure : has_well_founded (psum (Σ' (v₁ : value), value) (psum (Σ' (e₁ : exp), exp) (psum (Σ' (t₁ : term), term) (psum (Σ' (R : spec), spec) (Σ' (σ₁ : env), env))))) := ⟨_, measure_wf $ λ s, match s with | psum.inl a := a.1.sizeof | psum.inr (psum.inl a) := a.1.sizeof | psum.inr (psum.inr (psum.inl a)) := a.1.sizeof | psum.inr (psum.inr (psum.inr (psum.inl a))) := a.1.sizeof | psum.inr (psum.inr (psum.inr (psum.inr a))) := a.1.sizeof end⟩ mutual def value.dec_eq, exp.dec_eq, term.dec_eq, spec.dec_eq, env.dec_eq with value.dec_eq : ∀ (v₁ v₂: value), decidable (v₁ = v₂) | v₁ v₂ := let z := v₁ in have h: z = v₁, from rfl, value.cases_on (λv₁, (z = v₁) → decidable (v₁ = v₂)) v₁ ( assume : z = value.true, show decidable (value.true = v₂), from value.cases_on (λv₂, decidable (value.true = v₂)) v₂ ( show decidable (value.true = value.true), from is_true rfl ) ( have value.true ≠ value.false, by contradiction, show decidable (value.true = value.false), from is_false this ) ( assume n: ℤ, have value.true ≠ value.num n, by contradiction, show decidable (value.true = value.num n), from is_false this ) ( assume f x R S e σ, have value.true ≠ value.func f x R S e σ, by contradiction, show decidable (value.true = value.func f x R S e σ), from is_false this ) ) ( assume : z = value.false, show decidable (value.false = v₂), from value.cases_on (λv₂, decidable (value.false = v₂)) v₂ ( have value.false ≠ value.true, by contradiction, show decidable (value.false = value.true), from is_false this ) ( show decidable (value.false = value.false), from is_true rfl ) ( assume n: ℤ, have value.false ≠ value.num n, by contradiction, show decidable (value.false = value.num n), from is_false this ) ( assume f x R S e σ, have value.false ≠ value.func f x R S e σ, by contradiction, show decidable (value.false = value.func f x R S e σ), from is_false this ) ) ( assume n₁: ℤ, assume : z = value.num n₁, show decidable (value.num n₁ = v₂), from value.cases_on (λv₂, decidable (value.num n₁ = v₂)) v₂ ( have value.num n₁ ≠ value.true, by contradiction, show decidable (value.num n₁ = value.true), from is_false this ) ( have value.num n₁ ≠ value.false, by contradiction, show decidable (value.num n₁ = value.false), from is_false this ) ( assume n₂: ℤ, if h: n₁ = n₂ then ( have value.num n₁ = value.num n₂, from h ▸ rfl, show decidable (value.num n₁ = value.num n₂), from is_true this ) else ( have value.num n₁ ≠ value.num n₂, from ( assume : value.num n₁ = value.num n₂, have n₁ = n₂, from value.num.inj this, show «false», from h this ), show decidable (value.num n₁ = value.num n₂), from is_false this ) ) ( assume f x R S e σ, have value.num n₁ ≠ value.func f x R S e σ, by contradiction, show decidable (value.num n₁ = value.func f x R S e σ), from is_false this ) ) ( assume f₁ x₁ R₁ S₁ e₁ σ₁, assume : z = value.func f₁ x₁ R₁ S₁ e₁ σ₁, have v₁_is_func: v₁ = value.func f₁ x₁ R₁ S₁ e₁ σ₁, from eq.trans h this, show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = v₂), from value.cases_on (λv₂, decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = v₂)) v₂ ( have value.func f₁ x₁ R₁ S₁ e₁ σ₁ ≠ value.true, by contradiction, show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.true), from is_false this ) ( have value.func f₁ x₁ R₁ S₁ e₁ σ₁ ≠ value.false, by contradiction, show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.false), from is_false this ) ( assume n: ℤ, have value.func f₁ x₁ R₁ S₁ e₁ σ₁ ≠ value.num n, by contradiction, show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.num n), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂ σ₂, have R₁.sizeof < v₁.sizeof, from v₁_is_func.symm ▸ sizeof_value_func_R, have decidable (R₁ = R₂), from spec.dec_eq R₁ R₂, have S₁.sizeof < v₁.sizeof, from v₁_is_func.symm ▸ sizeof_value_func_S, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, have e₁.sizeof < v₁.sizeof, from v₁_is_func.symm ▸ sizeof_value_func_e, have decidable (e₁ = e₂), from exp.dec_eq e₁ e₂, have σ₁.sizeof < v₁.sizeof, from v₁_is_func.symm ▸ sizeof_value_func_σ, have decidable (σ₁ = σ₂), from env.dec_eq σ₁ σ₂, if h: (f₁ = f₂) ∧ (x₁ = x₂) ∧ (R₁ = R₂) ∧ (S₁ = S₂) ∧ (e₁ = e₂) ∧ (σ₁ = σ₂) then ( have value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.func f₂ x₂ R₂ S₂ e₂ σ₂, from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right.left ▸ h.right.right.right.right.left ▸ h.right.right.right.right.right ▸ rfl, show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.func f₂ x₂ R₂ S₂ e₂ σ₂), from is_true this ) else ( have value.func f₁ x₁ R₁ S₁ e₁ σ₁ ≠ value.func f₂ x₂ R₂ S₂ e₂ σ₂, from ( assume : value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.func f₂ x₂ R₂ S₂ e₂ σ₂, show «false», from h (value.func.inj this) ), show decidable (value.func f₁ x₁ R₁ S₁ e₁ σ₁ = value.func f₂ x₂ R₂ S₂ e₂ σ₂), from is_false this ) ) ) rfl with exp.dec_eq : ∀ (e₁ e₂: exp), decidable (e₁ = e₂) | e₁ e₂ := let z := e₁ in have h: z = e₁, from rfl, exp.cases_on (λe₁, (z = e₁) → decidable (e₁ = e₂)) e₁ ( assume x₁ e₁', assume : z = exp.true x₁ e₁', have e₁_is_tru: e₁ = exp.true x₁ e₁', from eq.trans h this, show decidable (exp.true x₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.true x₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_tru.symm ▸ sizeof_exp_true, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (e₁' = e₂') then ( have exp.true x₁ e₁' = exp.true x₂ e₂', from h.left ▸ h.right ▸ rfl, show decidable (exp.true x₁ e₁' = exp.true x₂ e₂'), from is_true this ) else ( have exp.true x₁ e₁' ≠ exp.true x₂ e₂', from ( assume : exp.true x₁ e₁' = exp.true x₂ e₂', show «false», from h (exp.true.inj this) ), show decidable (exp.true x₁ e₁' = exp.true x₂ e₂'), from is_false this ) ) ( assume x₂ e₂', have exp.true x₁ e₁' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.true x₁ e₁' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.true x₁ e₁' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.true x₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.true x₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.true x₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.true x₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.true x₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.true x₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.true x₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.true x₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.true x₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.true x₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.true x₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.true x₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.true x₁ e₁' = exp.return x₂), from is_false this ) ) ( assume x₁ e₁', assume : z = exp.false x₁ e₁', have e₁_is_false: e₁ = exp.false x₁ e₁', from eq.trans h this, show decidable (exp.false x₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.false x₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have exp.false x₁ e₁' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.false x₁ e₁' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_false.symm ▸ sizeof_exp_false, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (e₁' = e₂') then ( have exp.false x₁ e₁' = exp.false x₂ e₂', from h.left ▸ h.right ▸ rfl, show decidable (exp.false x₁ e₁' = exp.false x₂ e₂'), from is_true this ) else ( have exp.false x₁ e₁' ≠ exp.false x₂ e₂', from ( assume : exp.false x₁ e₁' = exp.false x₂ e₂', show «false», from h (exp.false.inj this) ), show decidable (exp.false x₁ e₁' = exp.false x₂ e₂'), from is_false this ) ) ( assume x₂ n₂ e₂', have exp.false x₁ e₁' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.false x₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.false x₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.false x₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.false x₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.false x₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.false x₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.false x₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.false x₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.false x₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.false x₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.false x₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.false x₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.false x₁ e₁' = exp.return x₂), from is_false this ) ) ( assume x₁ n₁ e₁', assume : z = exp.num x₁ n₁ e₁', have e₁_is_num: e₁ = exp.num x₁ n₁ e₁', from eq.trans h this, show decidable (exp.num x₁ n₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.num x₁ n₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have exp.num x₁ n₁ e₁' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.num x₁ n₁ e₁' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_num.symm ▸ sizeof_exp_num, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (n₁ = n₂) ∧ (e₁' = e₂') then ( have exp.num x₁ n₁ e₁' = exp.num x₂ n₂ e₂', from h.left ▸ h.right.left ▸ h.right.right ▸ rfl, show decidable (exp.num x₁ n₁ e₁' = exp.num x₂ n₂ e₂'), from is_true this ) else ( have exp.num x₁ n₁ e₁' ≠ exp.num x₂ n₂ e₂', from ( assume : exp.num x₁ n₁ e₁' = exp.num x₂ n₂ e₂', show «false», from h (exp.num.inj this) ), show decidable (exp.num x₁ n₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.num x₁ n₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.num x₁ n₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.num x₁ n₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.num x₁ n₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.num x₁ n₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.num x₁ n₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.num x₁ n₁ e₁' = exp.return x₂), from is_false this ) ) ( assume f₁ x₁ R₁ S₁ e₁' e₁'', assume : z = exp.func f₁ x₁ R₁ S₁ e₁' e₁'', have e₁_is_func: e₁ = exp.func f₁ x₁ R₁ S₁ e₁' e₁'', from eq.trans h this, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = e₂), from exp.cases_on (λe₂, decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = e₂)) e₂ ( assume x₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have R₁.sizeof < e₁.sizeof, from e₁_is_func.symm ▸ sizeof_exp_func_R, have decidable (R₁ = R₂), from spec.dec_eq R₁ R₂, have S₁.sizeof < e₁.sizeof, from e₁_is_func.symm ▸ sizeof_exp_func_S, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, have e₁'.sizeof < e₁.sizeof, from e₁_is_func.symm ▸ sizeof_exp_func_e₁, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', have e₁''.sizeof < e₁.sizeof, from e₁_is_func.symm ▸ sizeof_exp_func_e₂, have decidable (e₁'' = e₂''), from exp.dec_eq e₁'' e₂'', if h: (f₁ = f₂) ∧ (x₁ = x₂) ∧ (R₁ = R₂) ∧ (S₁ = S₂) ∧ (e₁' = e₂') ∧ (e₁'' = e₂'') then ( have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.func f₂ x₂ R₂ S₂ e₂' e₂'', from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right.left ▸ h.right.right.right.right.left ▸ h.right.right.right.right.right ▸ rfl, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_true this ) else ( have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', from ( assume : exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.func f₂ x₂ R₂ S₂ e₂' e₂'', show «false», from h (exp.func.inj this) ), show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ) ( assume x₂ op₂ y₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.func f₁ x₁ R₁ S₁ e₁' e₁'' ≠ exp.return x₂, by contradiction, show decidable (exp.func f₁ x₁ R₁ S₁ e₁' e₁'' = exp.return x₂), from is_false this ) ) ( assume x₁ op₁ y₁ e₁', assume : z = exp.unop x₁ op₁ y₁ e₁', have e₁_is_unop: e₁ = exp.unop x₁ op₁ y₁ e₁', from eq.trans h this, show decidable (exp.unop x₁ op₁ y₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.unop x₁ op₁ y₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_unop.symm ▸ sizeof_exp_unop, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (op₁ = op₂) ∧ (y₁ = y₂) ∧ (e₁' = e₂') then ( have exp.unop x₁ op₁ y₁ e₁' = exp.unop x₂ op₂ y₂ e₂', from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right ▸ rfl, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_true this ) else ( have exp.unop x₁ op₁ y₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', from ( assume : exp.unop x₁ op₁ y₁ e₁' = exp.unop x₂ op₂ y₂ e₂', show «false», from h (exp.unop.inj this) ), show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.unop x₁ op₁ y₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.unop x₁ op₁ y₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.unop x₁ op₁ y₁ e₁' = exp.return x₂), from is_false this ) ) ( assume x₁ op₁ y₁ z₁ e₁', assume : z = exp.binop x₁ op₁ y₁ z₁ e₁', have e₁_is_binop: e₁ = exp.binop x₁ op₁ y₁ z₁ e₁', from eq.trans h this, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_binop.symm ▸ sizeof_exp_binop, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (op₁ = op₂) ∧ (y₁ = y₂) ∧ (z₁ = z₂) ∧ (e₁' = e₂') then ( have exp.binop x₁ op₁ y₁ z₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂', from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right.left ▸ h.right.right.right.right ▸ rfl, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_true this ) else ( have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', from ( assume : exp.binop x₁ op₁ y₁ z₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂', show «false», from h (exp.binop.inj this) ), show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ) ( assume x₂ y₂ z₂ e₂', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.binop x₁ op₁ y₁ z₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.binop x₁ op₁ y₁ z₁ e₁' = exp.return x₂), from is_false this ) ) ( assume x₁ y₁ z₁ e₁', assume : z = exp.app x₁ y₁ z₁ e₁', have e₁_is_app: e₁ = exp.app x₁ y₁ z₁ e₁', from eq.trans h this, show decidable (exp.app x₁ y₁ z₁ e₁' = e₂), from exp.cases_on (λe₂, decidable (exp.app x₁ y₁ z₁ e₁' = e₂)) e₂ ( assume x₂ e₂', have exp.app x₁ y₁ z₁ e₁' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.app x₁ y₁ z₁ e₁' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.app x₁ y₁ z₁ e₁' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.app x₁ y₁ z₁ e₁' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.app x₁ y₁ z₁ e₁' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.app x₁ y₁ z₁ e₁' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have e₁'.sizeof < e₁.sizeof, from e₁_is_app.symm ▸ sizeof_exp_app, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', if h: (x₁ = x₂) ∧ (y₁ = y₂) ∧ (z₁ = z₂) ∧ (e₁' = e₂') then ( have exp.app x₁ y₁ z₁ e₁' = exp.app x₂ y₂ z₂ e₂', from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right ▸ rfl, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_true this ) else ( have exp.app x₁ y₁ z₁ e₁' ≠ exp.app x₂ y₂ z₂ e₂', from ( assume : exp.app x₁ y₁ z₁ e₁' = exp.app x₂ y₂ z₂ e₂', show «false», from h (exp.app.inj this) ), show decidable (exp.app x₁ y₁ z₁ e₁' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ) ( assume x₂ e₂' e₂'', have exp.app x₁ y₁ z₁ e₁' ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, have exp.app x₁ y₁ z₁ e₁' ≠ exp.return x₂, by contradiction, show decidable (exp.app x₁ y₁ z₁ e₁' = exp.return x₂), from is_false this ) ) ( assume x₁ e₁' e₁'', assume : z = exp.ite x₁ e₁' e₁'', have e₁_is_ite: e₁ = exp.ite x₁ e₁' e₁'', from eq.trans h this, show decidable (exp.ite x₁ e₁' e₁'' = e₂), from exp.cases_on (λe₂, decidable (exp.ite x₁ e₁' e₁'' = e₂)) e₂ ( assume x₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.ite x₁ e₁' e₁'' ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.ite x₁ e₁' e₁'' ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have e₁'.sizeof < e₁.sizeof, from e₁_is_ite.symm ▸ sizeof_exp_ite_e₁, have decidable (e₁' = e₂'), from exp.dec_eq e₁' e₂', have e₁''.sizeof < e₁.sizeof, from e₁_is_ite.symm ▸ sizeof_exp_ite_e₂, have decidable (e₁'' = e₂''), from exp.dec_eq e₁'' e₂'', if h: (x₁ = x₂) ∧ (e₁' = e₂') ∧ (e₁'' = e₂'') then ( have exp.ite x₁ e₁' e₁'' = exp.ite x₂ e₂' e₂'', from h.left ▸ h.right.left ▸ h.right.right ▸ rfl, show decidable (exp.ite x₁ e₁' e₁'' = exp.ite x₂ e₂' e₂''), from is_true this ) else ( have exp.ite x₁ e₁' e₁'' ≠ exp.ite x₂ e₂' e₂'', from ( assume : exp.ite x₁ e₁' e₁'' = exp.ite x₂ e₂' e₂'', show «false», from h (exp.ite.inj this) ), show decidable (exp.ite x₁ e₁' e₁'' = exp.ite x₂ e₂' e₂''), from is_false this ) ) ( assume x₂, have exp.ite x₁ e₁' e₁'' ≠ exp.return x₂, by contradiction, show decidable (exp.ite x₁ e₁' e₁'' = exp.return x₂), from is_false this ) ) ( assume x₁, assume : z = exp.return x₁, have e₁_is_tru: e₁ = exp.return x₁, from eq.trans h this, show decidable (exp.return x₁ = e₂), from exp.cases_on (λe₂, decidable (exp.return x₁ = e₂)) e₂ ( assume x₂ e₂', have exp.return x₁ ≠ exp.true x₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.true x₂ e₂'), from is_false this ) ( assume x₂ e₂', have exp.return x₁ ≠ exp.false x₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.false x₂ e₂'), from is_false this ) ( assume x₂ n₂ e₂', have exp.return x₁ ≠ exp.num x₂ n₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.num x₂ n₂ e₂'), from is_false this ) ( assume f₂ x₂ R₂ S₂ e₂' e₂'', have exp.return x₁ ≠ exp.func f₂ x₂ R₂ S₂ e₂' e₂'', by contradiction, show decidable (exp.return x₁ = exp.func f₂ x₂ R₂ S₂ e₂' e₂''), from is_false this ) ( assume x₂ op₂ y₂ e₂', have exp.return x₁ ≠ exp.unop x₂ op₂ y₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.unop x₂ op₂ y₂ e₂'), from is_false this ) ( assume x₂ op₂ y₂ z₂ e₂', have exp.return x₁ ≠ exp.binop x₂ op₂ y₂ z₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.binop x₂ op₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ y₂ z₂ e₂', have exp.return x₁ ≠ exp.app x₂ y₂ z₂ e₂', by contradiction, show decidable (exp.return x₁ = exp.app x₂ y₂ z₂ e₂'), from is_false this ) ( assume x₂ e₂' e₂'', have exp.return x₁ ≠ exp.ite x₂ e₂' e₂'', by contradiction, show decidable (exp.return x₁ = exp.ite x₂ e₂' e₂''), from is_false this ) ( assume x₂, if h: x₁ = x₂ then ( have exp.return x₁ = exp.return x₂, from h ▸ rfl, show decidable (exp.return x₁ = exp.return x₂), from is_true this ) else ( have exp.return x₁ ≠ exp.return x₂, from ( assume : exp.return x₁ = exp.return x₂, show «false», from h (exp.return.inj this) ), show decidable (exp.return x₁ = exp.return x₂), from is_false this ) ) ) rfl with term.dec_eq : ∀ (t₁ t₂: term), decidable (t₁ = t₂) | t₁ t₂ := let z := t₁ in have h: z = t₁, from rfl, term.cases_on (λt₁, (z = t₁) → decidable (t₁ = t₂)) t₁ ( assume v₁, assume : z = term.value v₁, have t₁_id: t₁ = term.value v₁, from eq.trans h this, show decidable (term.value v₁ = t₂), from term.cases_on (λt₂, decidable (term.value v₁ = t₂)) t₂ ( assume v₂, have v₁.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_value, have decidable (v₁ = v₂), from value.dec_eq v₁ v₂, if h: v₁ = v₂ then ( have term.value v₁ = term.value v₂, from h ▸ rfl, show decidable (term.value v₁ = term.value v₂), from is_true this ) else ( have term.value v₁ ≠ term.value v₂, from ( assume : term.value v₁ = term.value v₂, show «false», from h (term.value.inj this) ), show decidable (term.value v₁ = term.value v₂), from is_false this ) ) ( assume x₂, have term.value v₁ ≠ term.var x₂, by contradiction, show decidable (term.value v₁ = term.var x₂), from is_false this ) ( assume op₂ t₂', have term.value v₁ ≠ term.unop op₂ t₂', by contradiction, show decidable (term.value v₁ = term.unop op₂ t₂'), from is_false this ) ( assume op₂ t₂' t₂'', have term.value v₁ ≠ term.binop op₂ t₂' t₂'', by contradiction, show decidable (term.value v₁ = term.binop op₂ t₂' t₂''), from is_false this ) ( assume t₂' t₂'', have term.value v₁ ≠ term.app t₂' t₂'', by contradiction, show decidable (term.value v₁ = term.app t₂' t₂''), from is_false this ) ) ( assume x₁, assume : z = term.var x₁, have t₁_id: t₁ = term.var x₁, from eq.trans h this, show decidable (term.var x₁ = t₂), from term.cases_on (λt₂, decidable (term.var x₁ = t₂)) t₂ ( assume v₂, have term.var x₁ ≠ term.value v₂, by contradiction, show decidable (term.var x₁ = term.value v₂), from is_false this ) ( assume x₂, if h: x₁ = x₂ then ( have term.var x₁ = term.var x₂, from h ▸ rfl, show decidable (term.var x₁ = term.var x₂), from is_true this ) else ( have term.var x₁ ≠ term.var x₂, from ( assume : term.var x₁ = term.var x₂, show «false», from h (term.var.inj this) ), show decidable (term.var x₁ = term.var x₂), from is_false this ) ) ( assume op₂ t₂', have term.var x₁ ≠ term.unop op₂ t₂', by contradiction, show decidable (term.var x₁ = term.unop op₂ t₂'), from is_false this ) ( assume op₂ t₂' t₂'', have term.var x₁ ≠ term.binop op₂ t₂' t₂'', by contradiction, show decidable (term.var x₁ = term.binop op₂ t₂' t₂''), from is_false this ) ( assume t₂' t₂'', have term.var x₁ ≠ term.app t₂' t₂'', by contradiction, show decidable (term.var x₁ = term.app t₂' t₂''), from is_false this ) ) ( assume op₁ t₁', assume : z = term.unop op₁ t₁', have t₁_id: t₁ = term.unop op₁ t₁', from eq.trans h this, show decidable (term.unop op₁ t₁' = t₂), from term.cases_on (λt₂, decidable (term.unop op₁ t₁' = t₂)) t₂ ( assume v₂, have term.unop op₁ t₁' ≠ term.value v₂, by contradiction, show decidable (term.unop op₁ t₁' = term.value v₂), from is_false this ) ( assume x₂, have term.unop op₁ t₁' ≠ term.var x₂, by contradiction, show decidable (term.unop op₁ t₁' = term.var x₂), from is_false this ) ( assume op₂ t₂', have t₁'.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_unop, have decidable (t₁' = t₂'), from term.dec_eq t₁' t₂', if h: (op₁ = op₂) ∧ (t₁' = t₂') then ( have term.unop op₁ t₁' = term.unop op₂ t₂', from h.left ▸ h.right ▸ rfl, show decidable (term.unop op₁ t₁' = term.unop op₂ t₂'), from is_true this ) else ( have term.unop op₁ t₁' ≠ term.unop op₂ t₂', from ( assume : term.unop op₁ t₁' = term.unop op₂ t₂', show «false», from h (term.unop.inj this) ), show decidable (term.unop op₁ t₁' = term.unop op₂ t₂'), from is_false this ) ) ( assume op₂ t₂' t₂'', have term.unop op₁ t₁' ≠ term.binop op₂ t₂' t₂'', by contradiction, show decidable (term.unop op₁ t₁' = term.binop op₂ t₂' t₂''), from is_false this ) ( assume t₂' t₂'', have term.unop op₁ t₁' ≠ term.app t₂' t₂'', by contradiction, show decidable (term.unop op₁ t₁' = term.app t₂' t₂''), from is_false this ) ) ( assume op₁ t₁' t₁'', assume : z = term.binop op₁ t₁' t₁'', have t₁_id: t₁ = term.binop op₁ t₁' t₁'', from eq.trans h this, show decidable (term.binop op₁ t₁' t₁'' = t₂), from term.cases_on (λt₂, decidable (term.binop op₁ t₁' t₁'' = t₂)) t₂ ( assume v₂, have term.binop op₁ t₁' t₁'' ≠ term.value v₂, by contradiction, show decidable (term.binop op₁ t₁' t₁'' = term.value v₂), from is_false this ) ( assume x₂, have term.binop op₁ t₁' t₁'' ≠ term.var x₂, by contradiction, show decidable (term.binop op₁ t₁' t₁'' = term.var x₂), from is_false this ) ( assume op₂ t₂', have term.binop op₁ t₁' t₁'' ≠ term.unop op₂ t₂', by contradiction, show decidable (term.binop op₁ t₁' t₁'' = term.unop op₂ t₂'), from is_false this ) ( assume op₂ t₂' t₂'', have t₁'.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_binop₁, have decidable (t₁' = t₂'), from term.dec_eq t₁' t₂', have t₁''.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_binop₂, have decidable (t₁'' = t₂''), from term.dec_eq t₁'' t₂'', if h: (op₁ = op₂) ∧ (t₁' = t₂') ∧ (t₁'' = t₂'') then ( have term.binop op₁ t₁' t₁'' = term.binop op₂ t₂' t₂'', from h.left ▸ h.right.left ▸ h.right.right ▸ rfl, show decidable (term.binop op₁ t₁' t₁'' = term.binop op₂ t₂' t₂''), from is_true this ) else ( have term.binop op₁ t₁' t₁'' ≠ term.binop op₂ t₂' t₂'', from ( assume : term.binop op₁ t₁' t₁'' = term.binop op₂ t₂' t₂'', show «false», from h (term.binop.inj this) ), show decidable (term.binop op₁ t₁' t₁'' = term.binop op₂ t₂' t₂''), from is_false this ) ) ( assume t₂' t₂'', have term.binop op₁ t₁' t₁'' ≠ term.app t₂' t₂'', by contradiction, show decidable (term.binop op₁ t₁' t₁'' = term.app t₂' t₂''), from is_false this ) ) ( assume t₁' t₁'', assume : z = term.app t₁' t₁'', have t₁_id: t₁ = term.app t₁' t₁'', from eq.trans h this, show decidable (term.app t₁' t₁'' = t₂), from term.cases_on (λt₂, decidable (term.app t₁' t₁'' = t₂)) t₂ ( assume v₂, have term.app t₁' t₁'' ≠ term.value v₂, by contradiction, show decidable (term.app t₁' t₁'' = term.value v₂), from is_false this ) ( assume x₂, have term.app t₁' t₁'' ≠ term.var x₂, by contradiction, show decidable (term.app t₁' t₁'' = term.var x₂), from is_false this ) ( assume op₂ t₂', have term.app t₁' t₁'' ≠ term.unop op₂ t₂', by contradiction, show decidable (term.app t₁' t₁'' = term.unop op₂ t₂'), from is_false this ) ( assume op₂ t₂' t₂'', have term.app t₁' t₁'' ≠ term.binop op₂ t₂' t₂'', by contradiction, show decidable (term.app t₁' t₁'' = term.binop op₂ t₂' t₂''), from is_false this ) ( assume t₂' t₂'', have t₁'.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_app₁, have decidable (t₁' = t₂'), from term.dec_eq t₁' t₂', have t₁''.sizeof < t₁.sizeof, from t₁_id.symm ▸ sizeof_term_app₂, have decidable (t₁'' = t₂''), from term.dec_eq t₁'' t₂'', if h: (t₁' = t₂') ∧ (t₁'' = t₂'') then ( have term.app t₁' t₁'' = term.app t₂' t₂'', from h.left ▸ h.right ▸ rfl, show decidable (term.app t₁' t₁'' = term.app t₂' t₂''), from is_true this ) else ( have term.app t₁' t₁'' ≠ term.app t₂' t₂'', from ( assume : term.app t₁' t₁'' = term.app t₂' t₂'', show «false», from h (term.app.inj this) ), show decidable (term.app t₁' t₁'' = term.app t₂' t₂''), from is_false this ) ) ) rfl with spec.dec_eq : ∀ (R₁ R₂: spec), decidable (R₁ = R₂) | R₁ R₂ := let z := R₁ in have h: z = R₁, from rfl, spec.cases_on (λR₁, (z = R₁) → decidable (R₁ = R₂)) R₁ ( assume t₁, assume : z = spec.term t₁, have R₁_id: R₁ = spec.term t₁, from eq.trans h this, show decidable (spec.term t₁ = R₂), from spec.cases_on (λR₂, decidable (spec.term t₁ = R₂)) R₂ ( assume t₂, have t₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_term, have decidable (t₁ = t₂), from term.dec_eq t₁ t₂, if h: t₁ = t₂ then ( have spec.term t₁ = spec.term t₂, from h ▸ rfl, show decidable (spec.term t₁ = spec.term t₂), from is_true this ) else ( have spec.term t₁ ≠ spec.term t₂, from ( assume : spec.term t₁ = spec.term t₂, show «false», from h (spec.term.inj this) ), show decidable (spec.term t₁ = spec.term t₂), from is_false this ) ) ( assume S₂, have spec.term t₁ ≠ spec.not S₂, by contradiction, show decidable (spec.term t₁ = spec.not S₂), from is_false this ) ( assume S₂ S₂', have spec.term t₁ ≠ spec.and S₂ S₂', by contradiction, show decidable (spec.term t₁ = spec.and S₂ S₂'), from is_false this ) ( assume S₂ S₂', have spec.term t₁ ≠ spec.or S₂ S₂', by contradiction, show decidable (spec.term t₁ = spec.or S₂ S₂'), from is_false this ) ( assume t₂ x₂ S₂ S₂', have spec.term t₁ ≠ spec.func t₂ x₂ S₂ S₂', by contradiction, show decidable (spec.term t₁ = spec.func t₂ x₂ S₂ S₂'), from is_false this ) ) ( assume S₁, assume : z = spec.not S₁, have R₁_id: R₁ = spec.not S₁, from eq.trans h this, show decidable (spec.not S₁ = R₂), from spec.cases_on (λR₂, decidable (spec.not S₁ = R₂)) R₂ ( assume t₂, have spec.not S₁ ≠ spec.term t₂, by contradiction, show decidable (spec.not S₁ = spec.term t₂), from is_false this ) ( assume S₂, have S₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_not, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, if h: S₁ = S₂ then ( have spec.not S₁ = spec.not S₂, from h ▸ rfl, show decidable (spec.not S₁ = spec.not S₂), from is_true this ) else ( have spec.not S₁ ≠ spec.not S₂, from ( assume : spec.not S₁ = spec.not S₂, show «false», from h (spec.not.inj this) ), show decidable (spec.not S₁ = spec.not S₂), from is_false this ) ) ( assume S₂ S₂', have spec.not S₁ ≠ spec.and S₂ S₂', by contradiction, show decidable (spec.not S₁ = spec.and S₂ S₂'), from is_false this ) ( assume S₂ S₂', have spec.not S₁ ≠ spec.or S₂ S₂', by contradiction, show decidable (spec.not S₁ = spec.or S₂ S₂'), from is_false this ) ( assume t₂ x₂ S₂ S₂', have spec.not S₁ ≠ spec.func t₂ x₂ S₂ S₂', by contradiction, show decidable (spec.not S₁ = spec.func t₂ x₂ S₂ S₂'), from is_false this ) ) ( assume S₁ S₁', assume : z = spec.and S₁ S₁', have R₁_id: R₁ = spec.and S₁ S₁', from eq.trans h this, show decidable (spec.and S₁ S₁' = R₂), from spec.cases_on (λR₂, decidable (spec.and S₁ S₁' = R₂)) R₂ ( assume t₂, have spec.and S₁ S₁' ≠ spec.term t₂, by contradiction, show decidable (spec.and S₁ S₁' = spec.term t₂), from is_false this ) ( assume S₂, have spec.and S₁ S₁' ≠ spec.not S₂, by contradiction, show decidable (spec.and S₁ S₁' = spec.not S₂), from is_false this ) ( assume S₂ S₂', have S₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_and₁, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, have S₁'.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_and₂, have decidable (S₁' = S₂'), from spec.dec_eq S₁' S₂', if h: (S₁ = S₂) ∧ (S₁' = S₂') then ( have spec.and S₁ S₁' = spec.and S₂ S₂', from h.left ▸ h.right ▸ rfl, show decidable (spec.and S₁ S₁' = spec.and S₂ S₂'), from is_true this ) else ( have spec.and S₁ S₁' ≠ spec.and S₂ S₂', from ( assume : spec.and S₁ S₁' = spec.and S₂ S₂', show «false», from h (spec.and.inj this) ), show decidable (spec.and S₁ S₁' = spec.and S₂ S₂'), from is_false this ) ) ( assume S₂ S₂', have spec.and S₁ S₁' ≠ spec.or S₂ S₂', by contradiction, show decidable (spec.and S₁ S₁' = spec.or S₂ S₂'), from is_false this ) ( assume t₂ x₂ S₂ S₂', have spec.and S₁ S₁' ≠ spec.func t₂ x₂ S₂ S₂', by contradiction, show decidable (spec.and S₁ S₁' = spec.func t₂ x₂ S₂ S₂'), from is_false this ) ) ( assume S₁ S₁', assume : z = spec.or S₁ S₁', have R₁_id: R₁ = spec.or S₁ S₁', from eq.trans h this, show decidable (spec.or S₁ S₁' = R₂), from spec.cases_on (λR₂, decidable (spec.or S₁ S₁' = R₂)) R₂ ( assume t₂, have spec.or S₁ S₁' ≠ spec.term t₂, by contradiction, show decidable (spec.or S₁ S₁' = spec.term t₂), from is_false this ) ( assume S₂, have spec.or S₁ S₁' ≠ spec.not S₂, by contradiction, show decidable (spec.or S₁ S₁' = spec.not S₂), from is_false this ) ( assume S₂ S₂', have spec.or S₁ S₁' ≠ spec.and S₂ S₂', by contradiction, show decidable (spec.or S₁ S₁' = spec.and S₂ S₂'), from is_false this ) ( assume S₂ S₂', have S₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_and₁, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, have S₁'.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_and₂, have decidable (S₁' = S₂'), from spec.dec_eq S₁' S₂', if h: (S₁ = S₂) ∧ (S₁' = S₂') then ( have spec.or S₁ S₁' = spec.or S₂ S₂', from h.left ▸ h.right ▸ rfl, show decidable (spec.or S₁ S₁' = spec.or S₂ S₂'), from is_true this ) else ( have spec.or S₁ S₁' ≠ spec.or S₂ S₂', from ( assume : spec.or S₁ S₁' = spec.or S₂ S₂', show «false», from h (spec.or.inj this) ), show decidable (spec.or S₁ S₁' = spec.or S₂ S₂'), from is_false this ) ) ( assume t₂ x₂ S₂ S₂', have spec.or S₁ S₁' ≠ spec.func t₂ x₂ S₂ S₂', by contradiction, show decidable (spec.or S₁ S₁' = spec.func t₂ x₂ S₂ S₂'), from is_false this ) ) ( assume t₁ x₁ S₁ S₁', assume : z = spec.func t₁ x₁ S₁ S₁', have R₁_id: R₁ = spec.func t₁ x₁ S₁ S₁', from eq.trans h this, show decidable (spec.func t₁ x₁ S₁ S₁' = R₂), from spec.cases_on (λR₂, decidable (spec.func t₁ x₁ S₁ S₁' = R₂)) R₂ ( assume t₂, have spec.func t₁ x₁ S₁ S₁' ≠ spec.term t₂, by contradiction, show decidable (spec.func t₁ x₁ S₁ S₁' = spec.term t₂), from is_false this ) ( assume S₂, have spec.func t₁ x₁ S₁ S₁' ≠ spec.not S₂, by contradiction, show decidable (spec.func t₁ x₁ S₁ S₁' = spec.not S₂), from is_false this ) ( assume S₂ S₂', have spec.func t₁ x₁ S₁ S₁' ≠ spec.and S₂ S₂', by contradiction, show decidable (spec.func t₁ x₁ S₁ S₁' = spec.and S₂ S₂'), from is_false this ) ( assume S₂ S₂', have spec.func t₁ x₁ S₁ S₁' ≠ spec.or S₂ S₂', by contradiction, show decidable (spec.func t₁ x₁ S₁ S₁' = spec.or S₂ S₂'), from is_false this ) ( assume t₂ x₂ S₂ S₂', have t₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_func_t, have decidable (t₁ = t₂), from term.dec_eq t₁ t₂, have S₁.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_func_R, have decidable (S₁ = S₂), from spec.dec_eq S₁ S₂, have S₁'.sizeof < R₁.sizeof, from R₁_id.symm ▸ sizeof_spec_func_S, have decidable (S₁' = S₂'), from spec.dec_eq S₁' S₂', if h: (t₁ = t₂) ∧ (x₁ = x₂) ∧ (S₁ = S₂) ∧ (S₁' = S₂') then ( have spec.func t₁ x₁ S₁ S₁' = spec.func t₂ x₂ S₂ S₂', from h.left ▸ h.right.left ▸ h.right.right.left ▸ h.right.right.right ▸ rfl, show decidable (spec.func t₁ x₁ S₁ S₁' = spec.func t₂ x₂ S₂ S₂'), from is_true this ) else ( have spec.func t₁ x₁ S₁ S₁' ≠ spec.func t₂ x₂ S₂ S₂', from ( assume : spec.func t₁ x₁ S₁ S₁' = spec.func t₂ x₂ S₂ S₂', show «false», from h (spec.func.inj this) ), show decidable (spec.func t₁ x₁ S₁ S₁' = spec.func t₂ x₂ S₂ S₂'), from is_false this ) ) ) rfl with env.dec_eq : ∀ (σ₁ σ₂: env), decidable (σ₁ = σ₂) | σ₁ σ₂ := let z := σ₁ in have h: z = σ₁, from rfl, env.cases_on (λσ₁, (z = σ₁) → decidable (σ₁ = σ₂)) σ₁ ( assume : z = env.empty, have σ₁_id: σ₁ = env.empty, from eq.trans h this, show decidable (env.empty = σ₂), from env.cases_on (λσ₂, decidable (env.empty = σ₂)) σ₂ ( show decidable (env.empty = env.empty), from is_true rfl ) ( assume σ₂' x₂ v₂, have env.empty ≠ env.cons σ₂' x₂ v₂, by contradiction, show decidable (env.empty = env.cons σ₂' x₂ v₂), from is_false this ) ) ( assume σ₁' x₁ v₁, assume : z = env.cons σ₁' x₁ v₁, have σ₁_id: σ₁ = env.cons σ₁' x₁ v₁, from eq.trans h this, show decidable (env.cons σ₁' x₁ v₁ = σ₂), from env.cases_on (λσ₂, decidable (env.cons σ₁' x₁ v₁ = σ₂)) σ₂ ( have env.cons σ₁' x₁ v₁ ≠ env.empty, by contradiction, show decidable (env.cons σ₁' x₁ v₁ = env.empty), from is_false this ) ( assume σ₂' x₂ v₂, have σ₁'.sizeof < σ₁.sizeof, from σ₁_id.symm ▸ sizeof_env_rest, have decidable (σ₁' = σ₂'), from env.dec_eq σ₁' σ₂', have v₁.sizeof < σ₁.sizeof, from σ₁_id.symm ▸ sizeof_env_value, have decidable (v₁ = v₂), from value.dec_eq v₁ v₂, if h: (σ₁' = σ₂') ∧ (x₁ = x₂) ∧ (v₁ = v₂) then ( have env.cons σ₁' x₁ v₁ = env.cons σ₂' x₂ v₂, from h.left ▸ h.right.left ▸ h.right.right ▸ rfl, show decidable (env.cons σ₁' x₁ v₁ = env.cons σ₂' x₂ v₂), from is_true this ) else ( have env.cons σ₁' x₁ v₁ ≠ env.cons σ₂' x₂ v₂, from ( assume : env.cons σ₁' x₁ v₁ = env.cons σ₂' x₂ v₂, show «false», from h (env.cons.inj this) ), show decidable (env.cons σ₁' x₁ v₁ = env.cons σ₂' x₂ v₂), from is_false this ) ) ) rfl using_well_founded { rel_tac := λ _ _, `[exact wf_measure], dec_tac := tactic.assumption } instance : decidable_eq value := value.dec_eq
c294f5aa8c144bb0dfa9527c273deee7893f5cb3
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/fully_faithful.lean
f04d07e7b67e5faf0af2952975fdbc50f2cb05ab
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,820
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 category_theory.isomorphism universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables {C : Sort u₁} [𝒞 : category.{v₁} C] {D : Sort u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness class faithful (F : C ⥤ D) : Prop := (injectivity' : ∀ {X Y : C} {f g : X ⟶ Y} (p : F.map f = F.map g), f = g . obviously) restate_axiom faithful.injectivity' namespace functor def injectivity (F : C ⥤ D) [faithful F] {X Y : C} {f g : X ⟶ Y} (p : F.map f = F.map g) : f = g := faithful.injectivity F p def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor section variables {F : C ⥤ D} [full F] [faithful F] {X Y : C} def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := begin apply @faithful.injectivity _ _ _ _ F, obviously, end, inv_hom_id' := begin apply @faithful.injectivity _ _ _ _ F, obviously, end, } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl end class fully_faithful (F : C ⥤ D) extends (full F), (faithful F). @[simp] lemma preimage_id (F : C ⥤ D) [fully_faithful F] (X : C) : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.injectivity (by simp) end category_theory namespace category_theory variables {C : Sort u₁} [𝒞 : category.{v₁} C] include 𝒞 instance full.id : full (functor.id C) := { preimage := λ _ _ f, f } instance : faithful (functor.id C) := by obviously instance : fully_faithful (functor.id C) := { ((by apply_instance) : full (functor.id C)) with } variables {D : Sort u₂} [𝒟 : category.{v₂} D] {E : Sort u₃} [ℰ : category.{v₃} E] include 𝒟 ℰ variables (F : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { injectivity' := λ _ _ _ _ p, F.injectivity (G.injectivity p) } instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } end category_theory
b4de842d6b8ab42d27f3dcd2d489a9ab2e34148c
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/whiskering.lean
aff7bdfaee451d8183efccfe44c88f3afeec3aab
[ "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
5,787
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 category_theory.natural_isomorphism namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ u₄ v₄ section variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] @[simps] def whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) : (F ⋙ G) ⟶ (F ⋙ H) := { app := λ c, α.app (F.obj c), naturality' := λ X Y f, by rw [functor.comp_map, functor.comp_map, α.naturality] } @[simps] def whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) : (G ⋙ F) ⟶ (H ⋙ F) := { app := λ c, F.map (α.app c), naturality' := λ X Y f, by rw [functor.comp_map, functor.comp_map, ←F.map_comp, ←F.map_comp, α.naturality] } variables (C D E) @[simps] def whiskering_left : (C ⥤ D) ⥤ ((D ⥤ E) ⥤ (C ⥤ E)) := { obj := λ F, { obj := λ G, F ⋙ G, map := λ G H α, whisker_left F α }, map := λ F G τ, { app := λ H, { app := λ c, H.map (τ.app c), naturality' := λ X Y f, begin dsimp, rw [←H.map_comp, ←H.map_comp, ←τ.naturality] end }, naturality' := λ X Y f, begin ext, dsimp, rw [f.naturality] end } } @[simps] def whiskering_right : (D ⥤ E) ⥤ ((C ⥤ D) ⥤ (C ⥤ E)) := { obj := λ H, { obj := λ F, F ⋙ H, map := λ _ _ α, whisker_right α H }, map := λ G H τ, { app := λ F, { app := λ c, τ.app (F.obj c), naturality' := λ X Y f, begin dsimp, rw [τ.naturality] end }, naturality' := λ X Y f, begin ext, dsimp, rw [←nat_trans.naturality] end } } variables {C} {D} {E} @[simp] lemma whisker_left_id (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (nat_trans.id G) = nat_trans.id (F.comp G) := rfl @[simp] lemma whisker_left_id' (F : C ⥤ D) {G : D ⥤ E} : whisker_left F (𝟙 G) = 𝟙 (F.comp G) := rfl @[simp] lemma whisker_right_id {G : C ⥤ D} (F : D ⥤ E) : whisker_right (nat_trans.id G) F = nat_trans.id (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_right_id' {G : C ⥤ D} (F : D ⥤ E) : whisker_right (𝟙 G) F = 𝟙 (G.comp F) := ((whiskering_right C D E).obj F).map_id _ @[simp] lemma whisker_left_comp (F : C ⥤ D) {G H K : D ⥤ E} (α : G ⟶ H) (β : H ⟶ K) : whisker_left F (α ≫ β) = (whisker_left F α) ≫ (whisker_left F β) := rfl @[simp] lemma whisker_right_comp {G H K : C ⥤ D} (α : G ⟶ H) (β : H ⟶ K) (F : D ⥤ E) : whisker_right (α ≫ β) F = (whisker_right α F) ≫ (whisker_right β F) := ((whiskering_right C D E).obj F).map_comp α β def iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (F ⋙ G) ≅ (F ⋙ H) := ((whiskering_left C D E).obj F).map_iso α @[simp] lemma iso_whisker_left_hom (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).hom = whisker_left F α.hom := rfl @[simp] lemma iso_whisker_left_inv (F : C ⥤ D) {G H : D ⥤ E} (α : G ≅ H) : (iso_whisker_left F α).inv = whisker_left F α.inv := rfl def iso_whisker_right {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (G ⋙ F) ≅ (H ⋙ F) := ((whiskering_right C D E).obj F).map_iso α @[simp] lemma iso_whisker_right_hom {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).hom = whisker_right α.hom F := rfl @[simp] lemma iso_whisker_right_inv {G H : C ⥤ D} (α : G ≅ H) (F : D ⥤ E) : (iso_whisker_right α F).inv = whisker_right α.inv F := rfl instance is_iso_whisker_left (F : C ⥤ D) {G H : D ⥤ E} (α : G ⟶ H) [is_iso α] : is_iso (whisker_left F α) := { .. iso_whisker_left F (as_iso α) } instance is_iso_whisker_right {G H : C ⥤ D} (α : G ⟶ H) (F : D ⥤ E) [is_iso α] : is_iso (whisker_right α F) := { .. iso_whisker_right (as_iso α) F } variables {B : Type u₄} [category.{v₄} B] local attribute [elab_simple] whisker_left whisker_right @[simp] lemma whisker_left_twice (F : B ⥤ C) (G : C ⥤ D) {H K : D ⥤ E} (α : H ⟶ K) : whisker_left F (whisker_left G α) = whisker_left (F ⋙ G) α := rfl @[simp] lemma whisker_right_twice {H K : B ⥤ C} (F : C ⥤ D) (G : D ⥤ E) (α : H ⟶ K) : whisker_right (whisker_right α F) G = whisker_right α (F ⋙ G) := rfl lemma whisker_right_left (F : B ⥤ C) {G H : C ⥤ D} (α : G ⟶ H) (K : D ⥤ E) : whisker_right (whisker_left F α) K = whisker_left F (whisker_right α K) := rfl end namespace functor universes u₅ v₅ variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] @[simps] def left_unitor (F : A ⥤ B) : ((𝟭 _) ⋙ F) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } @[simps] def right_unitor (F : A ⥤ B) : (F ⋙ (𝟭 _)) ≅ F := { hom := { app := λ X, 𝟙 (F.obj X) }, inv := { app := λ X, 𝟙 (F.obj X) } } variables {C : Type u₃} [category.{v₃} C] variables {D : Type u₄} [category.{v₄} D] @[simps] def associator (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) : ((F ⋙ G) ⋙ H) ≅ (F ⋙ (G ⋙ H)) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } lemma triangle (F : A ⥤ B) (G : B ⥤ C) : (associator F (𝟭 B) G).hom ≫ (whisker_left F (left_unitor G).hom) = (whisker_right (right_unitor F).hom G) := by { ext, dsimp, simp } variables {E : Type u₅} [category.{v₅} E] variables (F : A ⥤ B) (G : B ⥤ C) (H : C ⥤ D) (K : D ⥤ E) lemma pentagon : (whisker_right (associator F G H).hom K) ≫ (associator F (G ⋙ H) K).hom ≫ (whisker_left F (associator G H K).hom) = ((associator (F ⋙ G) H K).hom ≫ (associator F G (H ⋙ K)).hom) := by { ext, dsimp, simp } end functor end category_theory
0b5056eb289b902ab02f456327d840b8761917a6
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/emptyc.lean
5ad95b846863578066b025088d97883e95f7dd9a
[ "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
220
lean
new_frontend structure A := (x : Nat := 0) def foo : A := {} theorem ex1 : foo = { x := 0 } := rfl theorem ex2 : foo.x = 0 := rfl instance : HasEmptyc A := ⟨{ x := 10 }⟩ def boo : A := {} -- this is ambiguous
c7c837ae836ba6bfd775385095ff4d8bf4c683d0
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/locally_ringed.lean
f8f74355104bbec97ddae9eb2de9043def460ec5
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
777
lean
import category_theory.sheaves import category_theory.examples.rings.universal universes v open category_theory.examples open category_theory.limits variables (X : Top.{v}) def structure_sheaf := sheaf.{v+1 v} X CommRing structure ringed_space := (𝒪 : structure_sheaf X) structure locally_ringed_space extends ringed_space X := (locality : ∀ x : X, local_ring (stalk_at.{v+1 v} 𝒪.presheaf x).1) -- coercion from sheaf to presheaf? def ringed_space.of_topological_space : ringed_space X := { 𝒪 := { presheaf := { obj := λ U, sorry /- ring of continuous functions U → ℂ -/, map' := sorry, map_id' := sorry, map_comp' := sorry }, sheaf_condition := sorry, } }
2f01d7020684d8d9ba19fb64eb8a2c41a7a325af
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/locally_convex/bounded.lean
5fc941f541e5e72474155ccfde9c95287ce596f0
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,365
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.locally_convex.basic import topology.bornology.basic import topology.algebra.uniform_group import analysis.locally_convex.balanced_core_hull /-! # Von Neumann Boundedness This file defines natural or von Neumann bounded sets and proves elementary properties. ## Main declarations * `bornology.is_vonN_bounded`: A set `s` is von Neumann-bounded if every neighborhood of zero absorbs `s`. * `bornology.vonN_bornology`: The bornology made of the von Neumann-bounded sets. ## Main results * `bornology.is_vonN_bounded_of_topological_space_le`: A coarser topology admits more von Neumann-bounded sets. ## References * [Bourbaki, *Topological Vector Spaces*][bourbaki1987] -/ variables {𝕜 E ι : Type*} open_locale topological_space pointwise namespace bornology section semi_normed_ring section has_zero variables (𝕜) variables [semi_normed_ring 𝕜] [has_scalar 𝕜 E] [has_zero E] variables [topological_space E] /-- A set `s` is von Neumann bounded if every neighborhood of 0 absorbs `s`. -/ def is_vonN_bounded (s : set E) : Prop := ∀ ⦃V⦄, V ∈ 𝓝 (0 : E) → absorbs 𝕜 V s variables (E) @[simp] lemma is_vonN_bounded_empty : is_vonN_bounded 𝕜 (∅ : set E) := λ _ _, absorbs_empty variables {𝕜 E} lemma is_vonN_bounded_iff (s : set E) : is_vonN_bounded 𝕜 s ↔ ∀ V ∈ 𝓝 (0 : E), absorbs 𝕜 V s := iff.rfl lemma _root_.filter.has_basis.is_vonN_bounded_basis_iff {q : ι → Prop} {s : ι → set E} {A : set E} (h : (𝓝 (0 : E)).has_basis q s) : is_vonN_bounded 𝕜 A ↔ ∀ i (hi : q i), absorbs 𝕜 (s i) A := begin refine ⟨λ hA i hi, hA (h.mem_of_mem hi), λ hA V hV, _⟩, rcases h.mem_iff.mp hV with ⟨i, hi, hV⟩, exact (hA i hi).mono_left hV, end /-- Subsets of bounded sets are bounded. -/ lemma is_vonN_bounded.subset {s₁ s₂ : set E} (h : s₁ ⊆ s₂) (hs₂ : is_vonN_bounded 𝕜 s₂) : is_vonN_bounded 𝕜 s₁ := λ V hV, (hs₂ hV).mono_right h /-- The union of two bounded sets is bounded. -/ lemma is_vonN_bounded.union {s₁ s₂ : set E} (hs₁ : is_vonN_bounded 𝕜 s₁) (hs₂ : is_vonN_bounded 𝕜 s₂) : is_vonN_bounded 𝕜 (s₁ ∪ s₂) := λ V hV, (hs₁ hV).union (hs₂ hV) end has_zero end semi_normed_ring section multiple_topologies variables [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E] /-- If a topology `t'` is coarser than `t`, then any set `s` that is bounded with respect to `t` is bounded with respect to `t'`. -/ lemma is_vonN_bounded.of_topological_space_le {t t' : topological_space E} (h : t ≤ t') {s : set E} (hs : @is_vonN_bounded 𝕜 E _ _ _ t s) : @is_vonN_bounded 𝕜 E _ _ _ t' s := λ V hV, hs $ (le_iff_nhds t t').mp h 0 hV end multiple_topologies section normed_field variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [topological_space E] [has_continuous_smul 𝕜 E] /-- Singletons are bounded. -/ lemma is_vonN_bounded_singleton (x : E) : is_vonN_bounded 𝕜 ({x} : set E) := λ V hV, (absorbent_nhds_zero hV).absorbs /-- The union of all bounded set is the whole space. -/ lemma is_vonN_bounded_covers : ⋃₀ (set_of (is_vonN_bounded 𝕜)) = (set.univ : set E) := set.eq_univ_iff_forall.mpr (λ x, set.mem_sUnion.mpr ⟨{x}, is_vonN_bounded_singleton _, set.mem_singleton _⟩) variables (𝕜 E) /-- The von Neumann bornology defined by the von Neumann bounded sets. Note that this is not registered as an instance, in order to avoid diamonds with the metric bornology.-/ @[reducible] -- See note [reducible non-instances] def vonN_bornology : bornology E := bornology.of_bounded (set_of (is_vonN_bounded 𝕜)) (is_vonN_bounded_empty 𝕜 E) (λ _ hs _ ht, hs.subset ht) (λ _ hs _, hs.union) is_vonN_bounded_singleton variables {E} @[simp] lemma is_bounded_iff_is_vonN_bounded {s : set E} : @is_bounded _ (vonN_bornology 𝕜 E) s ↔ is_vonN_bounded 𝕜 s := is_bounded_of_bounded_iff _ end normed_field end bornology section uniform_add_group variables [nondiscrete_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [uniform_space E] [uniform_add_group E] [has_continuous_smul 𝕜 E] variables [regular_space E] lemma totally_bounded.is_vonN_bounded {s : set E} (hs : totally_bounded s) : bornology.is_vonN_bounded 𝕜 s := begin rw totally_bounded_iff_subset_finite_Union_nhds_zero at hs, intros U hU, have h : filter.tendsto (λ (x : E × E), x.fst + x.snd) (𝓝 (0,0)) (𝓝 ((0 : E) + (0 : E))) := tendsto_add, rw add_zero at h, have h' := (nhds_basis_closed_balanced 𝕜 E).prod (nhds_basis_closed_balanced 𝕜 E), simp_rw [←nhds_prod_eq, id.def] at h', rcases h.basis_left h' U hU with ⟨x, hx, h''⟩, rcases hs x.snd hx.2.1 with ⟨t, ht, hs⟩, refine absorbs.mono_right _ hs, rw ht.absorbs_Union, have hx_fstsnd : x.fst + x.snd ⊆ U, { intros z hz, rcases set.mem_add.mp hz with ⟨z1, z2, hz1, hz2, hz⟩, have hz' : (z1, z2) ∈ x.fst ×ˢ x.snd := ⟨hz1, hz2⟩, simpa only [hz] using h'' hz' }, refine λ y hy, absorbs.mono_left _ hx_fstsnd, rw [←set.singleton_vadd, vadd_eq_add], exact (absorbent_nhds_zero hx.1.1).absorbs.add hx.2.2.2.absorbs_self, end end uniform_add_group
697ce46b9faf69b3f0b6059226ba5ccff8487358
560745f5fc6d6dc9a83825cf9709cf565d1f158e
/src/compact_unit_ball.lean
57694a69287eec6cb6ce48b547c39a8afc50aaf1
[]
no_license
LAC1213/compact_unit_ball
335efe663dcb0d2f4e69762677ba314828b701c8
b4ce16961cb57a4a242d67fb96b41bea2ef1f3a3
refs/heads/lean-3.4.2
1,600,937,389,835
1,575,749,508,000
1,575,749,508,000
225,719,174
11
2
null
1,575,631,335,000
1,575,408,323,000
Lean
UTF-8
Lean
false
false
12,517
lean
import analysis.normed_space.banach import analysis.normed_space.basic import linear_algebra.basic import linear_algebra.basis import linear_algebra.dimension import linear_algebra.finite_dimensional import topology.subset_properties import set_theory.cardinal import data.real.basic import topology.sequences import order.bounded_lattice import analysis.specific_limits import analysis.normed_space.finite_dimension noncomputable theory open_locale classical local attribute [instance, priority 20000] nat.has_zero nat.has_one real.domain local attribute [instance, priority 10000] mul_action.to_has_scalar distrib_mul_action.to_mul_action semimodule.to_distrib_mul_action module.to_semimodule vector_space.to_module normed_space.to_vector_space ring.to_monoid normed_ring.to_ring normed_field.to_normed_ring add_group.to_add_monoid add_comm_group.to_add_group normed_group.to_add_comm_group ring.to_semiring add_comm_group.to_add_comm_monoid normed_field.to_discrete_field normed_field.to_has_norm nondiscrete_normed_field.to_normed_field zero_ne_one_class.to_has_zero zero_ne_one_class.to_has_one domain.to_zero_ne_one_class division_ring.to_domain field.to_division_ring discrete_field.to_field set_option class.instance_max_depth 100 open metric set universe u -- completeness of k is only assumed so we can use the library to prove that -- the span of a finite set is closed. -- This is indeed necessary since as Sebastian Gouezel has pointed out, -- Q in R is not closed but it is the span of the finite set {1}! variables {k : Type} [nondiscrete_normed_field k] [complete_space k] {V : Type} [normed_group V] [normed_space k V] lemma nontrivial_norm_gt_one: ∃ x : k, x ≠ 0 ∧ norm x > 1 := begin cases normed_field.exists_one_lt_norm k with x hx, refine ⟨x, _, hx⟩, intro hzero, rw [hzero, norm_zero] at hx, linarith, end lemma nontrivial_arbitrarily_small_norm {e : ℝ} (he : e > 0) : ∃ x : k, x ≠ 0 ∧ norm x < e := begin rcases normed_field.exists_norm_lt k he with ⟨x, hx₁, hx₂⟩, refine ⟨x, _, hx₂⟩, intro xzero, rw [xzero, norm_zero] at hx₁, linarith end lemma nontrivial_norm_lt_one: ∃ x : k, x ≠ 0 ∧ norm x < 1 := nontrivial_arbitrarily_small_norm (by linarith) lemma ball_span_ash {A : set V} (hyp : ∀ v : V, norm v ≤ 1 → v ∈ submodule.span k A) (v : V) : v ∈ submodule.span k A := begin by_cases v0 : v = 0, { rw v0, exact submodule.zero_mem _ }, { have norm_pos : 0 < norm v, from (norm_pos_iff v).mpr v0, obtain ⟨x, hx₁, hx₂⟩ : ∃ x : k, x ≠ 0 ∧ norm x < 1 / norm v, from nontrivial_arbitrarily_small_norm (one_div_pos_of_pos norm_pos), rw ← submodule.smul_mem_iff (submodule.span k A) hx₁, apply hyp (x • v), rw [norm_smul], exact le_of_lt (mul_lt_of_lt_div norm_pos hx₂) } end /-- If A spans the closed unit ball then it spans all of V -/ lemma ball_span {A : set V} (H : (closed_ball 0 1 : set V) ⊆ submodule.span k A) : ∀ v : V, v ∈ submodule.span k A := begin apply ball_span_ash, intros v hv, rw ← dist_zero_right at hv, exact H hv, end theorem finite_dimensional_span_of_finite {A : set V} (hA : finite A) : finite_dimensional k ↥(submodule.span k A) := begin apply is_noetherian_of_fg_of_noetherian, exact submodule.fg_def.2 ⟨A, hA, rfl⟩, end -- the span of a finite set is (sequentially) closed lemma finite_span_seq_closed (A : set V) : finite A → is_seq_closed (↑(submodule.span k A) : set V) := begin intro h_fin, apply is_seq_closed_of_is_closed, haveI : finite_dimensional k ↥(submodule.span k A) := finite_dimensional_span_of_finite h_fin, exact submodule.closed_of_finite_dimensional _, end --turns cover into a choice function lemma cover_to_func (A X : set V) {r : ℝ} (hX : X ⊆ (⋃a ∈ A, ball a r)) (a : V) (ha : a ∈ A) : ∃(f : V → V), ∀x, f x ∈ A ∧ (x ∈ X → x ∈ ball (f x) r) := begin classical, have : ∀(x : V), ∃a, a ∈ A ∧ (x ∈ X → x ∈ ball a r) := begin assume x, by_cases h : x ∈ X, { simpa [h] using hX h }, { exact ⟨a, ha, by simp [h]⟩ } end, choose f hf using this, exact ⟨f, λx, hf x⟩ end -- if the closed unit ball is compact, then there is -- a function which selects the center of a ball of radius 1/2 close to it lemma compact_choice_func (hc : compact (closed_ball 0 1 : set V)) {r : k} (hr : norm r > 0) : ∃ A : set V, A ⊆ (closed_ball 0 1 : set V) ∧ finite A ∧ ∃ f : V → V, ∀ x : V, f x ∈ A ∧ (x ∈ (closed_ball 0 1 : set V) → x ∈ ball (f x) (1/norm r)) := begin let B : set V := closed_ball 0 1, have cover : B ⊆ ⋃ a ∈ B, ball a (1 / norm r), { intros x hx, simp, use x, rw dist_self, split, simp at hx, exact hx, norm_num, exact hr, }, obtain ⟨A, A_sub, A_fin, HcoverA⟩ : ∃ A ⊆ B, finite A ∧ B ⊆ ⋃ a ∈ A, ball a (1/ norm r) := compact_elim_finite_subcover_image hc (by simp[is_open_ball]) cover, -- need that A is non-empty to construct a choice function! have x_in : (0 : V) ∈ B, simp, norm_num, obtain ⟨a, a_in, ha⟩ : ∃ a ∈ A, dist (0 : V) a < 1/ norm r, by simpa using HcoverA x_in, have hfunc := cover_to_func A B HcoverA a a_in, existsi A, split, exact A_sub, split, exact A_fin, exact hfunc, end def aux_seq (v : V) (x : k) (f : V → V) : ℕ → V | 0 := v | (n + 1) := x • (aux_seq n - f (aux_seq n)) def partial_sum (f : ℕ → V) : ℕ → V | 0 := f 0 | (n + 1) := f (n + 1) + partial_sum n def approx_seq (v : V) (x : k) (f : V → V) : ℕ → V := partial_sum (λ n : ℕ, (1/x)^n • f(aux_seq v x f n)) -- if a sequence w n satisfies the bound |v - w n| < e^(n+1), where 0 < e < 1 -- then w n converges to v lemma bound_power_convergence (w : ℕ → V) {v : V} {x : k} (hx : norm x > 1) (h : ∀ n : ℕ, norm (v - w n) ≤ (1 / norm x)^(n + 1)) : filter.tendsto w filter.at_top (nhds v) := begin have hlt1 : 1 / norm x < 1, { rw div_lt_one_iff_lt, exact hx, apply lt_trans zero_lt_one, exact hx, }, have hpos : 1 / norm x > 0, { norm_num, apply lt_trans zero_lt_one, exact hx, }, have H : ∀ n : ℕ, norm (w n - v) ≤ (1 / norm x)^n, intro n, rw <- dist_eq_norm, rw dist_comm, rw dist_eq_norm, apply le_trans, exact h n, rw pow_succ, have h1 : (1 / norm x) * (1 / norm x)^n ≤ 1 * (1 / norm x)^n, rw mul_le_mul_right, rw le_iff_eq_or_lt, right, exact hlt1, apply pow_pos, exact hpos, rw one_mul at h1, exact h1, rw tendsto_iff_norm_tendsto_zero, apply squeeze_zero, intro t, exact norm_nonneg (w t - v), exact H, apply tendsto_pow_at_top_nhds_0_of_lt_1, rw le_iff_eq_or_lt, right, exact hpos, exact hlt1, end -- the approximation sequence (w n below) is contained in the span of A -- this is true since by construction w n is a linear combination -- of the elements in A lemma approx_in_span (A : set V) (v : V) (x : k) (f : V → V) (hf : ∀ x : V, f x ∈ A): ∀ n : ℕ, approx_seq v x f n ∈ submodule.span k A := begin let w := approx_seq v x f, have hw : w = approx_seq v x f, refl, intro n, rw submodule.mem_span, intros p hp, induction n with n hn, { have h1 : w 0 = (1/x)^0 • f(v), refl, simp at h1, rw <- hw, rw h1, have h2 : f v ∈ A := hf v, exact hp h2, },{ have h1 : w (n+1) = (1/x)^(n+1) • f(aux_seq v x f (n+1)) + w(n), refl, rw <- hw, rw h1, have h2 := hp (hf (aux_seq v x f (n+1))), have h3 := submodule.smul_mem p ((1/x)^(n+1)) h2, apply submodule.add_mem p, exact h3, exact hn, }, end theorem compact_unit_ball_implies_finite_dim (Hcomp : compact (closed_ball 0 1 : set V)) : finite_dimensional k V := begin -- there is an x in k such that norm x > 1 have hbignum : ∃ x : k, x ≠ 0 ∧ norm x > 1, exact nontrivial_norm_gt_one, cases hbignum with x hx, have hxpos : norm x > 0, { have h : (1:ℝ) > 0, norm_num, exact gt_trans hx.2 h, }, -- use compactness to find a finite set A -- and function f : V -> A such that for every -- v in closed_ball 0 1, |f v - v| < 1/ norm x obtain ⟨A, A_sub, A_fin, Hexistsf⟩ := compact_choice_func Hcomp hxpos, obtain ⟨f, hf⟩ := Hexistsf, -- suffices to show closed_ball 0 1 is spanned by A apply finite_dimensional.of_fg, rw submodule.fg_def, existsi A, split, exact A_fin, rw submodule.eq_top_iff', apply ball_span, -- let v in closed_ball 0 1 and show that it is in the span of A -- to do so we construct a sequence w n such that -- w n -> v and w n in span A for all n -- for this we do a kind of 'dyadic approximation' of v using the set A -- then we use that the span of a finite set is closed to conclude intros v hv, let u : ℕ → V := aux_seq v x f, let w : ℕ → V := partial_sum (λ n : ℕ, (1/x)^n • f(u(n))), -- show that w n is in the span of A have hw : ∀ n, w n ∈ submodule.span k A, { have hf' : ∀ x : V, f x ∈ A, intro x, exact (hf x).1, exact approx_in_span A v x f hf', }, -- this is just some algebraic manipulation have hdist : ∀ n : ℕ, v - w n = (1/x)^(n+1) • u (n+1), { intro n, induction n with n hn, { have h1 : w 0 = (1/x)^0 • f(v), refl, rw zero_add, rw pow_one, rw pow_zero at h1, rw one_smul at h1, rw h1, have h2 : u 1 = x • (v - f(v)), refl, rw h2, rw smul_smul, rw one_div_mul_cancel, rw one_smul, exact hx.1, }, { have h1 : w (n+1) = (1/x)^(n+1) • f(u (n+1)) + w(n), refl, have h2 : u (n+2) = x • (u (n+1) - f (u (n+1))), refl, rw h2, rw pow_succ, rw smul_smul, rw mul_comm, rw <- mul_assoc, rw mul_one_div_cancel, rw one_mul, rw smul_sub, rw <- hn, rw h1, rw add_comm _ (w n), rw sub_sub v (w n) _, exact hx.1, }, }, -- main bound for convergence using the expression hdist have hbound : ∀ n : ℕ, norm (v - w n) ≤ (1/norm x)^(n+1), { intro n, rw hdist n, rw norm_smul, have hu : u(n+1) = x • (u(n) - f(u(n))), refl, rw hu, have husmall : norm (u n) ≤ 1, { induction n with n hn, have h0 : u 0 = v, refl, rw h0, rw <- dist_zero_right, exact hv, have hu' : u(n + 1) = x • (u(n) - f(u(n))), refl, rw hu', have h2 := (hf (u n)).2, rw norm_smul, rw <- dist_eq_norm, have h3 := hn hu', rw <- dist_zero_right at h3, have h4 : dist (u n) (f (u n)) < 1/ norm x, exact h2 h3, rw le_iff_eq_or_lt, right, rw <- mul_lt_mul_left hxpos at h4, rw mul_one_div_cancel at h4, exact h4, exact mt (norm_eq_zero x).1 hx.1, }, have h2 : 0 < (1/norm x), norm_num, exact hxpos, have h1 : 0 < (1/ norm x)^(n+1), exact pow_pos h2 (n+1), have h3 : norm ((1/ x)^(n+1)) * norm (x • (u n - f(u n))) ≤ norm ((1/ x)^(n+1)) * 1 → (1/norm x)^(n+1) * norm (x • (u n - f(u n))) ≤ (1/norm x)^(n+1), intro h, rw mul_one at h, rw normed_field.norm_pow at h, rw normed_field.norm_div at h, rw normed_field.norm_one at h, exact h, rw normed_field.norm_pow, rw normed_field.norm_div, rw normed_field.norm_one, apply h3, rw normed_field.norm_pow, rw normed_field.norm_div, rw normed_field.norm_one, rw mul_le_mul_left h1, rw norm_smul, rw <- dist_zero_right at husmall, have h4 := (hf (u n)).2 husmall, rw <- dist_eq_norm, rw <- mul_le_mul_left h2, rw <- mul_assoc, rw mul_one, rw one_div_mul_cancel, rw one_mul, rw le_iff_eq_or_lt, right, exact h4, exact mt (norm_eq_zero x).1 hx.1, }, -- w n -> v as n -> infty have hlim : filter.tendsto w filter.at_top (nhds v : filter V) := bound_power_convergence w hx.2 hbound, -- the span of a finite set is (sequentially) closed let S : set V := ↑(submodule.span k A), have hspan_closed : is_seq_closed S := finite_span_seq_closed A A_fin, have hw' : ∀ n, w n ∈ S, exact hw, -- since S is closed, the limit v of w n is in S, as required. have hinS: v ∈ S, exact mem_of_is_seq_closed hspan_closed hw' hlim, exact hinS, end
bb4c455abac728ecc70ac9e2bbdde028fe3db3fb
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/power_basis.lean
be88af1e6a32a22be9a1a3b79e1e2ec5ebb2b6fb
[ "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,419
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.minpoly /-! # Power basis This file defines a structure `power_basis R S`, giving a basis of the `R`-algebra `S` as a finite list of powers `1, x, ..., x^n`. For example, if `x` is algebraic over a ring/field, adjoining `x` gives a `power_basis` structure generated by `x`. ## Definitions * `power_basis R A`: a structure containing an `x` and an `n` such that `1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module). * `finrank (hf : f ≠ 0) : finite_dimensional.finrank K (adjoin_root f) = f.nat_degree`, the dimension of `adjoin_root f` equals the degree of `f` * `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y` * `power_basis.equiv`: if two power bases satisfy the same equations, they are equivalent as algebras ## Implementation notes Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are `comm_ring` with `is_domain`s and `K`, `L`, ... are `field`s. `S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra. ## Tags power basis, powerbasis -/ open polynomial variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T] variables {A B : Type*} [comm_ring A] [comm_ring B] [is_domain B] [algebra A B] variables {K L : Type*} [field K] [field L] [algebra K L] /-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)` is a basis for the `R`-algebra `S` (viewed as `R`-module). This is a structure, not a class, since the same algebra can have many power bases. For the common case where `S` is defined by adjoining an integral element to `R`, the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`. -/ @[nolint has_inhabited_instance] structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] := (gen : S) (dim : ℕ) (basis : basis (fin dim) R S) (basis_eq_pow : ∀ i, basis i = gen ^ (i : ℕ)) -- this is usually not needed because of `basis_eq_pow` but can be needed in some cases; -- in such circumstances, add it manually using `@[simps dim gen basis]`. initialize_simps_projections power_basis (-basis) namespace power_basis @[simp] lemma coe_basis (pb : power_basis R S) : ⇑pb.basis = λ (i : fin pb.dim), pb.gen ^ (i : ℕ) := funext pb.basis_eq_pow /-- Cannot be an instance because `power_basis` cannot be a class. -/ lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S := finite_dimensional.of_fintype_basis pb.basis lemma finrank [algebra K S] (pb : power_basis K S) : finite_dimensional.finrank K S = pb.dim := by rw [finite_dimensional.finrank_eq_card_basis pb.basis, fintype.card_fin] lemma mem_span_pow' {x y : S} {d : ℕ} : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.degree < d ∧ y = aeval x f := begin have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d), { ext n, simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range], exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ }, simp only [this, finsupp.mem_span_image_iff_total, degree_lt_iff_coeff_zero, exists_iff_exists_finsupp, coeff, aeval, eval₂_ring_hom', eval₂_eq_sum, polynomial.sum, support, finsupp.mem_supported', finsupp.total, finsupp.sum, algebra.smul_def, eval₂_zero, exists_prop, linear_map.id_coe, eval₂_one, id.def, not_lt, finsupp.coe_lsum, linear_map.coe_smul_right, finset.mem_range, alg_hom.coe_mk, finset.mem_coe], simp_rw [@eq_comm _ y], exact iff.rfl end lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.nat_degree < d ∧ y = aeval x f := begin rw mem_span_pow', split; { rintros ⟨f, h, hy⟩, refine ⟨f, _, hy⟩, by_cases hf : f = 0, { simp only [hf, nat_degree_zero, degree_zero] at h ⊢, exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_coe d }, simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h }, end lemma dim_ne_zero [h : nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 := λ h, not_nonempty_iff.mpr (h.symm ▸ fin.is_empty : is_empty (fin pb.dim)) pb.basis.index_nonempty lemma dim_pos [nontrivial S] (pb : power_basis R S) : 0 < pb.dim := nat.pos_of_ne_zero pb.dim_ne_zero lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) : ∃ f : polynomial R, f.nat_degree < pb.dim ∧ y = aeval pb.gen f := (mem_span_pow pb.dim_ne_zero).mp (by simpa using pb.basis.mem_span y) lemma exists_eq_aeval' (pb : power_basis R S) (y : S) : ∃ f : polynomial R, y = aeval pb.gen f := begin nontriviality S, obtain ⟨f, _, hf⟩ := exists_eq_aeval pb y, exact ⟨f, hf⟩ end lemma alg_hom_ext {S' : Type*} [semiring S'] [algebra R S'] (pb : power_basis R S) ⦃f g : S →ₐ[R] S'⦄ (h : f pb.gen = g pb.gen) : f = g := begin ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, rw [← polynomial.aeval_alg_hom_apply, ← polynomial.aeval_alg_hom_apply, h] end section minpoly open_locale big_operators variable [algebra A S] /-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`. If `A` is not a field, it might not necessarily be *the* minimal polynomial, however `nat_degree_minpoly` shows its degree is indeed minimal. -/ noncomputable def minpoly_gen (pb : power_basis A S) : polynomial A := X ^ pb.dim - ∑ (i : fin pb.dim), C (pb.basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ) @[simp] lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 := begin simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow, aeval_C, ← algebra.smul_def, aeval_X], refine sub_eq_zero.mpr ((pb.basis.total_repr (pb.gen ^ pb.dim)).symm.trans _), rw [finsupp.total_apply, finsupp.sum_fintype]; simp only [pb.coe_basis, zero_smul, eq_self_iff_true, implies_true_iff] end lemma dim_le_nat_degree_of_root (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : h.dim ≤ p.nat_degree := begin refine le_of_not_lt (λ hlt, ne_zero _), let p_coeff : fin (h.dim) → A := λ i, p.coeff i, suffices : ∀ i, p_coeff i = 0, { ext i, by_cases hi : i < h.dim, { exact this ⟨i, hi⟩ }, exact coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)) }, intro i, refine linear_independent_iff'.mp h.basis.linear_independent _ _ _ i (finset.mem_univ _), rw aeval_eq_sum_range' hlt at root, rw finset.sum_fin_eq_sum_range, convert root, ext i, split_ifs with hi, { simp_rw [coe_basis, p_coeff, fin.coe_mk] }, { rw [coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)), zero_smul] } end lemma dim_le_degree_of_root (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : ↑h.dim ≤ p.degree := by { rw [degree_eq_nat_degree ne_zero, with_bot.coe_le_coe], exact h.dim_le_nat_degree_of_root ne_zero root } variables [is_domain A] @[simp] lemma degree_minpoly_gen (pb : power_basis A S) : degree (minpoly_gen pb) = pb.dim := begin unfold minpoly_gen, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, apply degree_sum_fin_lt end @[simp] lemma nat_degree_minpoly_gen (pb : power_basis A S) : nat_degree (minpoly_gen pb) = pb.dim := nat_degree_eq_of_degree_eq_some pb.degree_minpoly_gen lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) := begin apply monic_sub_of_left (monic_pow (monic_X) _), rw degree_X_pow, exact degree_sum_fin_lt _ end lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen := ⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩ @[simp] lemma nat_degree_minpoly (pb : power_basis A S) : (minpoly A pb.gen).nat_degree = pb.dim := begin refine le_antisymm _ (dim_le_nat_degree_of_root pb (minpoly.ne_zero pb.is_integral_gen) (minpoly.aeval _ _)), rw ← nat_degree_minpoly_gen, apply nat_degree_le_of_degree_le, rw ← degree_eq_nat_degree (minpoly_gen_monic pb).ne_zero, exact minpoly.min _ _ (minpoly_gen_monic pb) (aeval_minpoly_gen pb) end @[simp] lemma minpoly_gen_eq [algebra K S] (pb : power_basis K S) : pb.minpoly_gen = minpoly K pb.gen := minpoly.unique K pb.gen pb.minpoly_gen_monic pb.aeval_minpoly_gen (λ p p_monic p_root, pb.degree_minpoly_gen.symm ▸ pb.dim_le_degree_of_root p_monic.ne_zero p_root) end minpoly section equiv variables [algebra A S] {S' : Type*} [comm_ring S'] [algebra A S'] lemma nat_degree_lt_nat_degree {p q : polynomial R} (hp : p ≠ 0) (hpq : p.degree < q.degree) : p.nat_degree < q.nat_degree := begin by_cases hq : q = 0, { rw [hq, degree_zero] at hpq, have := not_lt_bot hpq, contradiction }, rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq end variables [is_domain A] lemma constr_pow_aeval (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f := begin rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _), ← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy], by_cases hf : f %ₘ minpoly A pb.gen = 0, { simp only [hf, alg_hom.map_zero, linear_map.map_zero] }, have : (f %ₘ minpoly A pb.gen).nat_degree < pb.dim, { rw ← pb.nat_degree_minpoly, apply nat_degree_lt_nat_degree hf, exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen) }, rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum], refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _), rw finset.mem_range at hi, rw linear_map.map_smul, congr, rw [← fin.coe_mk hi, ← pb.basis_eq_pow ⟨i, hi⟩, basis.constr_basis] end lemma constr_pow_gen (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) : pb.basis.constr A (λ i, y ^ (i : ℕ)) pb.gen = y := by { convert pb.constr_pow_aeval hy X; rw aeval_X } lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x : A) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x := by { convert pb.constr_pow_aeval hy (C x); rw aeval_C } lemma constr_pow_mul (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x x' : S) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (x * x') = pb.basis.constr A (λ i, y ^ (i : ℕ)) x * pb.basis.constr A (λ i, y ^ (i : ℕ)) x' := begin obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, obtain ⟨g, rfl⟩ := pb.exists_eq_aeval' x', simp only [← aeval_mul, pb.constr_pow_aeval hy] end /-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`, where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. See `power_basis.lift_equiv` for a bundled equiv sending `⟨y, hy⟩` to the algebra map. -/ noncomputable def lift (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : S →ₐ[A] S' := { map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one }, map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero }, map_mul' := pb.constr_pow_mul hy, commutes' := pb.constr_pow_algebra_map hy, .. pb.basis.constr A (λ i, y ^ (i : ℕ)) } @[simp] lemma lift_gen (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : pb.lift y hy pb.gen = y := pb.constr_pow_gen hy @[simp] lemma lift_aeval (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.lift y hy (aeval pb.gen f) = aeval y f := pb.constr_pow_aeval hy f /-- `pb.lift_equiv` states that roots of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. This is the bundled equiv version of `power_basis.lift`. If the codomain of the `alg_hom`s is an integral domain, then the roots form a multiset, see `lift_equiv'` for the corresponding statement. -/ @[simps] noncomputable def lift_equiv (pb : power_basis A S) : (S →ₐ[A] S') ≃ {y : S' // aeval y (minpoly A pb.gen) = 0} := { to_fun := λ f, ⟨f pb.gen, by rw [aeval_alg_hom_apply, minpoly.aeval, f.map_zero]⟩, inv_fun := λ y, pb.lift y y.2, left_inv := λ f, pb.alg_hom_ext $ lift_gen _ _ _, right_inv := λ y, subtype.ext $ lift_gen _ _ y.prop } /-- `pb.lift_equiv'` states that elements of the root set of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. -/ @[simps {fully_applied := ff}] noncomputable def lift_equiv' (pb : power_basis A S) : (S →ₐ[A] B) ≃ {y : B // y ∈ ((minpoly A pb.gen).map (algebra_map A B)).roots} := pb.lift_equiv.trans ((equiv.refl _).subtype_equiv (λ x, begin rw [mem_roots, is_root.def, equiv.refl_apply, ← eval₂_eq_eval_map, ← aeval_def], exact map_monic_ne_zero (minpoly.monic pb.is_integral_gen) end)) /-- There are finitely many algebra homomorphisms `S →ₐ[A] B` if `S` is of the form `A[x]` and `B` is an integral domain. -/ noncomputable def alg_hom.fintype (pb : power_basis A S) : fintype (S →ₐ[A] B) := by letI := classical.dec_eq B; exact fintype.of_equiv _ pb.lift_equiv'.symm local attribute [irreducible] power_basis.lift /-- `pb.equiv_of_root pb' h₁ h₂` is an equivalence of algebras with the same power basis, where "the same" means that `pb` is a root of `pb'`s minimal polynomial and vice versa. See also `power_basis.equiv_of_minpoly` which takes the hypothesis that the minimal polynomials are identical. -/ @[simps apply {attrs := []}] noncomputable def equiv_of_root (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : S ≃ₐ[A] S' := alg_equiv.of_alg_hom (pb.lift pb'.gen h₂) (pb'.lift pb.gen h₁) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval' x, simp }) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval' x, simp }) @[simp] lemma equiv_of_root_aeval (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) (f : polynomial A) : pb.equiv_of_root pb' h₁ h₂ (aeval pb.gen f) = aeval pb'.gen f := pb.lift_aeval _ h₂ _ @[simp] lemma equiv_of_root_gen (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : pb.equiv_of_root pb' h₁ h₂ pb.gen = pb'.gen := pb.lift_gen _ h₂ @[simp] lemma equiv_of_root_symm (pb : power_basis A S) (pb' : power_basis A S') (h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) : (pb.equiv_of_root pb' h₁ h₂).symm = pb'.equiv_of_root pb h₂ h₁ := rfl /-- `pb.equiv_of_minpoly pb' h` is an equivalence of algebras with the same power basis, where "the same" means that they have identical minimal polynomials. See also `power_basis.equiv_of_root` which takes the hypothesis that each generator is a root of the other basis' minimal polynomial; `power_basis.equiv_root` is more general if `A` is not a field. -/ @[simps apply {attrs := []}] noncomputable def equiv_of_minpoly (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : S ≃ₐ[A] S' := pb.equiv_of_root pb' (h ▸ minpoly.aeval _ _) (h.symm ▸ minpoly.aeval _ _) @[simp] lemma equiv_of_minpoly_aeval (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) (f : polynomial A) : pb.equiv_of_minpoly pb' h (aeval pb.gen f) = aeval pb'.gen f := pb.equiv_of_root_aeval pb' _ _ _ @[simp] lemma equiv_of_minpoly_gen (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : pb.equiv_of_minpoly pb' h pb.gen = pb'.gen := pb.equiv_of_root_gen pb' _ _ @[simp] lemma equiv_of_minpoly_symm (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : (pb.equiv_of_minpoly pb' h).symm = pb'.equiv_of_minpoly pb h.symm := rfl end equiv end power_basis open power_basis /-- Useful lemma to show `x` generates a power basis: the powers of `x` less than the degree of `x`'s minimal polynomial are linearly independent. -/ lemma is_integral.linear_independent_pow [algebra K S] {x : S} (hx : is_integral K x) : linear_independent K (λ (i : fin (minpoly K x).nat_degree), x ^ (i : ℕ)) := begin rw linear_independent_iff, intros p hp, set f : polynomial K := p.sum (λ i, monomial i) with hf0, have f_def : ∀ (i : fin _), f.coeff i = p i, { intro i, simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff], rw [finset.sum_eq_single, if_pos rfl], { intros b _ hb, rw if_neg (mt (λ h, _) hb), exact fin.coe_injective h }, { intro hi, rw if_pos rfl, exact finsupp.not_mem_support_iff.mp hi } }, have f_def' : ∀ i, f.coeff i = if hi : i < _ then p ⟨i, hi⟩ else 0, { intro i, split_ifs with hi, { exact f_def ⟨i, hi⟩ }, simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff], apply finset.sum_eq_zero, rintro ⟨j, hj⟩ -, apply if_neg (mt _ hi), rintro rfl, exact hj }, suffices : f = 0, { ext i, rw [← f_def, this, coeff_zero, finsupp.zero_apply] }, contrapose hp with hf, intro h, have : (minpoly K x).degree ≤ f.degree, { apply minpoly.degree_le_of_ne_zero K x hf, convert h, simp_rw [finsupp.total_apply, aeval_def, hf0, finsupp.sum, eval₂_finset_sum], apply finset.sum_congr rfl, rintro i -, simp only [algebra.smul_def, eval₂_monomial] }, have : ¬ (minpoly K x).degree ≤ f.degree, { apply not_le_of_lt, rw [degree_eq_nat_degree (minpoly.ne_zero hx), degree_lt_iff_coeff_zero], intros i hi, rw [f_def' i, dif_neg], exact hi.not_lt }, contradiction end lemma is_integral.mem_span_pow [nontrivial R] {x y : S} (hx : is_integral R x) (hy : ∃ f : polynomial R, y = aeval x f) : y ∈ submodule.span R (set.range (λ (i : fin (minpoly R x).nat_degree), x ^ (i : ℕ))) := begin obtain ⟨f, rfl⟩ := hy, apply mem_span_pow'.mpr _, have := minpoly.monic hx, refine ⟨f.mod_by_monic (minpoly R x), lt_of_lt_of_le (degree_mod_by_monic_lt _ this) degree_le_nat_degree, _⟩, conv_lhs { rw ← mod_by_monic_add_div f this }, simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul] end namespace power_basis section map variables {S' : Type*} [comm_ring S'] [algebra R S'] /-- `power_basis.map pb (e : S ≃ₐ[R] S')` is the power basis for `S'` generated by `e pb.gen`. -/ @[simps dim gen basis] noncomputable def map (pb : power_basis R S) (e : S ≃ₐ[R] S') : power_basis R S' := { dim := pb.dim, basis := pb.basis.map e.to_linear_equiv, gen := e pb.gen, basis_eq_pow := λ i, by rw [basis.map_apply, pb.basis_eq_pow, e.to_linear_equiv_apply, e.map_pow] } variables [algebra A S] [algebra A S'] @[simp] lemma minpoly_gen_map (pb : power_basis A S) (e : S ≃ₐ[A] S') : (pb.map e).minpoly_gen = pb.minpoly_gen := by { dsimp only [minpoly_gen, map_dim], -- Turn `fin (pb.map e).dim` into `fin pb.dim` simp only [linear_equiv.trans_apply, map_basis, basis.map_repr, map_gen, alg_equiv.to_linear_equiv_apply, e.to_linear_equiv_symm, alg_equiv.map_pow, alg_equiv.symm_apply_apply, sub_right_inj] } variables [is_domain A] @[simp] lemma equiv_of_root_map (pb : power_basis A S) (e : S ≃ₐ[A] S') (h₁ h₂) : pb.equiv_of_root (pb.map e) h₁ h₂ = e := by { ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, simp [aeval_alg_equiv] } @[simp] lemma equiv_of_minpoly_map (pb : power_basis A S) (e : S ≃ₐ[A] S') (h : minpoly A pb.gen = minpoly A (pb.map e).gen) : pb.equiv_of_minpoly (pb.map e) h = e := pb.equiv_of_root_map _ _ _ end map end power_basis
3aff7e5e6f816cc415a04e436486f84c8d5a8663
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/adjoin.lean
194325eef721b9e3cb2f4683726e675bbb07cc42
[ "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
9,160
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 ring_theory.polynomial.basic /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open submodule namespace algebra variables {R : Type u} {A : Type v} section semiring variables [comm_semiring R] [semiring A] variables [algebra R A] {s t : set A} open subsemiring theorem subset_adjoin : s ⊆ adjoin R s := set.subset.trans (set.subset_union_right _ _) subset_closure theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := closure_le.2 $ set.union_subset S.range_le H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= ⟨set.subset.trans subset_adjoin, adjoin_le⟩ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := closure_le.2 (set.subset.trans (set.union_subset_union_right _ H) subset_closure) variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.empty_subset _ variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s : submodule R A) = span R (monoid.closure s) := begin apply le_antisymm, { intros r hr, rcases mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ monoid.closure s), has_scalar.smul.{u v} z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, is_submonoid.one_mem, one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [smul_def, smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, is_submonoid.mul_mem (monoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, exact span_le.2 (show monoid.closure s ⊆ adjoin R s, from monoid.closure_subset subset_adjoin) end end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} open subsemiring variables (R s t) theorem adjoin_union : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_range : adjoin R s = (mv_polynomial.aeval (coe : s → A)).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, hp⟩, hp ▸ mv_polynomial.induction_on p (λ r, by rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C]; exact (adjoin R s).2 r) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact is_submonoid.mul_mem hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩) (λ y ⟨p, hp⟩, hp ▸ polynomial.induction_on p (λ r, by rw [polynomial.aeval_def, polynomial.eval₂_C]; exact (adjoin R _).2 r) (λ p q hp hq, by rw alg_hom.map_add; exact is_add_submonoid.add_mem hp hq) (λ n r ih, by { rw [pow_succ', ← mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X], exact is_submonoid.mul_mem ih (subset_adjoin rfl) })) theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t) : submodule R A) = (adjoin R s) * (adjoin R t) := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [monoid.mem_closure_union_iff, set.mem_mul], end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (closure s) := le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subset_closure is_add_submonoid.zero_mem is_submonoid.one_mem (λ _ _, is_add_submonoid.add_mem) (λ _ _, is_submonoid.mul_mem), suffices closure (set.range ⇑(algebra_map R A) ∪ s) ⊆ adjoin R s, from @this x, closure_subset subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s : set A) = closure (set.range (algebra_map R A) ∪ s) := set.ext $ λ x, mem_adjoin_iff end ring section comm_ring variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem fg_trans (h1 : (adjoin R s : submodule R A).fg) (h2 : (adjoin (adjoin R s) t : submodule (adjoin R s) A).fg) : (adjoin R (s ∪ t) : submodule R A).fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, y, hx, hy, rfl⟩, change x * y ∈ _, refine is_submonoid.mul_mem _ _, { have : x ∈ (adjoin R s : submodule R A), { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A), { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union at hr, change r ∈ (adjoin (adjoin R s) t : submodule (adjoin R s) A) at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s : submodule R A) := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ } end end comm_ring end algebra namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [comm_ring A] [algebra R A] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) : is_noetherian_ring (ring.closure s) := show is_noetherian_ring (subalgebra_of_subring (ring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
e2f0770822e4e700cf96001bf3c867d7be69559b
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/exercises_sources/tuesday/afternoon/sets.lean
f0f4cdd55880e0dfbc0497c8f7cddd7e087b59c1
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
7,255
lean
import data.set.basic data.set.lattice data.nat.parity import tactic.linarith open set nat function open_locale classical variables {α : Type*} {β : Type*} {γ : Type*} {I : Type*} /-! ## Set exercises These are collected from *Mathematics in Lean*. We will go over the examples together, and then let you work on the exercises. There is more material here than can fit in the sessions, but we will pick and choose as we go. -/ section set_variables variable x : α variables s t u : set α /-! ### Notation -/ #check s ⊆ t -- \sub #check x ∈ s -- \in or \mem #check x ∉ s -- \notin #check s ∩ t -- \i or \cap #check s ∪ t -- \un or \cup #check (∅ : set α) -- \empty /-! ### Examples -/ -- Three proofs of the same fact. -- The first two expand definitions explicitly, -- while the third forces Lean to do the unfolding. example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := begin rw [subset_def, inter_def, inter_def], rw subset_def at h, dsimp, rintros x ⟨xs, xu⟩, exact ⟨h _ xs, xu⟩, end example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := begin simp only [subset_def, mem_inter_eq] at *, rintros x ⟨xs, xu⟩, exact ⟨h _ xs, xu⟩, end example (h : s ⊆ t) : s ∩ u ⊆ t ∩ u := begin intros x xsu, exact ⟨h xsu.1, xsu.2⟩ end -- Use `cases` or `rcases` or `rintros` with union. -- Two proofs of the same fact, one longer and one shorter. example : s ∩ (t ∪ u) ⊆ (s ∩ t) ∪ (s ∩ u) := begin intros x hx, have xs : x ∈ s := hx.1, have xtu : x ∈ t ∪ u := hx.2, cases xtu with xt xu, { left, show x ∈ s ∩ t, exact ⟨xs, xt⟩ }, right, show x ∈ s ∩ u, exact ⟨xs, xu⟩ end example : s ∩ (t ∪ u) ⊆ (s ∩ t) ∪ (s ∩ u) := begin rintros x ⟨xs, xt | xu⟩, { left, exact ⟨xs, xt⟩ }, right, exact ⟨xs, xu⟩ end -- Two examples with set difference. -- Type it as ``\\``. -- ``x ∈ s \ t`` expands to ``x ∈ s ∧ x ∉ t``. example : s \ t \ u ⊆ s \ (t ∪ u) := begin intros x xstu, have xs : x ∈ s := xstu.1.1, have xnt : x ∉ t := xstu.1.2, have xnu : x ∉ u := xstu.2, split, { exact xs }, dsimp, intro xtu, -- x ∈ t ∨ x ∈ u cases xtu with xt xu, { show false, from xnt xt }, show false, from xnu xu end example : s \ t \ u ⊆ s \ (t ∪ u) := begin rintros x ⟨⟨xs, xnt⟩, xnu⟩, use xs, rintros (xt | xu); contradiction end /-! ### Exercises -/ example : (s ∩ t) ∪ (s ∩ u) ⊆ s ∩ (t ∪ u):= sorry example : s \ (t ∪ u) ⊆ s \ t \ u := sorry /-! ### Proving two sets are equal -/ -- the ext tactic example : s ∩ t = t ∩ s := begin ext x, -- simp only [mem_inter_eq], -- optional. split, { rintros ⟨xs, xt⟩, exact ⟨xt, xs⟩ }, rintros ⟨xt, xs⟩, exact ⟨xs, xt⟩ end example : s ∩ t = t ∩ s := by ext x; simp [and.comm] /-! ### Exercises -/ example : s ∩ (s ∪ t) = s := sorry example : s ∪ (s ∩ t) = s := sorry example : (s \ t) ∪ t = s ∪ t := sorry example : (s \ t) ∪ (t \ s) = (s ∪ t) \ (s ∩ t) := sorry /-! ### Set-builder notation -/ def evens : set ℕ := {n | even n} def odds : set ℕ := {n | ¬ even n} example : evens ∪ odds = univ := begin rw [evens, odds], ext n, simp, apply classical.em end example : s ∩ t = {x | x ∈ s ∧ x ∈ t} := rfl example : s ∪ t = {x | x ∈ s ∨ x ∈ t} := rfl example : (∅ : set α) = {x | false} := rfl example : (univ : set α) = {x | true} := rfl example (x : ℕ) (h : x ∈ (∅ : set ℕ)) : false := h example (x : ℕ) : x ∈ (univ : set ℕ) := trivial /-! ### Exercise -/ -- Use `intro n` to unfold the definition of subset, -- and use the simplifier to reduce the -- set-theoretic constructions to logic. -- We also recommend using the theorems -- ``prime.eq_two_or_odd`` and ``even_iff``. example : { n | prime n } ∩ { n | n > 2} ⊆ { n | ¬ even n } := sorry /-! Indexed unions -/ -- See *Mathematics in Lean* for a discussion of -- bounded quantifiers, which we will skip here. section -- We can use any index type in place of ℕ variables A B : ℕ → set α example : s ∩ (⋃ i, A i) = ⋃ i, (A i ∩ s) := begin ext x, simp only [mem_inter_eq, mem_Union], split, { rintros ⟨xs, ⟨i, xAi⟩⟩, exact ⟨i, xAi, xs⟩ }, rintros ⟨i, xAi, xs⟩, exact ⟨xs, ⟨i, xAi⟩⟩ end example : (⋂ i, A i ∩ B i) = (⋂ i, A i) ∩ (⋂ i, B i) := begin ext x, simp only [mem_inter_eq, mem_Inter], split, { intro h, split, { intro i, exact (h i).1 }, intro i, exact (h i).2 }, rintros ⟨h1, h2⟩ i, split, { exact h1 i }, exact h2 i end end /-! ### Exercise -/ -- One direction requires classical logic! -- We recommend using ``by_cases xs : x ∈ s`` -- at an appropriate point in the proof. section variables A B : ℕ → set α example : s ∪ (⋂ i, A i) = ⋂ i, (A i ∪ s) := sorry end /- Mathlib also has bounded unions and intersections, `⋃ x ∈ s, f x` and `⋂ x ∈ s, f x`, and set unions and intersections, `⋃₀ s` and `⋂₀ s`, where `s : set α`. See *Mathematics in Lean* for details. -/ end set_variables /-! ### Functions -/ section function_variables variable f : α → β variables s t : set α variables u v : set β variable A : I → set α variable B : I → set β #check f '' s #check image f s #check f ⁻¹' u -- type as \inv' and then hit space or tab #check preimage f u example : f '' s = {y | ∃ x, x ∈ s ∧ f x = y} := rfl example : f ⁻¹' u = {x | f x ∈ u } := rfl example : f ⁻¹' (u ∩ v) = f ⁻¹' u ∩ f ⁻¹' v := by { ext, refl } example : f '' (s ∪ t) = f '' s ∪ f '' t := begin ext y, split, { rintros ⟨x, xs | xt, rfl⟩, { left, use [x, xs] }, right, use [x, xt] }, rintros (⟨x, xs, rfl⟩ | ⟨x, xt, rfl⟩), { use [x, or.inl xs] }, use [x, or.inr xt] end example : s ⊆ f ⁻¹' (f '' s) := begin intros x xs, show f x ∈ f '' s, use [x, xs] end /-! ### Exercises -/ example : f '' s ⊆ u ↔ s ⊆ f ⁻¹' u := sorry example (h : injective f) : f ⁻¹' (f '' s) ⊆ s := sorry example : f '' (f⁻¹' u) ⊆ u := sorry example (h : surjective f) : u ⊆ f '' (f⁻¹' u) := sorry example (h : s ⊆ t) : f '' s ⊆ f '' t := sorry example (h : u ⊆ v) : f ⁻¹' u ⊆ f ⁻¹' v := sorry example : f ⁻¹' (u ∪ v) = f ⁻¹' u ∪ f ⁻¹' v := sorry example : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := sorry example (h : injective f) : f '' s ∩ f '' t ⊆ f '' (s ∩ t) := sorry example : f '' s \ f '' t ⊆ f '' (s \ t) := sorry example : f ⁻¹' u \ f ⁻¹' v ⊆ f ⁻¹' (u \ v) := sorry example : f '' s ∩ v = f '' (s ∩ f ⁻¹' v) := sorry example : f '' (s ∩ f ⁻¹' u) ⊆ f '' s ∪ u := sorry example : s ∩ f ⁻¹' u ⊆ f ⁻¹' (f '' s ∩ u) := sorry example : s ∪ f ⁻¹' u ⊆ f ⁻¹' (f '' s ∪ u) := sorry example : f '' (⋃ i, A i) = ⋃ i, f '' A i := sorry example : f '' (⋂ i, A i) ⊆ ⋂ i, f '' A i := sorry example (i : I) (injf : injective f) : (⋂ i, f '' A i) ⊆ f '' (⋂ i, A i) := sorry by { ext x, simp } sorry by { ext x, simp } sorry from h₁ sorry by rwa h at h₁
94d8ef70e282081244cb7d061c50e6a55bd4d5a2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1725.lean
aaea049f4a1d0733915ad3f42c1ded7ea5a930fe
[ "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
692
lean
structure Fun (α β : Type) : Type where toFun : α → β instance : CoeFun (Fun α β) (fun _ => α → β) where coe := Fun.toFun example (f : Fun α α) : α → α := f ∘ f example (f : Fun α β) : (γ δ : Type) × (γ → δ) := ⟨_, _, f⟩ structure Equiv (α : Sort _) (β : Sort _) := (toFun : α → β) (invFun : β → α) local infix:25 " ≃ " => Equiv variable {α β γ : Sort _} instance : CoeFun (α ≃ β) (λ _ => α → β) := ⟨Equiv.toFun⟩ def Equiv.symm (e : α ≃ β) : β ≃ α := ⟨e.invFun, e.toFun⟩ protected def Equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩
5cce700356a7b7f1a93b2ecd9d92567cd4ef863c
4fa161becb8ce7378a709f5992a594764699e268
/src/analysis/special_functions/trigonometric.lean
a858b1c41ec86976794aed6f24d22dc1109e8529
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
65,697
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import analysis.special_functions.exp_log /-! # Trigonometric functions ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on complex numbers ## Main statements Many basic inequalities on trigonometric functions are established. The continuity and differentiability of the usual trigonometric functions are proved, and their derivatives are computed. ## Tags log, sin, cos, tan, arcsin, arccos, arctan, angle, argument -/ noncomputable theory open_locale classical namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, neg_neg] end lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end complex section /-! Register lemmas for the derivatives of the composition of `complex.cos`, `complex.sin`, `complex.cosh` and `complex.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! `complex.cos`-/ lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x := (complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_deriv_within_at.ccos.differentiable_within_at @[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cos (f x)) x := hc.has_deriv_at.ccos.differentiable_at lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cos (f x)) s := λx h, (hc x h).ccos @[simp] lemma differentiable.ccos (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cos (f x)) := λx, (hc x).ccos lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccos.deriv_within hxs @[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) : deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) := hc.has_deriv_at.ccos.deriv /-! `complex.sin`-/ lemma has_deriv_at.csin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x := (complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_deriv_within_at.csin.differentiable_within_at @[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sin (f x)) x := hc.has_deriv_at.csin.differentiable_at lemma differentiable_on.csin (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sin (f x)) s := λx h, (hc x h).csin @[simp] lemma differentiable.csin (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sin (f x)) := λx, (hc x).csin lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csin.deriv_within hxs @[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) : deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) := hc.has_deriv_at.csin.deriv /-! `complex.cosh`-/ lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_deriv_within_at.ccosh.differentiable_within_at @[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cosh (f x)) x := hc.has_deriv_at.ccosh.differentiable_at lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cosh (f x)) s := λx h, (hc x h).ccosh @[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cosh (f x)) := λx, (hc x).ccosh lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccosh.deriv_within hxs @[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) : deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) := hc.has_deriv_at.ccosh.deriv /-! `complex.sinh`-/ lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_deriv_within_at.csinh.differentiable_within_at @[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sinh (f x)) x := hc.has_deriv_at.csinh.differentiable_at lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sinh (f x)) s := λx h, (hc x h).csinh @[simp] lemma differentiable.csinh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sinh (f x)) := λx, (hc x).csinh lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csinh.deriv_within hxs @[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) : deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) := hc.has_deriv_at.csinh.deriv end namespace real variables {x y z : ℝ} lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin : differentiable_at ℝ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos : differentiable_at ℝ cos x := differentiable_cos x lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end real section /-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`, `real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! `real.cos`-/ lemma has_deriv_at.cos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x := (real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_deriv_within_at.cos.differentiable_within_at @[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cos (f x)) x := hc.has_deriv_at.cos.differentiable_at lemma differentiable_on.cos (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cos (f x)) s := λx h, (hc x h).cos @[simp] lemma differentiable.cos (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cos (f x)) := λx, (hc x).cos lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cos.deriv_within hxs @[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) : deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) := hc.has_deriv_at.cos.deriv /-! `real.sin`-/ lemma has_deriv_at.sin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x := (real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_deriv_within_at.sin.differentiable_within_at @[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sin (f x)) x := hc.has_deriv_at.sin.differentiable_at lemma differentiable_on.sin (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sin (f x)) s := λx h, (hc x h).sin @[simp] lemma differentiable.sin (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sin (f x)) := λx, (hc x).sin lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sin.deriv_within hxs @[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) : deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) := hc.has_deriv_at.sin.deriv /-! `real.cosh`-/ lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x := (real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_deriv_within_at.cosh.differentiable_within_at @[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cosh (f x)) x := hc.has_deriv_at.cosh.differentiable_at lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cosh (f x)) s := λx h, (hc x h).cosh @[simp] lemma differentiable.cosh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cosh (f x)) := λx, (hc x).cosh lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cosh.deriv_within hxs @[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) : deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) := hc.has_deriv_at.cosh.deriv /-! `real.sinh`-/ lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x := (real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_deriv_within_at.sinh.differentiable_within_at @[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sinh (f x)) x := hc.has_deriv_at.sinh.differentiable_at lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sinh (f x)) s := λx h, (hc x h).sinh @[simp] lemma differentiable.sinh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sinh (f x)) := λx, (hc x).sinh lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sinh.deriv_within hxs @[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) : deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) := hc.has_deriv_at.sinh.deriv end namespace real lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.2 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ (@two_ne_zero ℝ _), sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_right_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : @is_add_group_hom ℝ angle _ _ (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑((n : ℝ) * x) = n •ℕ (↑x : angle) := by simpa using add_monoid_hom.map_nsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp, norm_cast] lemma coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) : ↑((n : ℝ) * x : ℝ) = n •ℤ (↑x : angle) := by simpa using add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_right_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_right_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.right_inverse.surjective tan_arctan lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, euclidean_domain.zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right' _ (mt abs_eq_zero.1 h)] end lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re] @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] end complex
42b7d982d97afe8e93689ae8e714b6f894c49d1a
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/metric_space/emetric_space.lean
c11d19a2cb2f880fbf31aa6daf47ab278129bd21
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
45,838
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.real.ennreal import data.finset.intervals import topology.uniform_space.uniform_embedding import topology.uniform_space.pi import topology.uniform_space.uniform_convergence /-! # Extended metric spaces This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ℝ≥0∞`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity. The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize to `emetric_space` at the end. -/ open set filter classical noncomputable theory open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) /-- `has_edist α` means that `α` is equipped with an extended distance. -/ class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞) export has_edist (edist) /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ℝ≥0∞) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ℝ≥0∞) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] } -- the uniform structure is embedded in the emetric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the value ∞ Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure on a product. Continuity of `edist` is proved in `topology.instances.ennreal` -/ class pseudo_emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [pseudo_emetric_space α] @[priority 100] -- see Note [lower instance priority] instance pseudo_emetric_space.to_uniform_space' : uniform_space α := pseudo_emetric_space.to_uniform_space export pseudo_emetric_space (edist_self edist_comm edist_triangle) attribute [simp] edist_self /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _ /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) := begin revert n, refine nat.le_induction _ _, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self], -- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too. exact le_refl (0:ℝ≥0∞) }, { assume n hn hrec, calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) : edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n) /-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (edist_le_Ico_sum_edist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced with an upper estimate. -/ lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) : edist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_pseudoedist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist theorem uniformity_basis_edist : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := (@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal (λ r hr p hp, ⟨min r p, lt_min hr hp, λ x hx, lt_of_lt_of_le hx (min_le_left _ _), λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩) ⟨1, ennreal.zero_lt_one⟩ /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := uniformity_basis_edist.mem_uniformity_iff /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`, `uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/ protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases hf ε ε₀ with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end /-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/ protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ } end theorem uniformity_basis_edist_le : (𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') : (𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) := emetric.mk_uniformity_basis_le (λ _, and.left) (λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in ⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩) theorem uniformity_basis_edist_nnreal : (𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) := emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2) (λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in ⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩) theorem uniformity_basis_edist_inv_nat : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) := emetric.mk_uniformity_basis (λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) theorem uniformity_basis_edist_inv_two_pow : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) := emetric.mk_uniformity_basis (λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _) (λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩) /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) := is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩ /-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/ theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b}, a ∈ s → b ∈ s → edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist /-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/ theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist /-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/ theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩, end /-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := uniform_space.complete_of_convergent_controlled_sequences uniformity_has_countable_basis (λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H /-- A sequentially complete pseudoemetric space is complete. -/ theorem complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis /-- Expressing locally uniform convergence on a set using `edist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `edist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `edist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, mem_univ, forall_const, exists_prop, nhds_within_univ] /-- Expressing uniform convergence using `edist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε := by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const] end emetric open emetric /-- Auxiliary function to replace the uniformity on a pseudoemetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct a pseudoemetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : pseudo_emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) } /-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/ def pseudo_emetric_space.induced {α β} (f : α → β) (m : pseudo_emetric_space β) : pseudo_emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/ instance {α : Type*} {p : α → Prop} [t : pseudo_emetric_space α] : pseudo_emetric_space (subtype p) := t.induced coe /-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of the original pseudodistance, by definition -/ theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl /-- The product of two pseudoemetric spaces, with the max distance, is an extended pseudometric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [pseudo_emetric_space.uniformity_edist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) : edist x y = max (edist x.1 y.1) (edist x.2 y.2) := rfl section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of pseudoemetric spaces, with the max distance, is still a pseudoemetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] : pseudo_emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb)) end, to_uniform_space := Pi.uniform_space _, uniformity_edist := begin simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq, comap_principal], rw infi_comm, congr, funext ε, rw infi_comm, congr, funext εpos, change 0 < ε at εpos, simp [set.ext_iff, εpos] end } lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) : edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl @[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b := finset.sup_const univ_nonempty (edist a b) lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) : edist (f b) (g b) ≤ edist f g := finset.le_sup (finset.mem_univ b) end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ /-- Relation “two points are at a finite edistance” is an equivalence relation. -/ def edist_lt_top_setoid : setoid α := { r := λ x y, edist x y < ⊤, iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top }, λ x y h, by rwa edist_comm, λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ } @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [emetric.ball_eq_empty_iff] theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_edist theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_edist_le theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) := nhds_basis_eball.eq_binfi theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem is_closed_ball_top : is_closed (ball x ⊤) := is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $ ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩ theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open.mem_nhds is_open_ball (mem_ball_self ε0) theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, max_lt_iff.symm theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, max_le_iff.symm /-- ε-characterization of the closure in pseudoemetric spaces -/ theorem mem_closure_iff : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := (mem_closure_iff_nhds_basis nhds_basis_eball).trans $ by simp only [mem_ball, edist_comm x] theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε := nhds_basis_eball.tendsto_right_iff theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_eball).trans $ by simp only [exists_prop, true_and, mem_Ici, mem_ball] /-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually, the pseudoedistance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε := uniformity_basis_edist.cauchy_seq_iff /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε := uniformity_basis_edist.cauchy_seq_iff' /-- A variation of the emetric characterization of Cauchy sequences that deals with `ℝ≥0` upper bounds. -/ theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε := uniformity_basis_edist_nnreal.cauchy_seq_iff' theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section first_countable @[priority 100] -- see Note [lower instance priority] instance (α : Type u) [pseudo_emetric_space α] : topological_space.first_countable_topology α := uniform_space.first_countable_topology uniformity_has_countable_basis end first_countable section compact /-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/ lemma subset_countable_closure_of_almost_dense_set (s : set α) (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩, { exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ }, choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)), have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2), { intros r x, rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩, { refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ }, { refine ⟨y, hys, λ z hz, _⟩, calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add hz.1 hxy ... = r * 2 : (mul_two r).symm } }, choose f hfs hf, refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _), countable_Union $ λ n, (hTc n).image _, _⟩, refine λ x hx, mem_closure_iff.2 (λ ε ε0, _), rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0).ne' with ⟨n, hn⟩, rcases mem_bUnion_iff.1 (hsT n hx) with ⟨y, hyn, hyx⟩, refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩, calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩ ... < ε : ennreal.mul_lt_of_lt_div hn end /-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a countable set. -/ lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s ⊆ closure t) := begin refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _), rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩, exact ⟨t, htf.countable, subset.trans hst (bUnion_subset_bUnion_right $ λ _ _, ball_subset_closed_ball)⟩ end end compact section second_countable open topological_space variables (α) /-- A separable pseudoemetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable [separable_space α] : second_countable_topology α := uniform_space.second_countable_of_separable uniformity_has_countable_basis /-- A sigma compact pseudo emetric space has second countable topology. This is not an instance to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/ lemma second_countable_of_sigma_compact [sigma_compact_space α] : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, choose T hTsub hTc hsubT using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n), refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact closure_mono (subset_Union _ n) (hsubT _ hn) end variable {α} lemma second_countable_of_almost_dense_set (hs : ∀ ε > 0, ∃ t : set α, countable t ∧ (⋃ x ∈ t, closed_ball x ε) = univ) : second_countable_topology α := begin suffices : separable_space α, by exactI second_countable_of_separable α, rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _) with ⟨t, -, htc, ht⟩, { exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ }, { rcases hs ε ε0 with ⟨t, htc, ht⟩, exact ⟨t, htc, univ_subset_iff.2 ht⟩ } end end second_countable section diam /-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/ def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y lemma diam_le_iff {d : ℝ≥0∞} : diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d := by simp only [diam, supr_le_iff] lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} : diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d := by simp only [diam_le_iff, ball_image_iff] lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d := diam_le_iff.1 hd x hx y hy /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := edist_le_of_diam_le hx hy le_rfl /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h /-- The diameter of a subsingleton vanishes. -/ lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := nonpos_iff_eq_zero.1 $ diam_le $ λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) := eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff, edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and, forall_and_distrib, and_self, ← and_assoc] lemma diam_pair : diam ({x, y} : set α) = edist x y := by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right] lemma diam_triple : diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) := by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton, ennreal.max_zero_right, ennreal.sup_eq_max] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy) /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add (add_le_add (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le (λa ha b hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_self_add ... = diam s + edist x y + diam t : (add_assoc _ _ _).symm }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_self } end lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r := diam_le $ λa ha b hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : (two_mul r).symm lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace /-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/ class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u := (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) variables {γ : Type w} [emetric_space γ] @[priority 100] -- see Note [lower instance priority] instance emetric_space.to_uniform_space' : uniform_space γ := pseudo_emetric_space.to_uniform_space export emetric_space (eq_of_edist_eq_zero) /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y := nonpos_iff_eq_zero.trans edist_eq_zero @[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le] /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h) /-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) := begin split, { assume h, exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : edist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : edist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end /-- An emetric space is separated -/ @[priority 100] -- see Note [lower instance priority] instance to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- If a `pseudo_emetric_space` is separated, then it is an `emetric_space`. -/ def emetric_of_t2_pseudo_emetric_space {α : Type*} [pseudo_emetric_space α] (h : separated_space α) : emetric_space α := { eq_of_edist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_edist.1 hs, exact H (show edist x y < ε, by rwa [hdist]) end ..‹pseudo_emetric_space α› } /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) : emetric_space γ := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) } /-- The extended metric induced by an injective function taking values in a emetric space. -/ def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : emetric_space β) : emetric_space γ := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced coe (λ x y, subtype.ext_iff_val.2) /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) := { eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := edist_le_zero.1 h₁, have B : x.snd = y.snd := edist_le_zero.1 h₂, exact prod.ext_iff.2 ⟨A, B⟩ end, ..prod.pseudo_emetric_space_max } /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist : 𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} := pseudo_emetric_space.uniformity_edist section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b), end, ..pseudo_emetric_space_pi } end pi namespace emetric /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/ lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩, exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩ end section diam variables {s : set γ} lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton := ⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩ lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y := begin have := not_congr (@diam_eq_zero_iff _ _ s), dunfold set.subsingleton at this, push_neg at this, simpa only [pos_iff_ne_zero, exists_prop] using this end end diam end emetric
b46c93dce38207449bce1c19168da0e280858733
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/logic/relation.lean
b9793edf6f6b460655811e1b9e5446f65eab0504
[]
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
13,477
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 Transitive reflexive as well as reflexive closure of relations. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.basic import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib namespace relation /-- 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 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (r : α → β → Prop) (p : β → γ → Prop) (a : α) (c : γ) := ∃ (b : β), r a b ∧ p b c theorem comp_eq {α : Type u_1} {β : Type u_2} {r : α → β → Prop} : comp r Eq = r := sorry theorem eq_comp {α : Type u_1} {β : Type u_2} {r : α → β → Prop} : comp Eq r = r := sorry theorem iff_comp {α : Type u_1} {r : Prop → α → Prop} : comp Iff r = r := sorry theorem comp_iff {α : Type u_1} {r : α → Prop → Prop} : comp r Iff = r := sorry theorem comp_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {r : α → β → Prop} {p : β → γ → Prop} {q : γ → δ → Prop} : comp (comp r p) q = comp r (comp p q) := sorry theorem flip_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {r : α → β → Prop} {p : β → γ → Prop} : flip (comp r p) = comp (flip p) (flip r) := sorry /-- 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 {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (r : α → β → Prop) (f : α → γ) (g : β → δ) : γ → δ → Prop := fun (c : γ) (d : δ) => ∃ (a : α), ∃ (b : β), r a b ∧ f a = c ∧ g b = d /-- `refl_trans_gen r`: reflexive transitive closure of `r` -/ inductive refl_trans_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where | refl : refl_trans_gen r a a | tail : ∀ {b c : α}, refl_trans_gen r a b → r b c → refl_trans_gen r a c /-- `refl_gen r`: reflexive closure of `r` -/ inductive refl_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where | refl : refl_gen r a a | single : ∀ {b : α}, r a b → refl_gen r a b /-- `trans_gen r`: transitive closure of `r` -/ inductive trans_gen {α : Type u_1} (r : α → α → Prop) (a : α) : α → Prop where | single : ∀ {b : α}, r a b → trans_gen r a b | tail : ∀ {b c : α}, trans_gen r a b → r b c → trans_gen r a c theorem refl_gen.to_refl_trans_gen {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} : refl_gen r a b → refl_trans_gen r a b := sorry namespace refl_trans_gen theorem trans {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : refl_trans_gen r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := sorry theorem single {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (hab : r a b) : refl_trans_gen r a b := tail refl hab theorem head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b) (hbc : refl_trans_gen r b c) : refl_trans_gen r a c := sorry theorem symmetric {α : Type u_1} {r : α → α → Prop} (h : symmetric r) : symmetric (refl_trans_gen r) := sorry theorem cases_tail {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} : refl_trans_gen r a b → b = a ∨ ∃ (c : α), refl_trans_gen r a c ∧ r c b := iff.mp (cases_tail_iff r a b) theorem head_induction_on {α : Type u_1} {r : α → α → Prop} {b : α} {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 (head h' h)) : P a h := sorry theorem trans_induction_on {α : Type u_1} {r : α → α → Prop} {P : {a b : α} → refl_trans_gen r a b → Prop} {a : α} {b : α} (h : refl_trans_gen r a b) (ih₁ : α → P 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 (trans h₁ h₂)) : P h := sorry theorem cases_head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : refl_trans_gen r a b) : a = b ∨ ∃ (c : α), r a c ∧ refl_trans_gen r c b := sorry theorem cases_head_iff {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} : refl_trans_gen r a b ↔ a = b ∨ ∃ (c : α), r a c ∧ refl_trans_gen r c b := sorry theorem total_of_right_unique {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (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 := sorry end refl_trans_gen namespace trans_gen theorem to_refl {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : trans_gen r a b) : refl_trans_gen r a b := trans_gen.drec (fun {b : α} (h : r a b) => refl_trans_gen.single h) (fun {b c : α} (h_ᾰ : trans_gen r a b) (bc : r b c) (ab : refl_trans_gen r a b) => refl_trans_gen.tail ab bc) h theorem trans_left {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : trans_gen r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := sorry theorem trans {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := trans_left hab (to_refl hbc) theorem head' {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b) (hbc : refl_trans_gen r b c) : trans_gen r a c := trans_left (single hab) hbc theorem tail' {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : refl_trans_gen r a b) (hbc : r b c) : trans_gen r a c := sorry theorem trans_right {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : refl_trans_gen r a b) (hbc : trans_gen r b c) : trans_gen r a c := sorry theorem head {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (hab : r a b) (hbc : trans_gen r b c) : trans_gen r a c := head' hab (to_refl hbc) theorem tail'_iff {α : Type u_1} {r : α → α → Prop} {a : α} {c : α} : trans_gen r a c ↔ ∃ (b : α), refl_trans_gen r a b ∧ r b c := sorry theorem head'_iff {α : Type u_1} {r : α → α → Prop} {a : α} {c : α} : trans_gen r a c ↔ ∃ (b : α), r a b ∧ refl_trans_gen r b c := sorry theorem trans_gen_eq_self {α : Type u_1} {r : α → α → Prop} (trans : transitive r) : trans_gen r = r := sorry theorem transitive_trans_gen {α : Type u_1} {r : α → α → Prop} : transitive (trans_gen r) := fun (a b c : α) => trans theorem trans_gen_idem {α : Type u_1} {r : α → α → Prop} : trans_gen (trans_gen r) = trans_gen r := trans_gen_eq_self transitive_trans_gen theorem trans_gen_lift {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {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) := sorry theorem trans_gen_lift' {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {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) := eq.mpr (id (Eq.refl (trans_gen p (f a) (f b)))) (eq.mp (congr_fun (congr_fun trans_gen_idem (f a)) (f b)) (trans_gen_lift f h hab)) theorem trans_gen_closed {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {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 end trans_gen theorem refl_trans_gen_iff_eq {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : ∀ (b : α), ¬r a b) : refl_trans_gen r a b ↔ b = a := sorry theorem refl_trans_gen_iff_eq_or_trans_gen {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} : refl_trans_gen r a b ↔ b = a ∨ trans_gen r a b := sorry theorem refl_trans_gen_lift {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {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 (fun (a : α) => refl_trans_gen.refl) (fun (a b : α) => refl_trans_gen.single ∘ h a b) fun (a b c : α) (_x : refl_trans_gen r a b) (_x : refl_trans_gen r b c) => refl_trans_gen.trans theorem refl_trans_gen_mono {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {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 theorem refl_trans_gen_eq_self {α : Type u_1} {r : α → α → Prop} (refl : reflexive r) (trans : transitive r) : refl_trans_gen r = r := sorry theorem reflexive_refl_trans_gen {α : Type u_1} {r : α → α → Prop} : reflexive (refl_trans_gen r) := fun (a : α) => refl_trans_gen.refl theorem transitive_refl_trans_gen {α : Type u_1} {r : α → α → Prop} : transitive (refl_trans_gen r) := fun (a b c : α) => refl_trans_gen.trans theorem refl_trans_gen_idem {α : Type u_1} {r : α → α → Prop} : refl_trans_gen (refl_trans_gen r) = refl_trans_gen r := refl_trans_gen_eq_self reflexive_refl_trans_gen transitive_refl_trans_gen theorem refl_trans_gen_lift' {α : Type u_1} {β : Type u_2} {r : α → α → Prop} {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) := eq.mpr (id (Eq.refl (refl_trans_gen p (f a) (f b)))) (eq.mp (congr_fun (congr_fun refl_trans_gen_idem (f a)) (f b)) (refl_trans_gen_lift f h hab)) theorem refl_trans_gen_closed {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {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 /-- 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 {α : Type u_1} (r : α → α → Prop) : α → α → Prop := fun (a b : α) => ∃ (c : α), r a c ∧ r b c theorem church_rosser {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {c : α} (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 := sorry theorem join_of_single {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : reflexive r) (hab : r a b) : join r a b := Exists.intro b { left := hab, right := h b } theorem symmetric_join {α : Type u_1} {r : α → α → Prop} : symmetric (join r) := sorry theorem reflexive_join {α : Type u_1} {r : α → α → Prop} (h : reflexive r) : reflexive (join r) := fun (a : α) => Exists.intro a { left := h a, right := h a } theorem transitive_join {α : Type u_1} {r : α → α → Prop} (ht : transitive r) (h : ∀ (a b c : α), r a b → r a c → join r b c) : transitive (join r) := sorry theorem equivalence_join {α : Type u_1} {r : α → α → Prop} (hr : reflexive r) (ht : transitive r) (h : ∀ (a b c : α), r a b → r a c → join r b c) : equivalence (join r) := { left := reflexive_join hr, right := { left := symmetric_join, right := transitive_join ht h } } theorem equivalence_join_refl_trans_gen {α : Type u_1} {r : α → α → Prop} (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 fun (a b c : α) => church_rosser h theorem join_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {r' : α → α → Prop} (hr : equivalence r) (h : ∀ (a b : α), r' a b → r a b) : join r' a b → r a b := sorry theorem refl_trans_gen_of_transitive_reflexive {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {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 := refl_trans_gen.drec (hr a) (fun {b c : α} (hab : refl_trans_gen r' a b) (hbc : r' b c) (ih : r a b) => ht ih (h b c hbc)) h' theorem refl_trans_gen_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} {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 (and.left hr) (and.right (and.right hr)) theorem eqv_gen_iff_of_equivalence {α : Type u_1} {r : α → α → Prop} {a : α} {b : α} (h : equivalence r) : eqv_gen r a b ↔ r a b := sorry theorem eqv_gen_mono {α : Type u_1} {a : α} {b : α} {r : α → α → Prop} {p : α → α → Prop} (hrp : ∀ (a b : α), r a b → p a b) (h : eqv_gen r a b) : eqv_gen p a b := sorry
4568ad9e08580bb8c7dd01446fab7ec47b3404d0
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/file_not_found.lean
0ec53f2fe01927a741ea74346a5cfa7393d5a87a
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
582
lean
prelude import Init.System.IO open IO.FS #eval (IO.FS.Handle.mk "non-existent-file.txt" Mode.read *> pure () : IO Unit) #eval do condM (IO.fileExists "readonly.txt") (pure ()) (IO.FS.withFile "readonly.txt" Mode.write $ fun _ => pure ()); IO.setAccessRights "readonly.txt" { user := { read := true } }; (pure () : IO Unit) #eval (IO.FS.Handle.mk "readonly.txt" Mode.write *> pure () : IO Unit) #eval do h ← IO.FS.Handle.mk "readonly.txt" Mode.read; h.putStr "foo"; IO.println "foo"; (pure () : IO Unit)
2e9c83500b86f6c227f351eba337c6b95ec6105b
7c92a46ce39266c13607ecdef7f228688f237182
/src/valuation/field.lean
a928e5dfa279b007762f202aa6126acf9e4a74b1
[ "Apache-2.0" ]
permissive
asym57/lean-perfectoid-spaces
3217d01f6ddc0d13e9fb68651749469750420767
359187b429f254a946218af4411d45f08705c83e
refs/heads/master
1,609,457,937,251
1,577,542,616,000
1,577,542,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,654
lean
import for_mathlib.topological_field import for_mathlib.topology import for_mathlib.uniform_space.uniform_field import valuation.topology import valuation.with_zero_topology import topology.algebra.ordered /-! In this file we study the topology of a field `K` endowed with a valuation (in our application to adic spaces, `K` will be the valuation field associated to some valuation on a ring, defined in valuation.basic). We already know from valuation.topology that one can build a topology on `K` which makes it a topological ring. The first goal is to show `K` is a topological *field*, ie inversion is continuous at every non-zero element. The next goal is to prove `K` is a *completable* topological field. This gives us a completion `hat K` which is a topological field. We also prove that `K` is automatically separated, so the map from `K` to `hat K` is injective. Then we extend the valuation given on `K` to a valuation on `hat K`. -/ open filter set linear_ordered_structure local attribute [instance, priority 0] classical.DLO local notation `𝓝` x: 70 := nhds x section division_ring variables {K : Type*} [division_ring K] section valuation_topological_division_ring section inversion_estimate variables {Γ₀ : Type*} [linear_ordered_comm_group_with_zero Γ₀] (v : valuation K Γ₀) -- The following is the main technical lemma ensuring that inversion is continuous -- in the topology induced by a valuation on a division ring (ie the next instance) -- and the fact that a valued field is completable -- [BouAC, VI.5.1 Lemme 1] lemma valuation.inversion_estimate {x y : K} {γ : units Γ₀} (y_ne : y ≠ 0) (h : v (x - y) < min (γ * ((v y) * (v y))) (v y)) : v (x⁻¹ - y⁻¹) < γ := begin have hyp1 : v (x - y) < γ * ((v y) * (v y)), from lt_of_lt_of_le h (min_le_left _ _), have hyp1' : v (x - y) * ((v y) * (v y))⁻¹ < γ, from mul_inv_lt_of_lt_mul' hyp1, have hyp2 : v (x - y) < v y, from lt_of_lt_of_le h (min_le_right _ _), have key : v x = v y, from valuation.map_eq_of_sub_lt v hyp2, have x_ne : x ≠ 0, { intro h, apply y_ne, rw [h, v.map_zero] at key, exact v.zero_iff.1 key.symm }, have decomp : x⁻¹ - y⁻¹ = x⁻¹ * (y - x) * y⁻¹, by rw [mul_sub_left_distrib, sub_mul, mul_assoc, show y * y⁻¹ = 1, from mul_inv_cancel y_ne, show x⁻¹ * x = 1, from inv_mul_cancel x_ne, mul_one, one_mul], calc v (x⁻¹ - y⁻¹) = v (x⁻¹ * (y - x) * y⁻¹) : by rw decomp ... = (v x⁻¹) * (v $ y - x) * (v y⁻¹) : by repeat { rw valuation.map_mul } ... = (v x)⁻¹ * (v $ y - x) * (v y)⁻¹ : by rw [v.map_inv' x_ne, v.map_inv' y_ne] ... = (v $ y - x) * ((v y) * (v y))⁻¹ : by rw [mul_assoc, mul_comm, key, mul_assoc, ← group_with_zero.mul_inv_rev] ... = (v $ y - x) * ((v y) * (v y))⁻¹ : rfl ... = (v $ x - y) * ((v y) * (v y))⁻¹ : by rw valuation.map_sub_swap ... < γ : hyp1', end end inversion_estimate local attribute [instance] valued.subgroups_basis subgroups_basis.topology ring_filter_basis.topological_ring local notation `v` := valued.value /-- The topology coming from a valuation on a division rings make it a topological division ring [BouAC, VI.5.1 middle of Proposition 1] -/ instance valued.topological_division_ring [valued K] : topological_division_ring K := { continuous_inv := begin intros x x_ne s s_in, cases valued.mem_nhds.mp s_in with γ hs, clear s_in, rw [mem_map, valued.mem_nhds], change ∃ (γ : units (valued.Γ₀ K)), {y : K | v (y - x) < γ} ⊆ {x : K | x⁻¹ ∈ s}, have vx_ne := (valuation.ne_zero_iff $ valued.v K).mpr x_ne, let γ' := group_with_zero.mk₀ _ vx_ne, use min (γ * (γ'*γ')) γ', intros y y_in, apply hs, change v (y⁻¹ - x⁻¹) < γ, simp only [mem_set_of_eq] at y_in, rw [coe_min, units.coe_mul, units.coe_mul] at y_in, exact valuation.inversion_estimate _ x_ne y_in end, ..(by apply_instance : topological_ring K) } section local attribute [instance] linear_ordered_comm_group_with_zero.topological_space linear_ordered_comm_group_with_zero.regular_space linear_ordered_comm_group_with_zero.nhds_basis lemma valued.continuous_valuation [valued K] : continuous (v : K → valued.Γ₀ K) := begin rw continuous_iff_continuous_at, intro x, classical, by_cases h : x = 0, { rw h, change tendsto _ _ (𝓝 (valued.v K 0)), erw valuation.map_zero, rw linear_ordered_comm_group_with_zero.tendsto_zero, intro γ, rw valued.mem_nhds_zero, use [γ, set.subset.refl _] }, { change tendsto _ _ _, have v_ne : v x ≠ 0, from (valuation.ne_zero_iff _).mpr h, rw linear_ordered_comm_group_with_zero.tendsto_nonzero v_ne, apply valued.loc_const v_ne }, end end section -- until the end of this section, all linearly ordered commutative groups will be endowed with -- the discrete topology -- In the next lemma, K will be endowed with its left uniformity coming from the valuation topology local attribute [instance] valued.uniform_space /-- A valued division ring is separated. -/ instance valued_ring.separated [valued K] : separated K := begin apply topological_add_group.separated_of_zero_sep, intros x x_ne, refine ⟨{k | v k < v x}, _, λ h, lt_irrefl _ h⟩, rw valued.mem_nhds, have vx_ne := (valuation.ne_zero_iff $ valued.v K).mpr x_ne, let γ' := group_with_zero.mk₀ _ vx_ne, exact ⟨γ', λ y hy, by simpa using hy⟩, end end end valuation_topological_division_ring end division_ring section valuation_on_valued_field_completion open uniform_space -- In this section K is commutative (hence a field), and equipped with a valuation variables {K : Type*} [discrete_field K] [vK : valued K] include vK open valued local notation `v` := valued.value local attribute [instance, priority 0] valued.uniform_space valued.uniform_add_group local notation `hat` K := completion K set_option class.instance_max_depth 300 -- The following instances helps going over the uniform_add_group/topological_add_group loop lemma hatK_top_group : topological_add_group (hat K) := uniform_add_group.to_topological_add_group local attribute [instance] hatK_top_group lemma hatK_top_monoid : topological_add_monoid (hat K) := topological_add_group.to_topological_add_monoid _ local attribute [instance] hatK_top_monoid /-- A valued field is completable. -/ instance valued.completable : completable_top_field K := { separated := by apply_instance, nice := begin rintros F hF h0, have : ∃ (γ₀ : units (Γ₀ K)) (M ∈ F), ∀ x ∈ M, (γ₀ : Γ₀ K) ≤ v x, { rcases (filter.inf_eq_bot_iff _ _).1 h0 with ⟨U, U_in, M, M_in, H⟩, rcases valued.mem_nhds_zero.mp U_in with ⟨γ₀, hU⟩, existsi [γ₀, M, M_in], intros x xM, apply le_of_not_lt _, intro hyp, have : x ∈ U ∩ M := ⟨hU hyp, xM⟩, rwa H at this }, rcases this with ⟨γ₀, M₀, M₀_in, H₀⟩, rw valued.cauchy_iff at hF ⊢, refine ⟨map_ne_bot hF.1, _⟩, replace hF := hF.2, intros γ, rcases hF (min (γ * γ₀ * γ₀) γ₀) with ⟨M₁, M₁_in, H₁⟩, clear hF, use (λ x : K, x⁻¹) '' (M₀ ∩ M₁), split, { rw mem_map, apply mem_sets_of_superset (filter.inter_mem_sets M₀_in M₁_in), exact subset_preimage_image _ _ }, { rintros _ _ ⟨x, ⟨x_in₀, x_in₁⟩, rfl⟩ ⟨y, ⟨y_in₀, y_in₁⟩, rfl⟩, simp only [mem_set_of_eq], specialize H₁ x y x_in₁ y_in₁, replace x_in₀ := H₀ x x_in₀, replace y_in₀ := H₀ y y_in₀, clear H₀, apply valuation.inversion_estimate, { have : v x ≠ 0, { intro h, rw h at x_in₀, simpa using x_in₀, }, exact (valuation.ne_zero_iff _).mp this }, { refine lt_of_lt_of_le H₁ _, rw coe_min, apply min_le_min _ x_in₀, rw mul_assoc, have : ((γ₀ * γ₀ : units (Γ₀ K)) : Γ₀ K) ≤ v x * v x, from calc ↑γ₀ * ↑γ₀ ≤ ↑γ₀ * v x : actual_ordered_comm_monoid.mul_le_mul_left' x_in₀ ... ≤ _ : actual_ordered_comm_monoid.mul_le_mul_right' x_in₀, exact actual_ordered_comm_monoid.mul_le_mul_left' this } } end } local attribute [instance] linear_ordered_comm_group_with_zero.topological_space linear_ordered_comm_group_with_zero.regular_space linear_ordered_comm_group_with_zero.nhds_basis linear_ordered_comm_group_with_zero.t2_space linear_ordered_comm_group_with_zero.ordered_topology /-- The extension of the valuation of a valued field to the completion of the field. -/ noncomputable def valued.extension : (hat K) → Γ₀ K := completion.dense_inducing_coe.extend (v : K → Γ₀ K) lemma valued.continuous_extension : continuous (valued.extension : (hat K) → Γ₀ K) := begin refine completion.dense_inducing_coe.continuous_extend _, intro x₀, by_cases h : x₀ = coe 0, { refine ⟨0, _⟩, erw [h, ← completion.dense_inducing_coe.to_inducing.nhds_eq_comap]; try { apply_instance }, rw linear_ordered_comm_group_with_zero.tendsto_zero, intro γ₀, rw valued.mem_nhds, exact ⟨γ₀, by simp⟩ }, { have preimage_one : v ⁻¹' {(1 : Γ₀ K)} ∈ 𝓝 (1 : K), { have : v (1 : K) ≠ 0, { rw valued.map_one, exact zero_ne_one.symm }, convert valued.loc_const this, ext x, rw [valued.map_one, mem_preimage, mem_singleton_iff, mem_set_of_eq] }, obtain ⟨V, V_in, hV⟩ : ∃ V ∈ 𝓝 (1 : hat K), ∀ x : K, (x : hat K) ∈ V → v x = 1, { rwa [completion.dense_inducing_coe.nhds_eq_comap, mem_comap_sets] at preimage_one, rcases preimage_one with ⟨V, V_in, hV⟩, use [V, V_in], intros x x_in, specialize hV x_in, rwa [mem_preimage, mem_singleton_iff] at hV }, have : ∃ V' ∈ (𝓝 (1 : hat K)), (0 : hat K) ∉ V' ∧ ∀ x y ∈ V', x*y⁻¹ ∈ V, { have : tendsto (λ p : (hat K) × hat K, p.1*p.2⁻¹) ((𝓝 1).prod 𝓝 1) 𝓝 1, { rw ← nhds_prod_eq, conv {congr, skip, skip, rw ← (one_mul (1 : hat K))}, refine continuous_fst.continuous_at.mul (tendsto.comp _ continuous_snd.continuous_at), convert topological_division_ring.continuous_inv (1 : hat K) zero_ne_one.symm, exact inv_one.symm }, rcases tendsto_prod_self_iff.mp this V V_in with ⟨U, U_in, hU⟩, let hatKstar := (-{0} : set $ hat K), have : hatKstar ∈ 𝓝 (1 : hat K), { haveI : t1_space (hat K) := @t2_space.t1_space (hat K) _ (@separated_t2 (hat K) _ _), exact compl_singleton_mem_nhds zero_ne_one.symm }, use [U ∩ hatKstar, filter.inter_mem_sets U_in this], split, { rintro ⟨h, h'⟩, rw mem_compl_singleton_iff at h', exact h' rfl }, { rintros x y ⟨hx, _⟩ ⟨hy, _⟩, apply hU ; assumption } }, rcases this with ⟨V', V'_in, zeroV', hV'⟩, have nhds_right : (λ x, x*x₀) '' V' ∈ 𝓝 x₀, { have l : function.left_inverse (λ (x : hat K), x * x₀⁻¹) (λ (x : hat K), x * x₀), { intro x, simp only [mul_assoc, mul_inv_cancel h, mul_one] }, have r: function.right_inverse (λ (x : hat K), x * x₀⁻¹) (λ (x : hat K), x * x₀), { intro x, simp only [mul_assoc, inv_mul_cancel h, mul_one] }, have c : continuous (λ (x : hat K), x * x₀⁻¹), from continuous_id.mul continuous_const, rw image_eq_preimage_of_inverse l r, rw ← mul_inv_cancel h at V'_in, exact c.continuous_at V'_in }, have : ∃ (z₀ : K) (y₀ ∈ V'), coe z₀ = y₀*x₀ ∧ z₀ ≠ 0, { rcases dense_range.mem_nhds completion.dense nhds_right with ⟨z₀, y₀, y₀_in, h⟩, refine ⟨z₀, y₀, y₀_in, ⟨h.symm, _⟩⟩, intro hz, rw hz at h, cases discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero _ _ h ; finish }, rcases this with ⟨z₀, y₀, y₀_in, hz₀, z₀_ne⟩, have vz₀_ne: valued.v K z₀ ≠ 0 := by rwa valuation.ne_zero_iff, refine ⟨valued.v K z₀, _⟩, rw [linear_ordered_comm_group_with_zero.tendsto_nonzero vz₀_ne, mem_comap_sets], use [(λ x, x*x₀) '' V', nhds_right], intros x x_in, rcases mem_preimage.1 x_in with ⟨y, y_in, hy⟩, clear x_in, change y*x₀ = coe x at hy, have : valued.v K (x*z₀⁻¹) = 1, { apply hV, rw [completion.coe_mul, is_ring_hom.map_inv' (coe : K → hat K) z₀_ne, ← hy, hz₀, mul_inv'], assoc_rw mul_inv_cancel h, rw mul_one, solve_by_elim }, calc valued.v K x = valued.v K (x*z₀⁻¹*z₀) : by rw [mul_assoc, inv_mul_cancel z₀_ne, mul_one] ... = valued.v K (x*z₀⁻¹)*valued.v K z₀ : valuation.map_mul _ _ _ ... = valued.v K z₀ : by rw [this, one_mul] }, end @[elim_cast] lemma valued.extension_extends (x : K) : valued.extension (x : hat K) = v x := begin haveI : t2_space (valued.Γ₀ K) := regular_space.t2_space _, exact completion.dense_inducing_coe.extend_eq_of_cont valued.continuous_valuation x end /-- the extension of a valuation on a division ring to its completion. -/ noncomputable def valued.extension_valuation : valuation (hat K) (Γ₀ K) := { to_fun := valued.extension, map_zero' := by exact_mod_cast valuation.map_zero _, map_one' := by { rw [← completion.coe_one, valued.extension_extends (1 : K)], exact valuation.map_one _ }, map_mul' := λ x y, begin apply completion.induction_on₂ x y, { have c1 : continuous (λ (x : (hat K) × hat K), valued.extension (x.1 * x.2)), from valued.continuous_extension.comp (continuous_fst.mul continuous_snd), have c2 : continuous (λ (x : (hat K) × hat K), valued.extension x.1 * valued.extension x.2), from (valued.continuous_extension.comp continuous_fst).mul (valued.continuous_extension.comp continuous_snd), exact is_closed_eq c1 c2 }, { intros x y, norm_cast, exact valuation.map_mul _ _ _ }, end, map_add' := λ x y, begin rw le_max_iff, apply completion.induction_on₂ x y, { exact is_closed_union (is_closed_le ((valued.continuous_extension).comp continuous_add) ((valued.continuous_extension).comp continuous_fst)) (is_closed_le ((valued.continuous_extension).comp continuous_add) ((valued.continuous_extension).comp continuous_snd)) }, { intros x y, norm_cast, rw ← le_max_iff, exact valuation.map_add _ _ _ }, end } end valuation_on_valued_field_completion
5bfdf6c47e81f777447ac687905cd185cec9533c
7b02c598aa57070b4cf4fbfe2416d0479220187f
/algebra/graded.hlean
e7a5053748fa39b4f6040e892ada3c056d467856
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,667
hlean
/- Graded (left-) R-modules for a ring R. -/ -- Author: Floris van Doorn import .left_module .direct_sum .submodule --..heq open is_trunc algebra eq left_module pointed function equiv is_equiv prod group sigma sigma.ops nat trunc_index namespace left_module definition graded [reducible] (str : Type) (I : Type) : Type := I → str definition graded_module [reducible] (R : Ring) : Type → Type := graded (LeftModule R) -- TODO: We can (probably) make I a type everywhere variables {R : Ring} {I : Set} {M M₁ M₂ M₃ : graded_module R I} /- morphisms between graded modules. The definition is unconventional in two ways: (1) The degree is determined by an endofunction instead of a element of I (and in this case we don't need to assume that I is a group). The "standard" degree i corresponds to the endofunction which is addition with i on the right. However, this is more flexible. For example, the composition of two graded module homomorphisms φ₂ and φ₁ with degrees i₂ and i₁ has type M₁ i → M₂ ((i + i₁) + i₂). However, a homomorphism with degree i₁ + i₂ must have type M₁ i → M₂ (i + (i₁ + i₂)), which means that we need to insert a transport. With endofunctions this is not a problem: λi, (i + i₁) + i₂ is a perfectly fine degree of a map (2) Since we cannot eliminate all possible transports, we don't define a homomorphism as function M₁ i →lm M₂ (i + deg f) or M₁ i →lm M₂ (deg f i) but as a function taking a path as argument. Specifically, for every path deg f i = j we get a function M₁ i → M₂ j. (3) Note: we do assume that I is a set. This is not strictly necessary, but it simplifies things -/ definition graded_hom_of_deg (d : I ≃ I) (M₁ M₂ : graded_module R I) : Type := Π⦃i j : I⦄ (p : d i = j), M₁ i →lm M₂ j definition gmd_constant [constructor] (d : I ≃ I) (M₁ M₂ : graded_module R I) : graded_hom_of_deg d M₁ M₂ := λi j p, lm_constant (M₁ i) (M₂ j) definition gmd0 [constructor] {d : I ≃ I} {M₁ M₂ : graded_module R I} : graded_hom_of_deg d M₁ M₂ := gmd_constant d M₁ M₂ structure graded_hom (M₁ M₂ : graded_module R I) : Type := mk' :: (d : I ≃ I) (fn' : graded_hom_of_deg d M₁ M₂) notation M₁ ` →gm ` M₂ := graded_hom M₁ M₂ abbreviation deg [unfold 5] := @graded_hom.d postfix ` ↘`:max := graded_hom.fn' -- there is probably a better character for this? Maybe ↷? definition graded_hom_fn [reducible] [unfold 5] [coercion] (f : M₁ →gm M₂) (i : I) : M₁ i →lm M₂ (deg f i) := f ↘ idp definition graded_hom_fn_out [reducible] [unfold 5] (f : M₁ →gm M₂) (i : I) : M₁ ((deg f)⁻¹ i) →lm M₂ i := f ↘ (to_right_inv (deg f) i) infix ` ← `:max := graded_hom_fn_out -- todo: change notation -- definition graded_hom_fn_out_rec (f : M₁ →gm M₂) -- (P : Π{i j} (p : deg f i = j) (m : M₁ i) (n : M₂ j), Type) -- (H : Πi m, P (right_inv (deg f) i) m (f ← i m)) {i j : I} -- (p : deg f i = j) (m : M₁ i) (n : M₂ j) : P p m (f ↘ p m) := -- begin -- revert i j p m n, refine equiv_rect (deg f)⁻¹ᵉ _ _, intro i, -- refine eq.rec_to (right_inv (deg f) i) _, -- intro m n, exact H i m -- end -- definition graded_hom_fn_rec (f : M₁ →gm M₂) -- {P : Π{i j} (p : deg f i = j) (m : M₁ i) (n : M₂ j), Type} -- (H : Πi m, P idp m (f i m)) ⦃i j : I⦄ -- (p : deg f i = j) (m : M₁ i) : P p m (f ↘ p m) := -- begin -- induction p, apply H -- end -- definition graded_hom_fn_out_rec (f : M₁ →gm M₂) -- {P : Π{i j} (p : deg f i = j) (m : M₁ i) (n : M₂ j), Type} -- (H : Πi m, P idp m (f i m)) ⦃i : I⦄ (m : M₁ ((deg f)⁻¹ᵉ i)) : -- P (right_inv (deg f) i) m (f ← i m) := -- graded_hom_fn_rec f H (right_inv (deg f) i) m -- definition graded_hom_fn_out_rec_simple (f : M₁ →gm M₂) -- {P : Π{j} (n : M₂ j), Type} -- (H : Πi m, P (f i m)) ⦃i : I⦄ (m : M₁ ((deg f)⁻¹ᵉ i)) : -- P (f ← i m) := -- graded_hom_fn_out_rec f H m definition graded_hom.mk [constructor] (d : I ≃ I) (fn : Πi, M₁ i →lm M₂ (d i)) : M₁ →gm M₂ := graded_hom.mk' d (λi j p, homomorphism_of_eq (ap M₂ p) ∘lm fn i) definition graded_hom.mk_out [constructor] (d : I ≃ I) (fn : Πi, M₁ (d⁻¹ i) →lm M₂ i) : M₁ →gm M₂ := graded_hom.mk' d (λi j p, fn j ∘lm homomorphism_of_eq (ap M₁ (eq_inv_of_eq p))) definition graded_hom.mk_out' [constructor] (d : I ≃ I) (fn : Πi, M₁ (d i) →lm M₂ i) : M₁ →gm M₂ := graded_hom.mk' d⁻¹ᵉ (λi j p, fn j ∘lm homomorphism_of_eq (ap M₁ (eq_inv_of_eq p))) definition graded_hom.mk_out_in [constructor] (d₁ : I ≃ I) (d₂ : I ≃ I) (fn : Πi, M₁ (d₁ i) →lm M₂ (d₂ i)) : M₁ →gm M₂ := graded_hom.mk' (d₁⁻¹ᵉ ⬝e d₂) (λi j p, homomorphism_of_eq (ap M₂ p) ∘lm fn (d₁⁻¹ᵉ i) ∘lm homomorphism_of_eq (ap M₁ (to_right_inv d₁ i)⁻¹)) definition graded_hom_eq_transport (f : M₁ →gm M₂) {i j : I} (p : deg f i = j) (m : M₁ i) : f ↘ p m = transport M₂ p (f i m) := by induction p; reflexivity definition graded_hom_mk_refl (d : I ≃ I) (fn : Πi, M₁ i →lm M₂ (d i)) {i : I} (m : M₁ i) : graded_hom.mk d fn i m = fn i m := by reflexivity lemma graded_hom_mk_out'_destruct (d : I ≃ I) (fn : Πi, M₁ (d i) →lm M₂ i) {i : I} (m : M₁ (d i)) : graded_hom.mk_out' d fn ↘ (left_inv d i) m = fn i m := begin unfold [graded_hom.mk_out'], apply ap (λx, fn i (cast x m)), refine !ap_compose⁻¹ ⬝ ap02 _ _, apply is_set.elim --TODO: we can also prove this if I is not a set end lemma graded_hom_mk_out_destruct (d : I ≃ I) (fn : Πi, M₁ (d⁻¹ i) →lm M₂ i) {i : I} (m : M₁ (d⁻¹ i)) : graded_hom.mk_out d fn ↘ (right_inv d i) m = fn i m := begin rexact graded_hom_mk_out'_destruct d⁻¹ᵉ fn m end lemma graded_hom_mk_out_in_destruct (d₁ : I ≃ I) (d₂ : I ≃ I) (fn : Πi, M₁ (d₁ i) →lm M₂ (d₂ i)) {i : I} (m : M₁ (d₁ i)) : graded_hom.mk_out_in d₁ d₂ fn ↘ (ap d₂ (left_inv d₁ i)) m = fn i m := begin unfold [graded_hom.mk_out_in], rewrite [adj d₁, -ap_inv, - +ap_compose, ], refine cast_fn_cast_square fn _ _ !con.left_inv m end definition graded_hom_eq_zero {f : M₁ →gm M₂} {i j k : I} {q : deg f i = j} {p : deg f i = k} (m : M₁ i) (r : f ↘ q m = 0) : f ↘ p m = 0 := have f ↘ p m = transport M₂ (q⁻¹ ⬝ p) (f ↘ q m), begin induction p, induction q, reflexivity end, this ⬝ ap (transport M₂ (q⁻¹ ⬝ p)) r ⬝ tr_eq_of_pathover (apd (λi, 0) (q⁻¹ ⬝ p)) definition graded_hom_change_image {f : M₁ →gm M₂} {i j k : I} {m : M₂ k} (p : deg f i = k) (q : deg f j = k) (h : image (f ↘ p) m) : image (f ↘ q) m := begin have Σ(r : i = j), ap (deg f) r = p ⬝ q⁻¹, from ⟨eq_of_fn_eq_fn (deg f) (p ⬝ q⁻¹), !ap_eq_of_fn_eq_fn'⟩, induction this with r s, induction r, induction q, esimp at s, induction s, exact h end definition graded_hom_codom_rec {f : M₁ →gm M₂} {j : I} {P : Π⦃i⦄, deg f i = j → Type} {i i' : I} (p : deg f i = j) (h : P p) (q : deg f i' = j) : P q := begin have Σ(r : i = i'), ap (deg f) r = p ⬝ q⁻¹, from ⟨eq_of_fn_eq_fn (deg f) (p ⬝ q⁻¹), !ap_eq_of_fn_eq_fn'⟩, induction this with r s, induction r, induction q, esimp at s, induction s, exact h end variables {f' : M₂ →gm M₃} {f g h : M₁ →gm M₂} definition graded_hom_compose [constructor] (f' : M₂ →gm M₃) (f : M₁ →gm M₂) : M₁ →gm M₃ := graded_hom.mk' (deg f ⬝e deg f') (λi j p, f' ↘ p ∘lm f i) infixr ` ∘gm `:75 := graded_hom_compose definition graded_hom_compose_fn (f' : M₂ →gm M₃) (f : M₁ →gm M₂) (i : I) (m : M₁ i) : (f' ∘gm f) i m = f' (deg f i) (f i m) := by reflexivity definition graded_hom_compose_fn_ext (f' : M₂ →gm M₃) (f : M₁ →gm M₂) ⦃i j k : I⦄ (p : deg f i = j) (q : deg f' j = k) (r : (deg f ⬝e deg f') i = k) (s : ap (deg f') p ⬝ q = r) (m : M₁ i) : ((f' ∘gm f) ↘ r) m = (f' ↘ q) (f ↘ p m) := by induction s; induction q; induction p; reflexivity definition graded_hom_compose_fn_out (f' : M₂ →gm M₃) (f : M₁ →gm M₂) (i : I) (m : M₁ ((deg f ⬝e deg f')⁻¹ᵉ i)) : (f' ∘gm f) ← i m = f' ← i (f ← ((deg f')⁻¹ᵉ i) m) := graded_hom_compose_fn_ext f' f _ _ _ idp m -- the following composition might be useful if you want tight control over the paths to which f and f' are applied definition graded_hom_compose_ext [constructor] (f' : M₂ →gm M₃) (f : M₁ →gm M₂) (d : Π⦃i j⦄ (p : (deg f ⬝e deg f') i = j), I) (pf : Π⦃i j⦄ (p : (deg f ⬝e deg f') i = j), deg f i = d p) (pf' : Π⦃i j⦄ (p : (deg f ⬝e deg f') i = j), deg f' (d p) = j) : M₁ →gm M₃ := graded_hom.mk' (deg f ⬝e deg f') (λi j p, (f' ↘ (pf' p)) ∘lm (f ↘ (pf p))) variable (M) definition graded_hom_id [constructor] [refl] : M →gm M := graded_hom.mk erfl (λi, lmid) variable {M} abbreviation gmid [constructor] := graded_hom_id M definition gm_constant [constructor] (M₁ M₂ : graded_module R I) (d : I ≃ I) : M₁ →gm M₂ := graded_hom.mk' d (gmd_constant d M₁ M₂) definition is_surjective_graded_hom_compose ⦃x z⦄ (f' : M₂ →gm M₃) (f : M₁ →gm M₂) (p : deg f' (deg f x) = z) (H' : Π⦃y⦄ (q : deg f' y = z), is_surjective (f' ↘ q)) (H : Π⦃y⦄ (q : deg f x = y), is_surjective (f ↘ q)) : is_surjective ((f' ∘gm f) ↘ p) := begin induction p, apply is_surjective_compose (f' (deg f x)) (f x), apply H', apply H end structure graded_iso (M₁ M₂ : graded_module R I) : Type := mk' :: (to_hom : M₁ →gm M₂) (is_equiv_to_hom : Π⦃i j⦄ (p : deg to_hom i = j), is_equiv (to_hom ↘ p)) infix ` ≃gm `:25 := graded_iso attribute graded_iso.to_hom [coercion] attribute graded_iso._trans_of_to_hom [unfold 5] definition is_equiv_graded_iso [instance] [priority 1010] (φ : M₁ ≃gm M₂) (i : I) : is_equiv (φ i) := graded_iso.is_equiv_to_hom φ idp definition isomorphism_of_graded_iso' [constructor] (φ : M₁ ≃gm M₂) {i j : I} (p : deg φ i = j) : M₁ i ≃lm M₂ j := isomorphism.mk (φ ↘ p) !graded_iso.is_equiv_to_hom definition isomorphism_of_graded_iso [constructor] (φ : M₁ ≃gm M₂) (i : I) : M₁ i ≃lm M₂ (deg φ i) := isomorphism.mk (φ i) _ definition isomorphism_of_graded_iso_out [constructor] (φ : M₁ ≃gm M₂) (i : I) : M₁ ((deg φ)⁻¹ i) ≃lm M₂ i := isomorphism_of_graded_iso' φ !to_right_inv protected definition graded_iso.mk [constructor] (d : I ≃ I) (φ : Πi, M₁ i ≃lm M₂ (d i)) : M₁ ≃gm M₂ := begin apply graded_iso.mk' (graded_hom.mk d φ), intro i j p, induction p, exact to_is_equiv (equiv_of_isomorphism (φ i)), end protected definition graded_iso.mk_out [constructor] (d : I ≃ I) (φ : Πi, M₁ (d⁻¹ i) ≃lm M₂ i) : M₁ ≃gm M₂ := begin apply graded_iso.mk' (graded_hom.mk_out d φ), intro i j p, esimp, exact @is_equiv_compose _ _ _ _ _ !is_equiv_cast _, end definition graded_iso_of_eq [constructor] {M₁ M₂ : graded_module R I} (p : M₁ ~ M₂) : M₁ ≃gm M₂ := graded_iso.mk erfl (λi, isomorphism_of_eq (p i)) -- definition to_gminv [constructor] (φ : M₁ ≃gm M₂) : M₂ →gm M₁ := -- graded_hom.mk_out (deg φ)⁻¹ᵉ -- abstract begin -- intro i, apply isomorphism.to_hom, symmetry, -- apply isomorphism_of_graded_iso φ -- end end variable (M) definition graded_iso.refl [refl] [constructor] : M ≃gm M := graded_iso.mk equiv.rfl (λi, isomorphism.rfl) variable {M} definition graded_iso.rfl [refl] [constructor] : M ≃gm M := graded_iso.refl M definition graded_iso.symm [symm] [constructor] (φ : M₁ ≃gm M₂) : M₂ ≃gm M₁ := graded_iso.mk_out (deg φ)⁻¹ᵉ (λi, (isomorphism_of_graded_iso φ i)⁻¹ˡᵐ) definition graded_iso.trans [trans] [constructor] (φ : M₁ ≃gm M₂) (ψ : M₂ ≃gm M₃) : M₁ ≃gm M₃ := graded_iso.mk (deg φ ⬝e deg ψ) (λi, isomorphism_of_graded_iso φ i ⬝lm isomorphism_of_graded_iso ψ (deg φ i)) definition graded_iso.eq_trans [trans] [constructor] {M₁ M₂ M₃ : graded_module R I} (φ : M₁ ~ M₂) (ψ : M₂ ≃gm M₃) : M₁ ≃gm M₃ := proof graded_iso.trans (graded_iso_of_eq φ) ψ qed definition graded_iso.trans_eq [trans] [constructor] {M₁ M₂ M₃ : graded_module R I} (φ : M₁ ≃gm M₂) (ψ : M₂ ~ M₃) : M₁ ≃gm M₃ := graded_iso.trans φ (graded_iso_of_eq ψ) postfix `⁻¹ᵉᵍᵐ`:(max + 1) := graded_iso.symm infixl ` ⬝egm `:75 := graded_iso.trans infixl ` ⬝egmp `:75 := graded_iso.trans_eq infixl ` ⬝epgm `:75 := graded_iso.eq_trans definition graded_hom_of_eq [constructor] {M₁ M₂ : graded_module R I} (p : M₁ ~ M₂) : M₁ →gm M₂ := proof graded_iso_of_eq p qed definition fooff {I : Set} (P : I → Type) {i j : I} (M : P i) (N : P j) := unit notation M ` ==[`:50 P:0 `] `:0 N:50 := fooff P M N definition graded_homotopy (f g : M₁ →gm M₂) : Type := Π⦃i j k⦄ (p : deg f i = j) (q : deg g i = k) (m : M₁ i), f ↘ p m ==[λi, M₂ i] g ↘ q m -- mk' :: (hd : deg f ~ deg g) -- (hfn : Π⦃i j : I⦄ (pf : deg f i = j) (pg : deg g i = j), f ↘ pf ~ g ↘ pg) infix ` ~gm `:50 := graded_homotopy -- definition graded_homotopy.mk2 (hd : deg f ~ deg g) (hfn : Πi m, f i m =[hd i] g i m) : f ~gm g := -- graded_homotopy.mk' hd -- begin -- intro i j pf pg m, induction (is_set.elim (hd i ⬝ pg) pf), induction pg, esimp, -- exact graded_hom_eq_transport f (hd i) m ⬝ tr_eq_of_pathover (hfn i m), -- end definition graded_homotopy.mk (h : Πi m, f i m ==[λi, M₂ i] g i m) : f ~gm g := begin intros i j k p q m, induction q, induction p, constructor --exact h i m end -- definition graded_hom_compose_out {d₁ d₂ : I ≃ I} (f₂ : Πi, M₂ i →lm M₃ (d₂ i)) -- (f₁ : Πi, M₁ (d₁⁻¹ i) →lm M₂ i) : graded_hom.mk d₂ f₂ ∘gm graded_hom.mk_out d₁ f₁ ~gm -- graded_hom.mk_out_in d₁⁻¹ᵉ d₂ _ := -- _ -- definition graded_hom_out_in_compose_out {d₁ d₂ d₃ : I ≃ I} (f₂ : Πi, M₂ (d₂ i) →lm M₃ (d₃ i)) -- (f₁ : Πi, M₁ (d₁⁻¹ i) →lm M₂ i) : graded_hom.mk_out_in d₂ d₃ f₂ ∘gm graded_hom.mk_out d₁ f₁ ~gm -- graded_hom.mk_out_in (d₂ ⬝e d₁⁻¹ᵉ) d₃ (λi, f₂ i ∘lm (f₁ (d₂ i))) := -- begin -- apply graded_homotopy.mk, intro i m, exact sorry -- end -- definition graded_hom_out_in_rfl {d₁ d₂ : I ≃ I} (f : Πi, M₁ i →lm M₂ (d₂ i)) -- (p : Πi, d₁ i = i) : -- graded_hom.mk_out_in d₁ d₂ (λi, sorry) ~gm graded_hom.mk d₂ f := -- begin -- apply graded_homotopy.mk, intro i m, exact sorry -- end -- definition graded_homotopy.trans (h₁ : f ~gm g) (h₂ : g ~gm h) : f ~gm h := -- begin -- exact sorry -- end -- postfix `⁻¹ᵍᵐ`:(max + 1) := graded_iso.symm --infixl ` ⬝gm `:75 := graded_homotopy.trans -- infixl ` ⬝gmp `:75 := graded_iso.trans_eq -- infixl ` ⬝pgm `:75 := graded_iso.eq_trans -- definition graded_homotopy_of_deg (d : I ≃ I) (f g : graded_hom_of_deg d M₁ M₂) : Type := -- Π⦃i j : I⦄ (p : d i = j), f p ~ g p -- notation f ` ~[`:50 d:0 `] `:0 g:50 := graded_homotopy_of_deg d f g -- variables {d : I ≃ I} {f₁ f₂ : graded_hom_of_deg d M₁ M₂} -- definition graded_homotopy_of_deg.mk [constructor] (h : Πi, f₁ (idpath (d i)) ~ f₂ (idpath (d i))) : -- f₁ ~[d] f₂ := -- begin -- intro i j p, induction p, exact h i -- end -- definition graded_homotopy.mk_out [constructor] {M₁ M₂ : graded_module R I} (d : I ≃ I) -- (fn : Πi, M₁ (d⁻¹ i) →lm M₂ i) : M₁ →gm M₂ := -- graded_hom.mk' d (λi j p, fn j ∘lm homomorphism_of_eq (ap M₁ (eq_inv_of_eq p))) -- definition is_gconstant (f : M₁ →gm M₂) : Type := -- f↘ ~[deg f] gmd0 definition compose_constant (f' : M₂ →gm M₃) (f : M₁ →gm M₂) : Type := Π⦃i j k : I⦄ (p : deg f i = j) (q : deg f' j = k) (m : M₁ i), f' ↘ q (f ↘ p m) = 0 definition compose_constant.mk (h : Πi m, f' (deg f i) (f i m) = 0) : compose_constant f' f := by intros; induction p; induction q; exact h i m definition compose_constant.elim (h : compose_constant f' f) (i : I) (m : M₁ i) : f' (deg f i) (f i m) = 0 := h idp idp m definition is_gconstant (f : M₁ →gm M₂) : Type := Π⦃i j : I⦄ (p : deg f i = j) (m : M₁ i), f ↘ p m = 0 definition is_gconstant.mk (h : Πi m, f i m = 0) : is_gconstant f := by intros; induction p; exact h i m definition is_gconstant.elim (h : is_gconstant f) (i : I) (m : M₁ i) : f i m = 0 := h idp m /- direct sum of graded R-modules -/ variables {J : Set} (N : graded_module R J) definition dirsum' : AddAbGroup := group.dirsum (λj, AddAbGroup_of_LeftModule (N j)) variable {N} definition dirsum_smul [constructor] (r : R) : dirsum' N →a dirsum' N := dirsum_functor (λi, smul_homomorphism (N i) r) definition dirsum_smul_right_distrib (r s : R) (n : dirsum' N) : dirsum_smul (r + s) n = dirsum_smul r n + dirsum_smul s n := begin refine dirsum_functor_homotopy _ n ⬝ !dirsum_functor_add⁻¹, intro i ni, exact to_smul_right_distrib r s ni end definition dirsum_mul_smul' (r s : R) (n : dirsum' N) : dirsum_smul (r * s) n = (dirsum_smul r ∘a dirsum_smul s) n := begin refine dirsum_functor_homotopy _ n ⬝ (dirsum_functor_compose _ _ n)⁻¹ᵖ, intro i ni, exact to_mul_smul r s ni end definition dirsum_mul_smul (r s : R) (n : dirsum' N) : dirsum_smul (r * s) n = dirsum_smul r (dirsum_smul s n) := proof dirsum_mul_smul' r s n qed definition dirsum_one_smul (n : dirsum' N) : dirsum_smul 1 n = n := begin refine dirsum_functor_homotopy _ n ⬝ !dirsum_functor_gid, intro i ni, exact to_one_smul ni end definition dirsum : LeftModule R := LeftModule_of_AddAbGroup (dirsum' N) (λr n, dirsum_smul r n) (λr, homomorphism.addstruct (dirsum_smul r)) dirsum_smul_right_distrib dirsum_mul_smul dirsum_one_smul /- graded variants of left-module constructions -/ definition graded_submodule [constructor] (S : Πi, submodule_rel (M i)) : graded_module R I := λi, submodule (S i) definition graded_submodule_incl [constructor] (S : Πi, submodule_rel (M i)) : graded_submodule S →gm M := graded_hom.mk erfl (λi, submodule_incl (S i)) definition graded_hom_lift [constructor] {S : Πi, submodule_rel (M₂ i)} (φ : M₁ →gm M₂) (h : Π(i : I) (m : M₁ i), S (deg φ i) (φ i m)) : M₁ →gm graded_submodule S := graded_hom.mk (deg φ) (λi, hom_lift (φ i) (h i)) definition graded_submodule_functor [constructor] {S : Πi, submodule_rel (M₁ i)} {T : Πi, submodule_rel (M₂ i)} (φ : M₁ →gm M₂) (h : Π(i : I) (m : M₁ i), S i m → T (deg φ i) (φ i m)) : graded_submodule S →gm graded_submodule T := graded_hom.mk (deg φ) (λi, submodule_functor (φ i) (h i)) definition graded_image (f : M₁ →gm M₂) : graded_module R I := λi, image_module (f ← i) lemma graded_image_lift_lemma (f : M₁ →gm M₂) {i j: I} (p : deg f i = j) (m : M₁ i) : image (f ← j) (f ↘ p m) := graded_hom_change_image p (right_inv (deg f) j) (image.mk m idp) definition graded_image_lift [constructor] (f : M₁ →gm M₂) : M₁ →gm graded_image f := graded_hom.mk' (deg f) (λi j p, hom_lift (f ↘ p) (graded_image_lift_lemma f p)) definition graded_image_lift_destruct (f : M₁ →gm M₂) {i : I} (m : M₁ ((deg f)⁻¹ᵉ i)) : graded_image_lift f ← i m = image_lift (f ← i) m := subtype_eq idp definition graded_image.rec {f : M₁ →gm M₂} {i : I} {P : graded_image f (deg f i) → Type} [h : Πx, is_prop (P x)] (H : Πm, P (graded_image_lift f i m)) : Πm, P m := begin assert H₂ : Πi' (p : deg f i' = deg f i) (m : M₁ i'), P ⟨f ↘ p m, graded_hom_change_image p _ (image.mk m idp)⟩, { refine eq.rec_equiv_symm (deg f) _, intro m, refine transport P _ (H m), apply subtype_eq, reflexivity }, refine @total_image.rec _ _ _ _ h _, intro m, refine transport P _ (H₂ _ (right_inv (deg f) (deg f i)) m), apply subtype_eq, reflexivity end definition image_graded_image_lift {f : M₁ →gm M₂} {i j : I} (p : deg f i = j) (m : graded_image f j) (h : image (f ↘ p) m.1) : image (graded_image_lift f ↘ p) m := begin induction p, revert m h, refine total_image.rec _, intro m h, induction h with n q, refine image.mk n (subtype_eq q) end lemma is_surjective_graded_image_lift ⦃x y⦄ (f : M₁ →gm M₂) (p : deg f x = y) : is_surjective (graded_image_lift f ↘ p) := begin intro m, apply image_graded_image_lift, exact graded_hom_change_image (right_inv (deg f) y) _ m.2 end definition graded_image_elim [constructor] {f : M₁ →gm M₂} (g : M₁ →gm M₃) (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : graded_image f →gm M₃ := begin apply graded_hom.mk_out_in (deg f) (deg g), intro i, apply image_elim (g ↘ (ap (deg g) (to_left_inv (deg f) i))), exact abstract begin intro m p, refine graded_hom_eq_zero m (h _), exact graded_hom_eq_zero m p end end end lemma graded_image_elim_destruct {f : M₁ →gm M₂} {g : M₁ →gm M₃} (h : Π⦃i m⦄, f i m = 0 → g i m = 0) {i j k : I} (p' : deg f i = j) (p : deg g ((deg f)⁻¹ᵉ j) = k) (q : deg g i = k) (r : ap (deg g) (to_left_inv (deg f) i) ⬝ q = ap ((deg f)⁻¹ᵉ ⬝e deg g) p' ⬝ p) (m : M₁ i) : graded_image_elim g h ↘ p (graded_image_lift f ↘ p' m) = g ↘ q m := begin revert i j p' k p q r m, refine equiv_rect (deg f ⬝e (deg f)⁻¹ᵉ) _ _, intro i, refine eq.rec_grading _ (deg f) (right_inv (deg f) (deg f i)) _, intro k p q r m, assert r' : q = p, { refine cancel_left _ (r ⬝ whisker_right _ _), refine !ap_compose ⬝ ap02 (deg g) _, exact !adj_inv⁻¹ }, induction r', clear r, revert k q m, refine eq.rec_to (ap (deg g) (to_left_inv (deg f) i)) _, intro m, refine graded_hom_mk_out_in_destruct (deg f) (deg g) _ (graded_image_lift f ← (deg f i) m) ⬝ _, refine ap (image_elim _ _) !graded_image_lift_destruct ⬝ _, reflexivity end /- alternative (easier) definition of graded_image with "wrong" grading -/ -- definition graded_image' (f : M₁ →gm M₂) : graded_module R I := -- λi, image_module (f i) -- definition graded_image'_lift [constructor] (f : M₁ →gm M₂) : M₁ →gm graded_image' f := -- graded_hom.mk erfl (λi, image_lift (f i)) -- definition graded_image'_elim [constructor] {f : M₁ →gm M₂} (g : M₁ →gm M₃) -- (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : -- graded_image' f →gm M₃ := -- begin -- apply graded_hom.mk (deg g), -- intro i, -- apply image_elim (g i), -- intro m p, exact h p -- end -- theorem graded_image'_elim_compute {f : M₁ →gm M₂} {g : M₁ →gm M₃} -- (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : -- graded_image'_elim g h ∘gm graded_image'_lift f ~gm g := -- begin -- apply graded_homotopy.mk, -- intro i m, exact sorry --reflexivity -- end -- theorem graded_image_elim_compute {f : M₁ →gm M₂} {g : M₁ →gm M₃} -- (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : -- graded_image_elim g h ∘gm graded_image_lift f ~gm g := -- begin -- refine _ ⬝gm graded_image'_elim_compute h, -- esimp, exact sorry -- -- refine graded_hom_out_in_compose_out _ _ ⬝gm _, exact sorry -- -- -- apply graded_homotopy.mk, -- -- -- intro i m, -- end -- variables {α β : I ≃ I} -- definition gen_image (f : M₁ →gm M₂) (p : Πi, deg f (α i) = β i) : graded_module R I := -- λi, image_module (f ↘ (p i)) -- definition gen_image_lift [constructor] (f : M₁ →gm M₂) (p : Πi, deg f (α i) = β i) : M₁ →gm gen_image f p := -- graded_hom.mk_out α⁻¹ᵉ (λi, image_lift (f ↘ (p i))) -- definition gen_image_elim [constructor] {f : M₁ →gm M₂} (p : Πi, deg f (α i) = β i) (g : M₁ →gm M₃) -- (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : -- gen_image f p →gm M₃ := -- begin -- apply graded_hom.mk_out_in α⁻¹ᵉ (deg g), -- intro i, -- apply image_elim (g ↘ (ap (deg g) (to_right_inv α i))), -- intro m p, -- refine graded_hom_eq_zero m (h _), -- exact graded_hom_eq_zero m p -- end -- theorem gen_image_elim_compute {f : M₁ →gm M₂} {p : deg f ∘ α ~ β} {g : M₁ →gm M₃} -- (h : Π⦃i m⦄, f i m = 0 → g i m = 0) : -- gen_image_elim p g h ∘gm gen_image_lift f p ~gm g := -- begin -- -- induction β with β βe, esimp at *, induction p using homotopy.rec_on_idp, -- assert q : β ⬝e (deg f)⁻¹ᵉ = α, -- { apply equiv_eq, intro i, apply inv_eq_of_eq, exact (p i)⁻¹ }, -- induction q, -- -- unfold [gen_image_elim, gen_image_lift], -- -- induction (is_prop.elim (λi, to_right_inv (deg f) (β i)) p), -- -- apply graded_homotopy.mk, -- -- intro i m, reflexivity -- exact sorry -- end definition graded_kernel (f : M₁ →gm M₂) : graded_module R I := λi, kernel_module (f i) definition graded_quotient (S : Πi, submodule_rel (M i)) : graded_module R I := λi, quotient_module (S i) definition graded_quotient_map [constructor] (S : Πi, submodule_rel (M i)) : M →gm graded_quotient S := graded_hom.mk erfl (λi, quotient_map (S i)) definition graded_quotient_elim [constructor] {S : Πi, submodule_rel (M i)} (φ : M →gm M₂) (H : Πi ⦃m⦄, S i m → φ i m = 0) : graded_quotient S →gm M₂ := graded_hom.mk (deg φ) (λi, quotient_elim (φ i) (H i)) definition graded_homology (g : M₂ →gm M₃) (f : M₁ →gm M₂) : graded_module R I := graded_quotient (λi, submodule_rel_submodule (kernel_rel (g i)) (image_rel (f ← i))) -- the two reasonable definitions of graded_homology are definitionally equal example (g : M₂ →gm M₃) (f : M₁ →gm M₂) : (λi, homology (g i) (f ← i)) = graded_quotient (λi, submodule_rel_submodule (kernel_rel (g i)) (image_rel (f ← i))) := idp definition graded_homology.mk (g : M₂ →gm M₃) (f : M₁ →gm M₂) {i : I} (m : M₂ i) (h : g i m = 0) : graded_homology g f i := homology.mk _ m h definition graded_homology_intro [constructor] (g : M₂ →gm M₃) (f : M₁ →gm M₂) : graded_kernel g →gm graded_homology g f := graded_quotient_map _ definition graded_homology_elim {g : M₂ →gm M₃} {f : M₁ →gm M₂} (h : M₂ →gm M) (H : compose_constant h f) : graded_homology g f →gm M := graded_hom.mk (deg h) (λi, homology_elim (h i) (H _ _)) open trunc definition image_of_graded_homology_intro_eq_zero {g : M₂ →gm M₃} {f : M₁ →gm M₂} ⦃i j : I⦄ (p : deg f i = j) (m : graded_kernel g j) (H : graded_homology_intro g f j m = 0) : image (f ↘ p) m.1 := begin induction p, exact graded_hom_change_image _ _ (rel_of_quotient_map_eq_zero m H) end definition is_exact_gmod (f : M₁ →gm M₂) (f' : M₂ →gm M₃) : Type := Π⦃i j k⦄ (p : deg f i = j) (q : deg f' j = k), is_exact_mod (f ↘ p) (f' ↘ q) definition is_exact_gmod.mk {f : M₁ →gm M₂} {f' : M₂ →gm M₃} (h₁ : Π⦃i⦄ (m : M₁ i), f' (deg f i) (f i m) = 0) (h₂ : Π⦃i⦄ (m : M₂ (deg f i)), f' (deg f i) m = 0 → image (f i) m) : is_exact_gmod f f' := begin intro i j k p q; induction p; induction q; split, apply h₁, apply h₂ end definition gmod_im_in_ker (h : is_exact_gmod f f') : compose_constant f' f := λi j k p q, is_exact.im_in_ker (h p q) definition gmod_ker_in_im (h : is_exact_gmod f f') ⦃i : I⦄ (m : M₂ i) (p : f' i m = 0) : image (f ← i) m := is_exact.ker_in_im (h (right_inv (deg f) i) idp) m p end left_module