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
fdc348b47a305c00bd8f72fce472d6cb1805c9a8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/uniform_space/cauchy.lean
3cde6e975a9d1a4b02e58686e56f33ef16b91de4
[ "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
30,349
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 topology.uniform_space.basic import topology.bases import data.set.intervals /-! # Theory of Cauchy filters in uniform spaces. Complete uniform spaces. Totally bounded subsets. -/ universes u v open filter topological_space set classical uniform_space open_locale classical uniformity topological_space filter variables {α : Type u} {β : Type v} [uniform_space α] /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := ne_bot f ∧ f ×ᶠ f ≤ (𝓤 α) /-- A set `s` is called *complete*, if any Cauchy filter `f` such that `s ∈ f` has a limit in `s` (formally, it satisfies `f ≤ 𝓝 x` for some `x ∈ s`). -/ def is_complete (s : set α) := ∀f, cauchy f → f ≤ 𝓟 s → ∃x∈s, f ≤ 𝓝 x lemma filter.has_basis.cauchy_iff {p : β → Prop} {s : β → set (α × α)} (h : (𝓤 α).has_basis p s) {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ i, p i → ∃ t ∈ f, ∀ x y ∈ t, (x, y) ∈ s i)) := and_congr iff.rfl $ (f.basis_sets.prod_self.le_basis_iff h).trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_iff' {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, ∀ x y ∈ t, (x, y) ∈ s)) := (𝓤 α).basis_sets.cauchy_iff lemma cauchy_iff {f : filter α} : cauchy f ↔ (ne_bot f ∧ (∀ s ∈ 𝓤 α, ∃t∈f, (set.prod t t) ⊆ s)) := (𝓤 α).basis_sets.cauchy_iff.trans $ by simp only [subset_def, prod.forall, mem_prod_eq, and_imp, id] lemma cauchy_map_iff {l : filter β} {f : β → α} : cauchy (l.map f) ↔ (ne_bot l ∧ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α)) := by rw [cauchy, map_ne_bot_iff, prod_map_map_eq, tendsto] lemma cauchy_map_iff' {l : filter β} [hl : ne_bot l] {f : β → α} : cauchy (l.map f) ↔ tendsto (λp:β×β, (f p.1, f p.2)) (l ×ᶠ l) (𝓤 α) := cauchy_map_iff.trans $ and_iff_right hl lemma cauchy.mono {f g : filter α} [hg : ne_bot g] (h_c : cauchy f) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy.mono' {f g : filter α} (h_c : cauchy f) (hg : ne_bot g) (h_le : g ≤ f) : cauchy g := h_c.mono h_le lemma cauchy_nhds {a : α} : cauchy (𝓝 a) := ⟨nhds_ne_bot, calc 𝓝 a ×ᶠ 𝓝 a = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ (𝓤 α).lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ 𝓤 α : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_nhds.mono (pure_le_nhds a) lemma filter.tendsto.cauchy_map {l : filter β} [ne_bot l] {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : cauchy (map f l) := cauchy_nhds.mono h lemma cauchy.prod [uniform_space β] {f : filter α} {g : filter β} (hf : cauchy f) (hg : cauchy g) : cauchy (f ×ᶠ g) := begin refine ⟨hf.1.prod hg.1, _⟩, simp only [uniformity_prod, le_inf_iff, ← map_le_iff_le_comap, ← prod_map_map_eq], exact ⟨le_trans (prod_mono tendsto_fst tendsto_fst) hf.2, le_trans (prod_mono tendsto_snd tendsto_snd) hg.2⟩ end /-- The common part of the proofs of `le_nhds_of_cauchy_adhp` and `sequentially_complete.le_nhds_of_seq_tendsto_nhds`: if for any entourage `s` one can choose a set `t ∈ f` of diameter `s` such that it contains a point `y` with `(x, y) ∈ s`, then `f` converges to `x`. -/ lemma le_nhds_of_cauchy_adhp_aux {f : filter α} {x : α} (adhs : ∀ s ∈ 𝓤 α, ∃ t ∈ f, (set.prod t t ⊆ s) ∧ ∃ y, (x, y) ∈ s ∧ y ∈ t) : f ≤ 𝓝 x := begin -- Consider a neighborhood `s` of `x` assume s hs, -- Take an entourage twice smaller than `s` rcases comp_mem_uniformity_sets (mem_nhds_uniformity_iff_right.1 hs) with ⟨U, U_mem, hU⟩, -- Take a set `t ∈ f`, `t × t ⊆ U`, and a point `y ∈ t` such that `(x, y) ∈ U` rcases adhs U U_mem with ⟨t, t_mem, ht, y, hxy, hy⟩, apply mem_of_superset t_mem, -- Given a point `z ∈ t`, we have `(x, y) ∈ U` and `(y, z) ∈ t × t ⊆ U`, hence `z ∈ s` exact (λ z hz, hU (prod_mk_mem_comp_rel hxy (ht $ mk_mem_prod hy hz)) rfl) end /-- If `x` is an adherent (cluster) point for a Cauchy filter `f`, then it is a limit point for `f`. -/ lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : cluster_pt x f) : f ≤ 𝓝 x := le_nhds_of_cauchy_adhp_aux begin assume s hs, obtain ⟨t, t_mem, ht⟩ : ∃ t ∈ f, set.prod t t ⊆ s, from (cauchy_iff.1 hf).2 s hs, use [t, t_mem, ht], exact (forall_mem_nonempty_iff_ne_bot.2 adhs _ (inter_mem_inf (mem_nhds_left x hs) t_mem )) end lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ 𝓝 x ↔ cluster_pt x f := ⟨assume h, cluster_pt.of_le_nhds' h hf.1, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy.map [uniform_space β] {f : filter α} {m : α → β} (hf : cauchy f) (hm : uniform_continuous m) : cauchy (map m f) := ⟨hf.1.map _, calc map m f ×ᶠ map m f = map (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) (𝓤 α) : map_mono hf.right ... ≤ 𝓤 β : hm⟩ lemma cauchy.comap [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) [ne_bot (comap m f)] : cauchy (comap m f) := ⟨‹_›, calc comap m f ×ᶠ comap m f = comap (λp:α×α, (m p.1, m p.2)) (f ×ᶠ f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) : comap_mono hf.right ... ≤ 𝓤 α : hm⟩ lemma cauchy.comap' [uniform_space β] {f : filter β} {m : α → β} (hf : cauchy f) (hm : comap (λp:α×α, (m p.1, m p.2)) (𝓤 β) ≤ 𝓤 α) (hb : ne_bot (comap m f)) : cauchy (comap m f) := hf.comap hm /-- Cauchy sequences. Usually defined on ℕ, but often it is also useful to say that a function defined on ℝ is Cauchy at +∞ to deduce convergence. Therefore, we define it in a type class that is general enough to cover both ℕ and ℝ, which are the main motivating examples. -/ def cauchy_seq [semilattice_sup β] (u : β → α) := cauchy (at_top.map u) lemma cauchy_seq.tendsto_uniformity [semilattice_sup β] {u : β → α} (h : cauchy_seq u) : tendsto (prod.map u u) at_top (𝓤 α) := by simpa only [tendsto, prod_map_map_eq', prod_at_top_at_top_eq] using h.right lemma cauchy_seq.nonempty [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) : nonempty β := @nonempty_of_ne_bot _ _ $ (map_ne_bot_iff _).1 hu.1 lemma cauchy_seq.mem_entourage {β : Type*} [semilattice_sup β] {u : β → α} (h : cauchy_seq u) {V : set (α × α)} (hV : V ∈ 𝓤 α) : ∃ k₀, ∀ i j, k₀ ≤ i → k₀ ≤ j → (u i, u j) ∈ V := begin haveI := h.nonempty, have := h.tendsto_uniformity, rw ← prod_at_top_at_top_eq at this, simpa [maps_to] using at_top_basis.prod_self.tendsto_left_iff.1 this V hV end lemma filter.tendsto.cauchy_seq [semilattice_sup β] [nonempty β] {f : β → α} {x} (hx : tendsto f at_top (𝓝 x)) : cauchy_seq f := hx.cauchy_map lemma cauchy_seq_const (x : α) : cauchy_seq (λ n : ℕ, x) := tendsto_const_nhds.cauchy_seq lemma cauchy_seq_iff_tendsto [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (prod.map u u) at_top (𝓤 α) := cauchy_map_iff'.trans $ by simp only [prod_at_top_at_top_eq, prod.map_def] lemma cauchy_seq.comp_tendsto {γ} [semilattice_sup β] [semilattice_sup γ] [nonempty γ] {f : β → α} (hf : cauchy_seq f) {g : γ → β} (hg : tendsto g at_top at_top) : cauchy_seq (f ∘ g) := cauchy_seq_iff_tendsto.2 $ hf.tendsto_uniformity.comp (hg.prod_at_top hg) lemma cauchy_seq.subseq_subseq_mem {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} (hu : cauchy_seq u) {f g : ℕ → ℕ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, ((u ∘ f ∘ φ) n, (u ∘ g ∘ φ) n) ∈ V n := begin rw cauchy_seq_iff_tendsto at hu, exact ((hu.comp $ hf.prod_at_top hg).comp tendsto_at_top_diagonal).subseq_mem hV, end lemma cauchy_seq_iff' {u : ℕ → α} : cauchy_seq u ↔ ∀ V ∈ 𝓤 α, ∀ᶠ k in at_top, k ∈ (prod.map u u) ⁻¹' V := by simpa only [cauchy_seq_iff_tendsto] lemma cauchy_seq_iff {u : ℕ → α} : cauchy_seq u ↔ ∀ V ∈ 𝓤 α, ∃ N, ∀ k ≥ N, ∀ l ≥ N, (u k, u l) ∈ V := by simp [cauchy_seq_iff', filter.eventually_at_top_prod_self', prod_map] lemma cauchy_seq.prod_map {γ δ} [uniform_space β] [semilattice_sup γ] [semilattice_sup δ] {u : γ → α} {v : δ → β} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (prod.map u v) := by simpa only [cauchy_seq, prod_map_map_eq', prod_at_top_at_top_eq] using hu.prod hv lemma cauchy_seq.prod {γ} [uniform_space β] [semilattice_sup γ] {u : γ → α} {v : γ → β} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (λ x, (u x, v x)) := begin haveI := hu.nonempty, exact (hu.prod hv).mono (tendsto.prod_mk le_rfl le_rfl) end lemma uniform_continuous.comp_cauchy_seq {γ} [uniform_space β] [semilattice_sup γ] {f : α → β} (hf : uniform_continuous f) {u : γ → α} (hu : cauchy_seq u) : cauchy_seq (f ∘ u) := hu.map hf lemma cauchy_seq.subseq_mem {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} (hu : cauchy_seq u) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, (u $ φ (n + 1), u $ φ n) ∈ V n := begin have : ∀ n, ∃ N, ∀ k ≥ N, ∀ l ≥ k, (u l, u k) ∈ V n, { intro n, rw [cauchy_seq_iff] at hu, rcases hu _ (hV n) with ⟨N, H⟩, exact ⟨N, λ k hk l hl, H _ (le_trans hk hl) _ hk ⟩ }, obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∀ l ≥ φ n, (u l, u $ φ n) ∈ V n⟩ := extraction_forall_of_eventually' this, exact ⟨φ, φ_extr, λ n, hφ _ _ (φ_extr $ lt_add_one n).le⟩, end lemma filter.tendsto.subseq_mem_entourage {V : ℕ → set (α × α)} (hV : ∀ n, V n ∈ 𝓤 α) {u : ℕ → α} {a : α} (hu : tendsto u at_top (𝓝 a)) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ (u (φ 0), a) ∈ V 0 ∧ ∀ n, (u $ φ (n + 1), u $ φ n) ∈ V (n + 1) := begin rcases mem_at_top_sets.1 (hu (ball_mem_nhds a (symm_le_uniformity $ hV 0))) with ⟨n, hn⟩, rcases (hu.comp (tendsto_add_at_top_nat n)).cauchy_seq.subseq_mem (λ n, hV (n + 1)) with ⟨φ, φ_mono, hφV⟩, exact ⟨λ k, φ k + n, φ_mono.add_const _, hn _ le_add_self, hφV⟩ end /-- If a Cauchy sequence has a convergent subsequence, then it converges. -/ lemma tendsto_nhds_of_cauchy_seq_of_subseq [semilattice_sup β] {u : β → α} (hu : cauchy_seq u) {ι : Type*} {f : ι → β} {p : filter ι} [ne_bot p] (hf : tendsto f p at_top) {a : α} (ha : tendsto (u ∘ f) p (𝓝 a)) : tendsto u at_top (𝓝 a) := le_nhds_of_cauchy_adhp hu (map_cluster_pt_of_comp hf ha) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma filter.has_basis.cauchy_seq_iff {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (h : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀m n≥N, (u m, u n) ∈ s i := begin rw [cauchy_seq_iff_tendsto, ← prod_at_top_at_top_eq], refine (at_top_basis.prod_self.tendsto_iff h).trans _, simp only [exists_prop, true_and, maps_to, preimage, subset_def, prod.forall, mem_prod_eq, mem_set_of_eq, mem_Ici, and_imp, prod.map] end lemma filter.has_basis.cauchy_seq_iff' {γ} [nonempty β] [semilattice_sup β] {u : β → α} {p : γ → Prop} {s : γ → set (α × α)} (H : (𝓤 α).has_basis p s) : cauchy_seq u ↔ ∀ i, p i → ∃N, ∀n≥N, (u n, u N) ∈ s i := begin refine H.cauchy_seq_iff.trans ⟨λ h i hi, _, λ h i hi, _⟩, { exact (h i hi).imp (λ N hN n hn, hN n N hn (le_refl N)) }, { rcases comp_symm_of_uniformity (H.mem_of_mem hi) with ⟨t, ht, ht', hts⟩, rcases H.mem_iff.1 ht with ⟨j, hj, hjt⟩, refine (h j hj).imp (λ N hN m n hm hn, hts ⟨u N, hjt _, ht' $ hjt _⟩), { exact hN m hm }, { exact hN n hn } } end lemma cauchy_seq_of_controlled [semilattice_sup β] [nonempty β] (U : β → set (α × α)) (hU : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) {f : β → α} (hf : ∀ {N m n : β}, N ≤ m → N ≤ n → (f m, f n) ∈ U N) : cauchy_seq f := cauchy_seq_iff_tendsto.2 begin assume s hs, rw [mem_map, mem_at_top_sets], cases hU s hs with N hN, refine ⟨(N, N), λ mn hmn, _⟩, cases mn with m n, exact hN (hf hmn.1 hmn.2) end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ 𝓝 x) lemma complete_univ {α : Type u} [uniform_space α] [complete_space α] : is_complete (univ : set α) := begin assume f hf _, rcases complete_space.complete hf with ⟨x, hx⟩, exact ⟨x, mem_univ x, hx⟩ end instance complete_space.prod [uniform_space β] [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ hf.map uniform_continuous_fst in let ⟨x2, hx2⟩ := complete_space.complete $ hf.map uniform_continuous_snd in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem H1 H2)⟩ } /--If `univ` is complete, the space is a complete space -/ lemma complete_space_of_is_complete_univ (h : is_complete (univ : set α)) : complete_space α := ⟨λ f hf, let ⟨x, _, hx⟩ := h f hf ((@principal_univ α).symm ▸ le_top) in ⟨x, hx⟩⟩ lemma complete_space_iff_is_complete_univ : complete_space α ↔ is_complete (univ : set α) := ⟨@complete_univ α _, complete_space_of_is_complete_univ⟩ lemma cauchy_iff_exists_le_nhds [complete_space α] {l : filter α} [ne_bot l] : cauchy l ↔ (∃x, l ≤ 𝓝 x) := ⟨complete_space.complete, assume ⟨x, hx⟩, cauchy_nhds.mono hx⟩ lemma cauchy_map_iff_exists_tendsto [complete_space α] {l : filter β} {f : β → α} [ne_bot l] : cauchy (l.map f) ↔ (∃x, tendsto f l (𝓝 x)) := cauchy_iff_exists_le_nhds /-- A Cauchy sequence in a complete space converges -/ theorem cauchy_seq_tendsto_of_complete [semilattice_sup β] [complete_space α] {u : β → α} (H : cauchy_seq u) : ∃x, tendsto u at_top (𝓝 x) := complete_space.complete H /-- If `K` is a complete subset, then any cauchy sequence in `K` converges to a point in `K` -/ lemma cauchy_seq_tendsto_of_is_complete [semilattice_sup β] {K : set α} (h₁ : is_complete K) {u : β → α} (h₂ : ∀ n, u n ∈ K) (h₃ : cauchy_seq u) : ∃ v ∈ K, tendsto u at_top (𝓝 v) := h₁ _ h₃ $ le_principal_iff.2 $ mem_map_iff_exists_image.2 ⟨univ, univ_mem, by { simp only [image_univ], rintros _ ⟨n, rfl⟩, exact h₂ n }⟩ theorem cauchy.le_nhds_Lim [complete_space α] [nonempty α] {f : filter α} (hf : cauchy f) : f ≤ 𝓝 (Lim f) := le_nhds_Lim (complete_space.complete hf) theorem cauchy_seq.tendsto_lim [semilattice_sup β] [complete_space α] [nonempty α] {u : β → α} (h : cauchy_seq u) : tendsto u at_top (𝓝 $ lim at_top u) := h.le_nhds_Lim lemma is_closed.is_complete [complete_space α] {s : set α} (h : is_closed s) : is_complete s := λ f cf fs, let ⟨x, hx⟩ := complete_space.complete cf in ⟨x, is_closed_iff_cluster_pt.mp h x (cf.left.mono (le_inf hx fs)), hx⟩ /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ 𝓤 α, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ 𝓤 α, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := k ∩ {y | ∃ x ∈ s, (x, y) ∈ r}, choose hk f hfs hfr using λ x : u, x.coe_prop, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 hfs }, { haveI : fintype u := (fk.inter_of_left _).fintype, exact finite_range f }, { intros x xs, obtain ⟨y, hy, xy⟩ : ∃ y ∈ k, (x, y) ∈ r, from mem_bUnion_iff.1 (ks xs), rw [bUnion_range, mem_Union], set z : ↥u := ⟨y, hy, ⟨x, xs, xy⟩⟩, exact ⟨z, rd $ mem_comp_rel.2 ⟨y, xy, rs (hfr z)⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_of_forall_symm {s : set α} (h : ∀ V ∈ 𝓤 α, symmetric_rel V → ∃ t : set α, finite t ∧ s ⊆ ⋃ y ∈ t, ball y V) : totally_bounded s := begin intros V V_in, rcases h _ (symmetrize_mem_uniformity V_in) (symmetric_symmetrize_rel V) with ⟨t, tfin, h⟩, refine ⟨t, tfin, subset.trans h _⟩, mono, intros x x_in z z_in, exact z_in.right end lemma totally_bounded_subset {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_empty : totally_bounded (∅ : set α) := λ d hd, ⟨∅, finite_empty, empty_subset _⟩ /-- The closure of a totally bounded set is totally bounded. -/ lemma totally_bounded.closure {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : is_closed.closure_eq $ is_closed_bUnion hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ /-- The image of a totally bounded set under a unifromly continuous map is totally bounded. -/ lemma totally_bounded.image [uniform_space β] {f : α → β} {s : set α} (hs : totally_bounded s) (hf : uniform_continuous f) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ 𝓤 α, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, hfc.image f, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp, exact hct x hx end⟩ lemma ultrafilter.cauchy_of_totally_bounded {s : set α} (f : ultrafilter α) (hs : totally_bounded s) (h : ↑f ≤ 𝓟 s) : cauchy (f : filter α) := ⟨f.ne_bot', assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f, from mem_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f, from (ultrafilter.finite_bUnion_mem_iff hi).1 this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, mem_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, ne_bot f → f ≤ 𝓟 s → ∃c ≤ f, cauchy c) := begin split, { introsI H f hf hfs, exact ⟨ultrafilter.of f, ultrafilter.of_le f, (ultrafilter.of f).cauchy_of_totally_bounded H ((ultrafilter.of_le f).trans hfs)⟩ }, { intros H d hd, contrapose! H with hd_cover, set f := ⨅ t : finset α, 𝓟 (s \ ⋃ y ∈ t, {x | (x, y) ∈ d}), have : ne_bot f, { refine infi_ne_bot_of_directed' (directed_of_sup _) _, { intros t₁ t₂ h, exact principal_mono.2 (diff_subset_diff_right $ bUnion_subset_bUnion_left h) }, { intro t, simpa [nonempty_diff] using hd_cover t t.finite_to_set } }, have : f ≤ 𝓟 s, from infi_le_of_le ∅ (by simp), refine ⟨f, ‹_›, ‹_›, λ c hcf hc, _⟩, rcases mem_prod_same_iff.1 (hc.2 hd) with ⟨m, hm, hmd⟩, have : m ∩ s ∈ c, from inter_mem hm (le_principal_iff.mp (hcf.trans ‹_›)), rcases hc.1.nonempty_of_mem this with ⟨y, hym, hys⟩, set ys := ⋃ y' ∈ ({y} : finset α), {x | (x, y') ∈ d}, have : m ⊆ ys, by simpa [ys] using λ x hx, hmd (mk_mem_prod hx hym), have : c ≤ 𝓟 (s \ ys) := hcf.trans (infi_le_of_le {y} le_rfl), refine hc.1.ne (empty_mem_iff_bot.mp _), filter_upwards [le_principal_iff.1 this, hm], refine λ x hx hxm, hx.2 _, simpa [ys] using hmd (mk_mem_prod hxm hym) } end lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → cauchy (f : filter α)) := begin refine ⟨λ hs f, f.cauchy_of_totally_bounded hs, λ H, totally_bounded_iff_filter.2 _⟩, introsI f hf hfs, exact ⟨ultrafilter.of f, ultrafilter.of_le f, H _ ((ultrafilter.of_le f).trans hfs)⟩ end lemma compact_iff_totally_bounded_complete {s : set α} : is_compact s ↔ totally_bounded s ∧ is_complete s := ⟨λ hs, ⟨totally_bounded_iff_ultrafilter.2 (λ f hf, let ⟨x, xs, fx⟩ := is_compact_iff_ultrafilter_le_nhds.1 hs f hf in cauchy_nhds.mono fx), λ f fc fs, let ⟨a, as, fa⟩ := @hs f fc.1 fs in ⟨a, as, le_nhds_of_cauchy_adhp fc fa⟩⟩, λ ⟨ht, hc⟩, is_compact_iff_ultrafilter_le_nhds.2 (λf hf, hc _ (totally_bounded_iff_ultrafilter.1 ht f hf) hf)⟩ lemma is_compact.totally_bounded {s : set α} (h : is_compact s) : totally_bounded s := (compact_iff_totally_bounded_complete.1 h).1 lemma is_compact.is_complete {s : set α} (h : is_compact s) : is_complete s := (compact_iff_totally_bounded_complete.1 h).2 @[priority 100] -- see Note [lower instance priority] instance complete_of_compact {α : Type u} [uniform_space α] [compact_space α] : complete_space α := ⟨λf hf, by simpa using (compact_iff_totally_bounded_complete.1 compact_univ).2 f hf⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : is_compact s := (@compact_iff_totally_bounded_complete α _ s).2 ⟨ht, hc.is_complete⟩ /-! ### Sequentially complete space In this section we prove that a uniform space is complete provided that it is sequentially complete (i.e., any Cauchy sequence converges) and its uniformity filter admits a countable generating set. In particular, this applies to (e)metric spaces, see the files `topology/metric_space/emetric_space` and `topology/metric_space/basic`. More precisely, we assume that there is a sequence of entourages `U_n` such that any other entourage includes one of `U_n`. Then any Cauchy filter `f` generates a decreasing sequence of sets `s_n ∈ f` such that `s_n × s_n ⊆ U_n`. Choose a sequence `x_n∈s_n`. It is easy to show that this is a Cauchy sequence. If this sequence converges to some `a`, then `f ≤ 𝓝 a`. -/ namespace sequentially_complete variables {f : filter α} (hf : cauchy f) {U : ℕ → set (α × α)} (U_mem : ∀ n, U n ∈ 𝓤 α) (U_le : ∀ s ∈ 𝓤 α, ∃ n, U n ⊆ s) open set finset noncomputable theory /-- An auxiliary sequence of sets approximating a Cauchy filter. -/ def set_seq_aux (n : ℕ) : {s : set α // ∃ (_ : s ∈ f), s.prod s ⊆ U n } := indefinite_description _ $ (cauchy_iff.1 hf).2 (U n) (U_mem n) /-- Given a Cauchy filter `f` and a sequence `U` of entourages, `set_seq` provides an antitone sequence of sets `s n ∈ f` such that `(s n).prod (s n) ⊆ U`. -/ def set_seq (n : ℕ) : set α := ⋂ m ∈ Iic n, (set_seq_aux hf U_mem m).val lemma set_seq_mem (n : ℕ) : set_seq hf U_mem n ∈ f := (bInter_mem (finite_le_nat n)).2 (λ m _, (set_seq_aux hf U_mem m).2.fst) lemma set_seq_mono ⦃m n : ℕ⦄ (h : m ≤ n) : set_seq hf U_mem n ⊆ set_seq hf U_mem m := bInter_subset_bInter_left (λ k hk, le_trans hk h) lemma set_seq_sub_aux (n : ℕ) : set_seq hf U_mem n ⊆ set_seq_aux hf U_mem n := bInter_subset_of_mem right_mem_Iic lemma set_seq_prod_subset {N m n} (hm : N ≤ m) (hn : N ≤ n) : (set_seq hf U_mem m).prod (set_seq hf U_mem n) ⊆ U N := begin assume p hp, refine (set_seq_aux hf U_mem N).2.snd ⟨_, _⟩; apply set_seq_sub_aux, exact set_seq_mono hf U_mem hm hp.1, exact set_seq_mono hf U_mem hn hp.2 end /-- A sequence of points such that `seq n ∈ set_seq n`. Here `set_seq` is an antitone sequence of sets `set_seq n ∈ f` with diameters controlled by a given sequence of entourages. -/ def seq (n : ℕ) : α := some $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n) lemma seq_mem (n : ℕ) : seq hf U_mem n ∈ set_seq hf U_mem n := some_spec $ hf.1.nonempty_of_mem (set_seq_mem hf U_mem n) lemma seq_pair_mem ⦃N m n : ℕ⦄ (hm : N ≤ m) (hn : N ≤ n) : (seq hf U_mem m, seq hf U_mem n) ∈ U N := set_seq_prod_subset hf U_mem hm hn ⟨seq_mem hf U_mem m, seq_mem hf U_mem n⟩ include U_le theorem seq_is_cauchy_seq : cauchy_seq $ seq hf U_mem := cauchy_seq_of_controlled U U_le $ seq_pair_mem hf U_mem /-- If the sequence `sequentially_complete.seq` converges to `a`, then `f ≤ 𝓝 a`. -/ theorem le_nhds_of_seq_tendsto_nhds ⦃a : α⦄ (ha : tendsto (seq hf U_mem) at_top (𝓝 a)) : f ≤ 𝓝 a := le_nhds_of_cauchy_adhp_aux begin assume s hs, rcases U_le s hs with ⟨m, hm⟩, rcases tendsto_at_top'.1 ha _ (mem_nhds_left a (U_mem m)) with ⟨n, hn⟩, refine ⟨set_seq hf U_mem (max m n), set_seq_mem hf U_mem _, _, seq hf U_mem (max m n), _, seq_mem hf U_mem _⟩, { have := le_max_left m n, exact set.subset.trans (set_seq_prod_subset hf U_mem this this) hm }, { exact hm (hn _ $ le_max_right m n) } end end sequentially_complete namespace uniform_space open sequentially_complete variables [is_countably_generated (𝓤 α)] /-- A uniform space is complete provided that (a) its uniformity filter has a countable basis; (b) any sequence satisfying a "controlled" version of the Cauchy condition converges. -/ theorem complete_of_convergent_controlled_sequences (U : ℕ → set (α × α)) (U_mem : ∀ n, U n ∈ 𝓤 α) (HU : ∀ u : ℕ → α, (∀ N m n, N ≤ m → N ≤ n → (u m, u n) ∈ U N) → ∃ a, tendsto u at_top (𝓝 a)) : complete_space α := begin obtain ⟨U', U'_mono, hU'⟩ := (𝓤 α).exists_antitone_seq, have Hmem : ∀ n, U n ∩ U' n ∈ 𝓤 α, from λ n, inter_mem (U_mem n) (hU'.2 ⟨n, subset.refl _⟩), refine ⟨λ f hf, (HU (seq hf Hmem) (λ N m n hm hn, _)).imp $ le_nhds_of_seq_tendsto_nhds _ _ (λ s hs, _)⟩, { rcases (hU'.1 hs) with ⟨N, hN⟩, exact ⟨N, subset.trans (inter_subset_right _ _) hN⟩ }, { exact inter_subset_left _ _ (seq_pair_mem hf Hmem hm hn) } end /-- A sequentially complete uniform space with a countable basis of the uniformity filter is complete. -/ theorem complete_of_cauchy_seq_tendsto (H' : ∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) : complete_space α := let ⟨U', U'_mono, hU'⟩ := (𝓤 α).exists_antitone_seq in complete_of_convergent_controlled_sequences U' (λ n, hU'.2 ⟨n, subset.refl _⟩) (λ u hu, H' u $ cauchy_seq_of_controlled U' (λ s hs, hU'.1 hs) hu) variable (α) @[priority 100] instance first_countable_topology : first_countable_topology α := ⟨λ a, by { rw nhds_eq_comap_uniformity, apply_instance }⟩ /-- A separable uniform space with countably generated uniformity filter is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational "radii" from a countable open symmetric antitone basis of `𝓤 α`. 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 α := begin rcases exists_countable_dense α with ⟨s, hsc, hsd⟩, obtain ⟨t : ℕ → set (α × α), hto : ∀ (i : ℕ), t i ∈ (𝓤 α).sets ∧ is_open (t i) ∧ symmetric_rel (t i), h_basis : (𝓤 α).has_antitone_basis (λ _, true) t⟩ := (@uniformity_has_basis_open_symmetric α _).exists_antitone_subbasis, refine ⟨⟨⋃ (x ∈ s), range (λ k, ball x (t k)), hsc.bUnion (λ x hx, countable_range _), _⟩⟩, refine (is_topological_basis_of_open_of_nhds _ _).eq_generate_from, { simp only [mem_bUnion_iff, mem_range], rintros _ ⟨x, hxs, k, rfl⟩, exact is_open_ball x (hto k).2.1 }, { intros x V hxV hVo, simp only [mem_bUnion_iff, mem_range, exists_prop], rcases uniform_space.mem_nhds_iff.1 (is_open.mem_nhds hVo hxV) with ⟨U, hU, hUV⟩, rcases comp_symm_of_uniformity hU with ⟨U', hU', hsymm, hUU'⟩, rcases h_basis.to_has_basis.mem_iff.1 hU' with ⟨k, -, hk⟩, rcases hsd.inter_open_nonempty (ball x $ t k) (uniform_space.is_open_ball x (hto k).2.1) ⟨x, uniform_space.mem_ball_self _ (hto k).1⟩ with ⟨y, hxy, hys⟩, refine ⟨_, ⟨y, hys, k, rfl⟩, (hto k).2.2.subset hxy, λ z hz, _⟩, exact hUV (ball_subset_of_comp_subset (hk hxy) hUU' (hk hz)) } end end uniform_space
2ef954d844edb7d3bd9adc97eb2817a7141f4fad
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Elab/Tactic/Match.lean
fdd3cebcc67d2318af15fabffc401e6e229528fe
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,184
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Elab.Match import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.Induction namespace Lean.Elab.Tactic structure AuxMatchTermState where nextIdx : Nat := 1 «cases» : Array Syntax := #[] private def mkAuxiliaryMatchTermAux (parentTag : Name) (matchTac : Syntax) : StateT AuxMatchTermState MacroM Syntax := do let matchAlts := matchTac[4] let alts := matchAlts[0].getArgs let newAlts ← alts.mapM fun alt => do let alt := alt.setKind ``Parser.Term.matchAlt let holeOrTacticSeq := alt[3] if holeOrTacticSeq.isOfKind ``Parser.Term.syntheticHole then pure alt else if holeOrTacticSeq.isOfKind ``Parser.Term.hole then let s ← get let tag := if alts.size > 1 then parentTag ++ (`match).appendIndexAfter s.nextIdx else parentTag let holeName := mkIdentFrom holeOrTacticSeq tag let newHole ← `(?$holeName:ident) modify fun s => { s with nextIdx := s.nextIdx + 1} pure $ alt.setArg 3 newHole else withFreshMacroScope do let newHole ← `(?rhs) let newHoleId := newHole[1] let newCase ← `(tactic| case $newHoleId => $holeOrTacticSeq:tacticSeq ) modify fun s => { s with cases := s.cases.push newCase } pure $ alt.setArg 3 newHole let result := matchTac.setKind ``Parser.Term.«match» let result := result.setArg 4 (mkNode ``Parser.Term.matchAlts #[mkNullNode newAlts]) pure result private def mkAuxiliaryMatchTerm (parentTag : Name) (matchTac : Syntax) : MacroM (Syntax × Array Syntax) := do let (matchTerm, s) ← mkAuxiliaryMatchTermAux parentTag matchTac |>.run {} pure (matchTerm, s.cases) @[builtinTactic Lean.Parser.Tactic.match] def evalMatch : Tactic := fun stx => do let tag ← getMainTag let (matchTerm, cases) ← liftMacroM $ mkAuxiliaryMatchTerm tag stx let refineMatchTerm ← `(tactic| refine $matchTerm) let stxNew := mkNullNode (#[refineMatchTerm] ++ cases) withMacroExpansion stx stxNew $ evalTactic stxNew end Lean.Elab.Tactic
d71f958498f01ec6707a60b550c8cf28a5a1dcf2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/heyting/regular.lean
fbacda636ccd0d26f8f3ae79d322be651ee0001c
[ "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
6,592
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.galois_connection /-! # Heyting regular elements This file defines Heyting regular elements, elements of an Heyting algebra that are their own double complement, and proves that they form a boolean algebra. From a logic standpoint, this means that we can perform classical logic within intuitionistic logic by simply double-negating all propositions. This is practical for synthetic computability theory. ## Main declarations * `is_regular`: `a` is Heyting-regular if `aᶜᶜ = a`. * `regular`: The subtype of Heyting-regular elements. * `regular.boolean_algebra`: Heyting-regular elements form a boolean algebra. ## References * [Francis Borceux, *Handbook of Categorical Algebra III*][borceux-vol3] -/ open function variables {α : Type*} namespace heyting section has_compl variables [has_compl α] {a : α} /-- An element of an Heyting algebra is regular if its double complement is itself. -/ def is_regular (a : α) : Prop := aᶜᶜ = a protected lemma is_regular.eq : is_regular a → aᶜᶜ = a := id instance is_regular.decidable_pred [decidable_eq α] : @decidable_pred α is_regular := λ _, ‹decidable_eq α› _ _ end has_compl section heyting_algebra variables [heyting_algebra α] {a b : α} lemma is_regular_bot : is_regular (⊥ : α) := by rw [is_regular, compl_bot, compl_top] lemma is_regular_top : is_regular (⊤ : α) := by rw [is_regular, compl_top, compl_bot] lemma is_regular.inf (ha : is_regular a) (hb : is_regular b) : is_regular (a ⊓ b) := by rw [is_regular, compl_compl_inf_distrib, ha.eq, hb.eq] lemma is_regular.himp (ha : is_regular a) (hb : is_regular b) : is_regular (a ⇨ b) := by rw [is_regular, compl_compl_himp_distrib, ha.eq, hb.eq] lemma is_regular_compl (a : α) : is_regular aᶜ := compl_compl_compl _ protected lemma is_regular.disjoint_compl_left_iff (ha : is_regular a) : disjoint aᶜ b ↔ b ≤ a := by rw [←le_compl_iff_disjoint_left, ha.eq] protected lemma is_regular.disjoint_compl_right_iff (hb : is_regular b) : disjoint a bᶜ ↔ a ≤ b := by rw [←le_compl_iff_disjoint_right, hb.eq] /-- A Heyting algebra with regular excluded middle is a boolean algebra. -/ @[reducible] -- See note [reducible non-instances] def _root_.boolean_algebra.of_regular (h : ∀ a : α, is_regular (a ⊔ aᶜ)) : boolean_algebra α := have ∀ a : α, is_compl a aᶜ := λ a, ⟨disjoint_compl_right, codisjoint_iff.2 $ by erw [←(h a).eq, compl_sup, inf_compl_eq_bot, compl_bot]⟩, { himp_eq := λ a b, eq_of_forall_le_iff $ λ c, le_himp_iff.trans ((this _).le_sup_right_iff_inf_left_le).symm, inf_compl_le_bot := λ a, (this _).1.le_bot, top_le_sup_compl := λ a, (this _).2.top_le, ..‹heyting_algebra α›, ..generalized_heyting_algebra.to_distrib_lattice } variables (α) /-- The boolean algebra of Heyting regular elements. -/ def regular : Type* := {a : α // is_regular a} variables {α} namespace regular instance : has_coe (regular α) α := coe_subtype lemma coe_injective : injective (coe : regular α → α) := subtype.coe_injective @[simp] lemma coe_inj {a b : regular α} : (a : α) = b ↔ a = b := subtype.coe_inj instance : has_top (regular α) := ⟨⟨⊤, is_regular_top⟩⟩ instance : has_bot (regular α) := ⟨⟨⊥, is_regular_bot⟩⟩ instance : has_inf (regular α) := ⟨λ a b, ⟨a ⊓ b, a.2.inf b.2⟩⟩ instance : has_himp (regular α) := ⟨λ a b, ⟨a ⇨ b, a.2.himp b.2⟩⟩ instance : has_compl (regular α) := ⟨λ a, ⟨aᶜ, is_regular_compl _⟩⟩ @[simp, norm_cast] lemma coe_top : ((⊤ : regular α) : α) = ⊤ := rfl @[simp, norm_cast] lemma coe_bot : ((⊥ : regular α) : α) = ⊥ := rfl @[simp, norm_cast] lemma coe_inf (a b : regular α) : (↑(a ⊓ b) : α) = a ⊓ b := rfl @[simp, norm_cast] lemma coe_himp (a b : regular α) : (↑(a ⇨ b) : α) = a ⇨ b := rfl @[simp, norm_cast] lemma coe_compl (a : regular α) : (↑(aᶜ) : α) = aᶜ := rfl instance : inhabited (regular α) := ⟨⊥⟩ instance : semilattice_inf (regular α) := coe_injective.semilattice_inf _ coe_inf instance : bounded_order (regular α) := bounded_order.lift coe (λ _ _, id) coe_top coe_bot @[simp, norm_cast] lemma coe_le_coe {a b : regular α} : (a : α) ≤ b ↔ a ≤ b := iff.rfl @[simp, norm_cast] lemma coe_lt_coe {a b : regular α} : (a : α) < b ↔ a < b := iff.rfl /-- **Regularization** of `a`. The smallest regular element greater than `a`. -/ def to_regular : α →o regular α := ⟨λ a, ⟨aᶜᶜ, is_regular_compl _⟩, λ a b h, coe_le_coe.1 $ compl_le_compl $ compl_le_compl h⟩ @[simp, norm_cast] lemma coe_to_regular (a : α) : (to_regular a : α) = aᶜᶜ := rfl @[simp] lemma to_regular_coe (a : regular α) : to_regular (a : α) = a := coe_injective a.2 /-- The Galois insertion between `regular.to_regular` and `coe`. -/ def gi : galois_insertion to_regular (coe : regular α → α) := { choice := λ a ha, ⟨a, ha.antisymm le_compl_compl⟩, gc := λ a b, coe_le_coe.symm.trans $ ⟨le_compl_compl.trans, λ h, (compl_anti $ compl_anti h).trans_eq b.2⟩, le_l_u := λ _, le_compl_compl, choice_eq := λ a ha, coe_injective $ le_compl_compl.antisymm ha } instance : lattice (regular α) := gi.lift_lattice @[simp, norm_cast] lemma coe_sup (a b : regular α) : (↑(a ⊔ b) : α) = (a ⊔ b)ᶜᶜ := rfl instance : boolean_algebra (regular α) := { le_sup_inf := λ a b c, coe_le_coe.1 $ by { dsimp, rw [sup_inf_left, compl_compl_inf_distrib] }, inf_compl_le_bot := λ a, coe_le_coe.1 $ disjoint_iff_inf_le.1 disjoint_compl_right, top_le_sup_compl := λ a, coe_le_coe.1 $ by { dsimp, rw [compl_sup, inf_compl_eq_bot, compl_bot], refl }, himp_eq := λ a b, coe_injective begin dsimp, rw [compl_sup, a.prop.eq], refine eq_of_forall_le_iff (λ c, le_himp_iff.trans _), rw [le_compl_iff_disjoint_right, disjoint_left_comm, b.prop.disjoint_compl_left_iff], end, ..regular.lattice, ..regular.bounded_order, ..regular.has_himp, ..regular.has_compl } @[simp, norm_cast] lemma coe_sdiff (a b : regular α) : (↑(a \ b) : α) = a ⊓ bᶜ := rfl end regular end heyting_algebra variables [boolean_algebra α] lemma is_regular_of_boolean : ∀ a : α, is_regular a := compl_compl /-- A decidable proposition is intuitionistically Heyting-regular. -/ @[nolint decidable_classical] lemma is_regular_of_decidable (p : Prop) [decidable p] : is_regular p := propext $ decidable.not_not_iff _ end heyting
06479dd8cab279d3e89bdba3db9c4c243c588c35
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/t14.lean
d2b170c0829f600418d5f8e4ed8b4a53b82aee7a
[ "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
485
lean
prelude namespace foo constant A : Type.{1} constant a : A constant x : A constant c : A end foo section open foo (renaming a->b x->y) (hiding c) check b check y check c -- Error end section open foo (a x) check a check x check c -- Error end section open foo (a x) (hiding c) -- Error end section open foo check a check c check A end namespace foo constant f : A → A → A infix ` * `:75 := f end foo section open foo check a * c end
ebbed2f046c806c5b2fad986b76e1f204137a307
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/function/conditional_expectation/real.lean
a93d5a547b9e7ddc10e322ae737ec99d1663fff7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
19,712
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Kexing Ying -/ import measure_theory.function.conditional_expectation.indicator import measure_theory.function.uniform_integrable import measure_theory.decomposition.radon_nikodym /-! # Conditional expectation of real-valued functions This file proves some results regarding the conditional expectation of real-valued functions. ## Main results * `measure_theory.rn_deriv_ae_eq_condexp`: the conditional expectation `μ[f | m]` is equal to the Radon-Nikodym derivative of `fμ` restricted on `m` with respect to `μ` restricted on `m`. * `measure_theory.integrable.uniform_integrable_condexp`: the conditional expectation of a function form a uniformly integrable class. * `measure_theory.condexp_strongly_measurable_mul`: the pull-out property of the conditional expectation. -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topological_space big_operators measure_theory namespace measure_theory variables {α : Type*} {m m0 : measurable_space α} {μ : measure α} lemma rn_deriv_ae_eq_condexp {hm : m ≤ m0} [hμm : sigma_finite (μ.trim hm)] {f : α → ℝ} (hf : integrable f μ) : signed_measure.rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm) =ᵐ[μ] μ[f | m] := begin refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _, { exact λ _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm))).integrable_on }, { intros s hs hlt, conv_rhs { rw [← hf.with_densityᵥ_trim_eq_integral hm hs, ← signed_measure.with_densityᵥ_rn_deriv_eq ((μ.with_densityᵥ f).trim hm) (μ.trim hm) (hf.with_densityᵥ_trim_absolutely_continuous hm)], }, rw [with_densityᵥ_apply (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm)) hs, ← set_integral_trim hm _ hs], exact (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, { exact strongly_measurable.ae_strongly_measurable' (signed_measure.measurable_rn_deriv _ _).strongly_measurable }, end -- TODO: the following couple of lemmas should be generalized and proved using Jensen's inequality -- for the conditional expectation (not in mathlib yet) . lemma snorm_one_condexp_le_snorm (f : α → ℝ) : snorm (μ[f | m]) 1 μ ≤ snorm f 1 μ := begin by_cases hf : integrable f μ, swap, { rw [condexp_undef hf, snorm_zero], exact zero_le _ }, by_cases hm : m ≤ m0, swap, { rw [condexp_of_not_le hm, snorm_zero], exact zero_le _ }, by_cases hsig : sigma_finite (μ.trim hm), swap, { rw [condexp_of_not_sigma_finite hm hsig, snorm_zero], exact zero_le _ }, calc snorm (μ[f | m]) 1 μ ≤ snorm (μ[|f| | m]) 1 μ : begin refine snorm_mono_ae _, filter_upwards [@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf hf.abs (@ae_of_all _ m0 _ μ (λ x, le_abs_self (f x) : ∀ x, f x ≤ |f x|)), eventually_le.trans (condexp_neg f).symm.le (@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf.neg hf.abs (@ae_of_all _ m0 _ μ (λ x, neg_le_abs_self (f x) : ∀ x, -f x ≤ |f x|)))] with x hx₁ hx₂, exact abs_le_abs hx₁ hx₂, end ... = snorm f 1 μ : begin rw [snorm_one_eq_lintegral_nnnorm, snorm_one_eq_lintegral_nnnorm, ← ennreal.to_real_eq_to_real (ne_of_lt integrable_condexp.2) (ne_of_lt hf.2), ← integral_norm_eq_lintegral_nnnorm (strongly_measurable_condexp.mono hm).ae_strongly_measurable, ← integral_norm_eq_lintegral_nnnorm hf.1], simp_rw [real.norm_eq_abs], rw ← @integral_condexp _ _ _ _ _ m m0 μ _ hm hsig hf.abs, refine integral_congr_ae _, have : 0 ≤ᵐ[μ] μ[|f| | m], { rw ← @condexp_zero α ℝ _ _ _ m m0 μ, exact condexp_mono (integrable_zero _ _ _) hf.abs (@ae_of_all _ m0 _ μ (λ x, abs_nonneg (f x) : ∀ x, 0 ≤ |f x|)) }, filter_upwards [this] with x hx, exact abs_eq_self.2 hx end end lemma integral_abs_condexp_le (f : α → ℝ) : ∫ x, |μ[f | m] x| ∂μ ≤ ∫ x, |f x| ∂μ := begin by_cases hm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (λ x, abs_nonneg _) }, by_cases hfint : integrable f μ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (λ x, abs_nonneg _) }, rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae], { rw ennreal.to_real_le_to_real; simp_rw [← real.norm_eq_abs, of_real_norm_eq_coe_nnnorm], { rw [← snorm_one_eq_lintegral_nnnorm, ← snorm_one_eq_lintegral_nnnorm], exact snorm_one_condexp_le_snorm _ }, { exact ne_of_lt integrable_condexp.2 }, { exact ne_of_lt hfint.2 } }, { exact eventually_of_forall (λ x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact hfint.1.norm }, { exact eventually_of_forall (λ x, abs_nonneg _) }, { simp_rw ← real.norm_eq_abs, exact (strongly_measurable_condexp.mono hm).ae_strongly_measurable.norm } end lemma set_integral_abs_condexp_le {s : set α} (hs : measurable_set[m] s) (f : α → ℝ) : ∫ x in s, |μ[f | m] x| ∂μ ≤ ∫ x in s, |f x| ∂μ := begin by_cases hnm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero, integral_zero], exact integral_nonneg (λ x, abs_nonneg _) }, by_cases hfint : integrable f μ, swap, { simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const, algebra.id.smul_eq_mul, mul_zero], exact integral_nonneg (λ x, abs_nonneg _) }, have : ∫ x in s, |μ[f | m] x| ∂μ = ∫ x, |μ[s.indicator f | m] x| ∂μ, { rw ← integral_indicator, swap, { exact hnm _ hs }, refine integral_congr_ae _, have : (λ x, |μ[s.indicator f | m] x|) =ᵐ[μ] λ x, |s.indicator (μ[f | m]) x| := eventually_eq.fun_comp (condexp_indicator hfint hs) _, refine eventually_eq.trans (eventually_of_forall $ λ x, _) this.symm, rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl }, rw [this, ← integral_indicator], swap, { exact hnm _ hs }, refine (integral_abs_condexp_le _).trans (le_of_eq $ integral_congr_ae $ eventually_of_forall $ λ x, _), rw [← real.norm_eq_abs, norm_indicator_eq_indicator_norm], refl, end /-- If the real valued function `f` is bounded almost everywhere by `R`, then so is its conditional expectation. -/ lemma ae_bdd_condexp_of_ae_bdd {R : ℝ≥0} {f : α → ℝ} (hbdd : ∀ᵐ x ∂μ, |f x| ≤ R) : ∀ᵐ x ∂μ, |μ[f | m] x| ≤ R := begin by_cases hnm : m ≤ m0, swap, { simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero], refine eventually_of_forall (λ x, R.coe_nonneg) }, by_cases hfint : integrable f μ, swap, { simp_rw [condexp_undef hfint], filter_upwards [hbdd] with x hx, rw [pi.zero_apply, abs_zero], exact (abs_nonneg _).trans hx }, by_contra h, change μ _ ≠ 0 at h, simp only [← zero_lt_iff, set.compl_def, set.mem_set_of_eq, not_le] at h, suffices : (μ {x | ↑R < |μ[f | m] x|}).to_real * ↑R < (μ {x | ↑R < |μ[f | m] x|}).to_real * ↑R, { exact this.ne rfl }, refine lt_of_lt_of_le (set_integral_gt_gt R.coe_nonneg _ _ h.ne.symm) _, { simp_rw [← real.norm_eq_abs], exact (strongly_measurable_condexp.mono hnm).measurable.norm }, { exact integrable_condexp.abs.integrable_on }, refine (set_integral_abs_condexp_le _ _).trans _, { simp_rw [← real.norm_eq_abs], exact @measurable_set_lt _ _ _ _ _ m _ _ _ _ _ measurable_const strongly_measurable_condexp.norm.measurable }, simp only [← smul_eq_mul, ← set_integral_const, nnreal.val_eq_coe, is_R_or_C.coe_real_eq_id, id.def], refine set_integral_mono_ae hfint.abs.integrable_on _ _, { refine ⟨ae_strongly_measurable_const, lt_of_le_of_lt _ (integrable_condexp.integrable_on : integrable_on (μ[f | m]) {x | ↑R < |μ[f | m] x|} μ).2⟩, refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal (strongly_measurable_condexp.mono hnm).measurable.nnnorm.coe_nnreal_ennreal (λ x hx, _), { exact measurable_const }, { rw [ennreal.coe_le_coe, real.nnnorm_of_nonneg R.coe_nonneg], exact subtype.mk_le_mk.2 (le_of_lt hx) } }, { exact hbdd }, end /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a sequence of sub-σ-algebras is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp {ι : Type*} [is_finite_measure μ] {g : α → ℝ} (hint : integrable g μ) {ℱ : ι → measurable_space α} (hℱ : ∀ i, ℱ i ≤ m0) : uniform_integrable (λ i, μ[g | ℱ i]) 1 μ := begin have hmeas : ∀ n, ∀ C, measurable_set {x | C ≤ ‖μ[g | ℱ n] x‖₊} := λ n C, measurable_set_le measurable_const (strongly_measurable_condexp.mono (hℱ n)).measurable.nnnorm, have hg : mem_ℒp g 1 μ := mem_ℒp_one_iff_integrable.2 hint, refine uniform_integrable_of le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable) (λ ε hε, _), by_cases hne : snorm g 1 μ = 0, { rw snorm_eq_zero_iff hg.1 one_ne_zero at hne, refine ⟨0, λ n, (le_of_eq $ (snorm_eq_zero_iff ((strongly_measurable_condexp.mono (hℱ n)).ae_strongly_measurable.indicator (hmeas n 0)) one_ne_zero).2 _).trans (zero_le _)⟩, filter_upwards [@condexp_congr_ae _ _ _ _ _ (ℱ n) m0 μ _ _ hne] with x hx, simp only [zero_le', set.set_of_true, set.indicator_univ, pi.zero_apply, hx, condexp_zero] }, obtain ⟨δ, hδ, h⟩ := hg.snorm_indicator_le μ le_rfl ennreal.one_ne_top hε, set C : ℝ≥0 := ⟨δ, hδ.le⟩⁻¹ * (snorm g 1 μ).to_nnreal with hC, have hCpos : 0 < C := mul_pos (nnreal.inv_pos.2 hδ) (ennreal.to_nnreal_pos hne hg.snorm_lt_top.ne), have : ∀ n, μ {x : α | C ≤ ‖μ[g | ℱ n] x‖₊} ≤ ennreal.of_real δ, { intro n, have := mul_meas_ge_le_pow_snorm' μ one_ne_zero ennreal.one_ne_top ((@strongly_measurable_condexp _ _ _ _ _ (ℱ n) _ μ g).mono (hℱ n)).ae_strongly_measurable C, rw [ennreal.one_to_real, ennreal.rpow_one, ennreal.rpow_one, mul_comm, ← ennreal.le_div_iff_mul_le (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne)] at this, simp_rw [ennreal.coe_le_coe] at this, refine this.trans _, rw [ennreal.div_le_iff_le_mul (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm)) (or.inl ennreal.coe_lt_top.ne), hC, nonneg.inv_mk, ennreal.coe_mul, ennreal.coe_to_nnreal hg.snorm_lt_top.ne, ← mul_assoc, ← ennreal.of_real_eq_coe_nnreal, ← ennreal.of_real_mul hδ.le, mul_inv_cancel hδ.ne.symm, ennreal.of_real_one, one_mul], exact snorm_one_condexp_le_snorm _ }, refine ⟨C, λ n, le_trans _ (h {x : α | C ≤ ‖μ[g | ℱ n] x‖₊} (hmeas n C) (this n))⟩, have hmeasℱ : measurable_set[ℱ n] {x : α | C ≤ ‖μ[g | ℱ n] x‖₊} := @measurable_set_le _ _ _ _ _ (ℱ n) _ _ _ _ _ measurable_const (@measurable.nnnorm _ _ _ _ _ (ℱ n) _ strongly_measurable_condexp.measurable), rw ← snorm_congr_ae (condexp_indicator hint hmeasℱ), exact snorm_one_condexp_le_snorm _, end section pull_out -- TODO: this section could be generalized beyond multiplication, to any bounded bilinear map. /-- Auxiliary lemma for `condexp_measurable_mul`. -/ lemma condexp_strongly_measurable_simple_func_mul (hm : m ≤ m0) (f : @simple_func α m ℝ) {g : α → ℝ} (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : ∀ s c (f : α → ℝ), set.indicator s (function.const α c) * f = s.indicator (c • f), { intros s c f, ext1 x, by_cases hx : x ∈ s, { simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] }, { simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, }, refine @simple_func.induction _ _ m _ _ (λ c s hs, _) (λ g₁ g₂ h_disj h_eq₁ h_eq₂, _) f, { simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const, simple_func.coe_zero, set.piecewise_eq_indicator], rw [this, this], refine (condexp_indicator (hg.smul c) hs).trans _, filter_upwards [@condexp_smul α ℝ ℝ _ _ _ _ _ m m0 μ c g] with x hx, classical, simp_rw [set.indicator_apply, hx], }, { have h_add := @simple_func.coe_add _ _ m _ g₁ g₂, calc μ[⇑(g₁ + g₂) * g|m] =ᵐ[μ] μ[(⇑g₁ + ⇑g₂) * g|m] : by { refine condexp_congr_ae (eventually_eq.mul _ eventually_eq.rfl), rw h_add, } ... =ᵐ[μ] μ[⇑g₁ * g|m] + μ[⇑g₂ * g|m] : by { rw add_mul, exact condexp_add (hg.simple_func_mul' hm _) (hg.simple_func_mul' hm _), } ... =ᵐ[μ] ⇑g₁ * μ[g|m] + ⇑g₂ * μ[g|m] : eventually_eq.add h_eq₁ h_eq₂ ... =ᵐ[μ] ⇑(g₁ + g₂) * μ[g|m] : by rw [h_add, add_mul], }, end lemma condexp_strongly_measurable_mul_of_bound (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : strongly_measurable[m] f) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ‖f x‖ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin let fs := hf.approx_bounded c, have hfs_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, fs n x) at_top (𝓝 (f x)), from hf.tendsto_approx_bounded_ae hf_bound, by_cases hμ : μ = 0, { simp only [hμ, ae_zero], }, haveI : μ.ae.ne_bot, by simp only [hμ, ae_ne_bot, ne.def, not_false_iff], have hc : 0 ≤ c, { have h_exists : ∃ x, ‖f x‖ ≤ c := eventually.exists hf_bound, exact (norm_nonneg _).trans h_exists.some_spec, }, have hfs_bound : ∀ n x, ‖fs n x‖ ≤ c := hf.norm_approx_bounded_le hc, have hn_eq : ∀ n, μ[fs n * g | m] =ᵐ[μ] fs n * μ[g | m], from λ n, condexp_strongly_measurable_simple_func_mul hm _ hg, have : μ[f * μ[g|m]|m] = f * μ[g|m], { refine condexp_of_strongly_measurable hm (hf.mul strongly_measurable_condexp) _, exact integrable_condexp.bdd_mul' ((hf.mono hm).ae_strongly_measurable) hf_bound, }, rw ← this, refine tendsto_condexp_unique (λ n x, fs n x * g x) (λ n x, fs n x * μ[g|m] x) (f * g) (f * μ[g|m]) _ _ _ _ (λ x, c * ‖g x‖) _ (λ x, c * ‖μ[g|m] x‖) _ _ _ _, { exact λ n, hg.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { exact λ n, integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { filter_upwards [hfs_tendsto] with x hx, rw pi.mul_apply, exact tendsto.mul hx tendsto_const_nhds, }, { exact hg.norm.const_mul c, }, { exact integrable_condexp.norm.const_mul c, }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { refine λ n, eventually_of_forall (λ x, _), exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), }, { intros n, simp_rw ← pi.mul_apply, refine (condexp_strongly_measurable_simple_func_mul hm _ hg).trans _, rw condexp_of_strongly_measurable hm ((simple_func.strongly_measurable _).mul strongly_measurable_condexp) _, { apply_instance, }, { apply_instance, }, exact integrable_condexp.bdd_mul' ((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable (eventually_of_forall (hfs_bound n)), }, end lemma condexp_strongly_measurable_mul_of_bound₀ (hm : m ≤ m0) [is_finite_measure μ] {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hg : integrable g μ) (c : ℝ) (hf_bound : ∀ᵐ x ∂μ, ‖f x‖ ≤ c) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul_of_bound hm hf.strongly_measurable_mk hg c _, filter_upwards [hf_bound, hf.ae_eq_mk] with x hxc hx_eq, rw ← hx_eq, exact hxc, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul {f g : α → ℝ} (hf : strongly_measurable[m] f) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin by_cases hm : m ≤ m0, swap, { simp_rw condexp_of_not_le hm, rw mul_zero, }, by_cases hμm : sigma_finite (μ.trim hm), swap, { simp_rw condexp_of_not_sigma_finite hm hμm, rw mul_zero, }, haveI : sigma_finite (μ.trim hm) := hμm, obtain ⟨sets, sets_prop, h_univ⟩ := hf.exists_spanning_measurable_set_norm_le hm μ, simp_rw forall_and_distrib at sets_prop, obtain ⟨h_meas, h_finite, h_norm⟩ := sets_prop, suffices : ∀ n, ∀ᵐ x ∂μ, x ∈ sets n → μ[f * g|m] x = f x * μ[g|m] x, { rw ← ae_all_iff at this, filter_upwards [this] with x hx, rw pi.mul_apply, obtain ⟨i, hi⟩ : ∃ i, x ∈ sets i, { have h_mem : x ∈ ⋃ i, sets i, { rw h_univ, exact set.mem_univ _, }, simpa using h_mem, }, exact hx i hi, }, refine λ n, ae_imp_of_ae_restrict _, suffices : (μ.restrict (sets n))[f * g | m] =ᵐ[μ.restrict (sets n)] f * (μ.restrict (sets n))[g | m], { simp_rw ← pi.mul_apply, refine (condexp_restrict_ae_eq_restrict hm (h_meas n) hfg).symm.trans _, exact this.trans (eventually_eq.rfl.mul (condexp_restrict_ae_eq_restrict hm (h_meas n) hg)), }, suffices : (μ.restrict (sets n))[((sets n).indicator f) * g | m] =ᵐ[μ.restrict (sets n)] ((sets n).indicator f) * (μ.restrict (sets n))[g | m], { refine eventually_eq.trans _ (this.trans _), { exact condexp_congr_ae ((indicator_ae_eq_restrict (hm _ (h_meas n))).symm.mul eventually_eq.rfl), }, { exact (indicator_ae_eq_restrict (hm _ (h_meas n))).mul eventually_eq.rfl, }, }, haveI : is_finite_measure (μ.restrict (sets n)), { constructor, rw measure.restrict_apply_univ, exact h_finite n, }, refine condexp_strongly_measurable_mul_of_bound hm (hf.indicator (h_meas n)) hg.integrable_on n _, refine eventually_of_forall (λ x, _), by_cases hxs : x ∈ sets n, { simp only [hxs, set.indicator_of_mem], exact h_norm n x hxs, }, { simp only [hxs, set.indicator_of_not_mem, not_false_iff, _root_.norm_zero, nat.cast_nonneg], }, end /-- Pull-out property of the conditional expectation. -/ lemma condexp_strongly_measurable_mul₀ {f g : α → ℝ} (hf : ae_strongly_measurable' m f μ) (hfg : integrable (f * g) μ) (hg : integrable g μ) : μ[f * g | m] =ᵐ[μ] f * μ[g | m] := begin have : μ[f * g | m] =ᵐ[μ] μ[hf.mk f * g | m], from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl), refine this.trans _, have : f * μ[g | m] =ᵐ[μ] hf.mk f * μ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, refine eventually_eq.trans _ this.symm, refine condexp_strongly_measurable_mul hf.strongly_measurable_mk _ hg, refine (integrable_congr _).mp hfg, exact eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl, end end pull_out end measure_theory
bc21abc1b14179d319c0de7013d30d22ee6be70e
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/shapes/terminal.lean
6785c251e9f3f916bb8c3f00c1fad132d88ff9e8
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
5,211
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.pempty import category_theory.limits.limits /-! # Initial and terminal objects in a category. ## References * [Stacks: Initial and final objects](https://stacks.math.columbia.edu/tag/002B) -/ noncomputable theory universes v u open category_theory namespace category_theory.limits variables {C : Type u} [category.{v} C] /-- Construct a cone for the empty diagram given an object. -/ def as_empty_cone (X : C) : cone (functor.empty C) := { X := X, π := by tidy } /-- Construct a cocone for the empty diagram given an object. -/ def as_empty_cocone (X : C) : cocone (functor.empty C) := { X := X, ι := by tidy } /-- `X` is terminal if the cone it induces on the empty diagram is limiting. -/ abbreviation is_terminal (X : C) := is_limit (as_empty_cone X) /-- `X` is initial if the cocone it induces on the empty diagram is colimiting. -/ abbreviation is_initial (X : C) := is_colimit (as_empty_cocone X) /-- Give the morphism to a terminal object from any other. -/ def is_terminal.from {X : C} (t : is_terminal X) (Y : C) : Y ⟶ X := t.lift (as_empty_cone Y) /-- Any two morphisms to a terminal object are equal. -/ lemma is_terminal.hom_ext {X Y : C} (t : is_terminal X) (f g : Y ⟶ X) : f = g := t.hom_ext (by tidy) /-- Give the morphism from an initial object to any other. -/ def is_initial.to {X : C} (t : is_initial X) (Y : C) : X ⟶ Y := t.desc (as_empty_cocone Y) /-- Any two morphisms from an initial object are equal. -/ lemma is_initial.hom_ext {X Y : C} (t : is_initial X) (f g : X ⟶ Y) : f = g := t.hom_ext (by tidy) /-- Any morphism from a terminal object is mono. -/ lemma is_terminal.mono_from {X Y : C} (t : is_terminal X) (f : X ⟶ Y) : mono f := ⟨λ Z g h eq, t.hom_ext _ _⟩ /-- Any morphism to an initial object is epi. -/ lemma is_initial.epi_to {X Y : C} (t : is_initial X) (f : Y ⟶ X) : epi f := ⟨λ Z g h eq, t.hom_ext _ _⟩ variable (C) /-- A category has a terminal object if it has a limit over the empty diagram. Use `has_terminal_of_unique` to construct instances. -/ abbreviation has_terminal := has_limits_of_shape (discrete pempty) C /-- A category has an initial object if it has a colimit over the empty diagram. Use `has_initial_of_unique` to construct instances. -/ abbreviation has_initial := has_colimits_of_shape (discrete pempty) C /-- An arbitrary choice of terminal object, if one exists. You can use the notation `⊤_ C`. This object is characterized by having a unique morphism from any object. -/ abbreviation terminal [has_terminal C] : C := limit (functor.empty C) /-- An arbitrary choice of initial object, if one exists. You can use the notation `⊥_ C`. This object is characterized by having a unique morphism to any object. -/ abbreviation initial [has_initial C] : C := colimit (functor.empty C) notation `⊤_` C:20 := terminal C notation `⊥_` C:20 := initial C section variables {C} /-- We can more explicitly show that a category has a terminal object by specifying the object, and showing there is a unique morphism to it from any other object. -/ lemma has_terminal_of_unique (X : C) [h : Π Y : C, unique (Y ⟶ X)] : has_terminal C := { has_limit := λ F, has_limit.mk { cone := { X := X, π := { app := pempty.rec _ } }, is_limit := { lift := λ s, (h s.X).default } } } /-- We can more explicitly show that a category has an initial object by specifying the object, and showing there is a unique morphism from it to any other object. -/ lemma has_initial_of_unique (X : C) [h : Π Y : C, unique (X ⟶ Y)] : has_initial C := { has_colimit := λ F, has_colimit.mk { cocone := { X := X, ι := { app := pempty.rec _ } }, is_colimit := { desc := λ s, (h s.X).default } } } /-- The map from an object to the terminal object. -/ abbreviation terminal.from [has_terminal C] (P : C) : P ⟶ ⊤_ C := limit.lift (functor.empty C) (as_empty_cone P) /-- The map to an object from the initial object. -/ abbreviation initial.to [has_initial C] (P : C) : ⊥_ C ⟶ P := colimit.desc (functor.empty C) (as_empty_cocone P) instance unique_to_terminal [has_terminal C] (P : C) : unique (P ⟶ ⊤_ C) := { default := terminal.from P, uniq := λ m, by { apply limit.hom_ext, rintro ⟨⟩ } } instance unique_from_initial [has_initial C] (P : C) : unique (⊥_ C ⟶ P) := { default := initial.to P, uniq := λ m, by { apply colimit.hom_ext, rintro ⟨⟩ } } /-- A terminal object is terminal. -/ def terminal_is_terminal [has_terminal C] : is_terminal (⊤_ C) := { lift := λ s, terminal.from _ } /-- An initial object is initial. -/ def initial_is_initial [has_initial C] : is_initial (⊥_ C) := { desc := λ s, initial.to _ } /-- Any morphism from a terminal object is mono. -/ instance terminal.mono_from {Y : C} [has_terminal C] (f : ⊤_ C ⟶ Y) : mono f := is_terminal.mono_from terminal_is_terminal _ /-- Any morphism to an initial object is epi. -/ instance initial.epi_to {Y : C} [has_initial C] (f : Y ⟶ ⊥_ C) : epi f := is_initial.epi_to initial_is_initial _ end end category_theory.limits
326121d4813537785931ab7266e9f054c72f136a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Util.lean
289a098ff25b751c1938328eea2a9cfcae2c7d9f
[ "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
9,983
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.Parser.Command import Lean.KeyedDeclsAttribute import Lean.Elab.Exception namespace Lean def Syntax.prettyPrint (stx : Syntax) : Format := match stx.unsetTrailing.reprint with -- TODO use syntax pretty printer | some str => format str.toFormat | none => format stx def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format := Std.format <| if view.scopes.isEmpty then view.name else if view.mainModule == mainModule then view.scopes.foldl Name.mkNum (view.name ++ view.imported) else view.scopes.foldl Name.mkNum (view.name ++ view.imported ++ view.mainModule) namespace Elab def expandOptNamedPrio (stx : Syntax) : MacroM Nat := if stx.isNone then return eval_prio default else match stx[0] with | `(Parser.Command.namedPrio| (priority := $prio)) => evalPrio prio | _ => Macro.throwUnsupported structure MacroStackElem where before : Syntax after : Syntax abbrev MacroStack := List MacroStackElem /-- If `ref` does not have position information, then try to use macroStack -/ def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax := match ref.getPos? with | some _ => ref | none => match macroStack.find? (·.before.getPos? != none) with | some elem => elem.before | none => ref register_builtin_option pp.macroStack : Bool := { defValue := false group := "pp" descr := "dispaly macro expansion stack" } def addMacroStack {m} [Monad m] [MonadOptions m] (msgData : MessageData) (macroStack : MacroStack) : m MessageData := do if !pp.macroStack.get (← getOptions) then pure msgData else match macroStack with | [] => pure msgData | stack@(top::_) => let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ indentD top.after pure $ stack.foldl (fun (msgData : MessageData) (elem : MacroStackElem) => msgData ++ Format.line ++ "while expanding" ++ indentD elem.before) msgData def checkSyntaxNodeKind [Monad m] [MonadEnv m] [MonadError m] (k : Name) : m Name := do if Parser.isValidSyntaxNodeKind (← getEnv) k then pure k else throwError "failed" def checkSyntaxNodeKindAtNamespaces [Monad m] [MonadEnv m] [MonadError m] (k : Name) : Name → m Name | n@(.str p _) => checkSyntaxNodeKind (n ++ k) <|> checkSyntaxNodeKindAtNamespaces k p | .anonymous => checkSyntaxNodeKind k | _ => throwError "failed" def checkSyntaxNodeKindAtCurrentNamespaces (k : Name) : AttrM Name := do let ctx ← read checkSyntaxNodeKindAtNamespaces k ctx.currNamespace def syntaxNodeKindOfAttrParam (defaultParserNamespace : Name) (stx : Syntax) : AttrM SyntaxNodeKind := do let k ← Attribute.Builtin.getId stx checkSyntaxNodeKindAtCurrentNamespaces k <|> checkSyntaxNodeKind (defaultParserNamespace ++ k) <|> throwError "invalid syntax node kind '{k}'" private unsafe def evalSyntaxConstantUnsafe (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := env.evalConstCheck Syntax opts `Lean.Syntax constName @[implemented_by evalSyntaxConstantUnsafe] opaque evalSyntaxConstant (env : Environment) (opts : Options) (constName : Name) : ExceptT String Id Syntax := throw "" unsafe def mkElabAttribute (γ) (attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String) (attrDeclName : Name := by exact decl_name%) : IO (KeyedDeclsAttribute γ) := KeyedDeclsAttribute.init { builtinName := attrBuiltinName name := attrName descr := kind ++ " elaborator" valueTypeName := typeName evalKey := fun _ stx => do let kind ← syntaxNodeKindOfAttrParam parserNamespace stx /- Recall that a `SyntaxNodeKind` is often the name of the parser, but this is not always true, and we must check it. -/ if (← getEnv).contains kind && (← getInfoState).enabled then addConstInfo stx[1] kind none return kind onAdded := fun builtin declName => do if builtin then if let some doc ← findDocString? (← getEnv) declName (includeBuiltin := false) then declareBuiltin (declName ++ `docString) (mkAppN (mkConst ``addBuiltinDocString) #[toExpr declName, toExpr doc]) if let some declRanges ← findDeclarationRanges? declName then declareBuiltin (declName ++ `declRange) (mkAppN (mkConst ``addBuiltinDeclarationRanges) #[toExpr declName, toExpr declRanges]) } attrDeclName unsafe def mkMacroAttributeUnsafe (ref : Name) : IO (KeyedDeclsAttribute Macro) := mkElabAttribute Macro `builtin_macro `macro Name.anonymous `Lean.Macro "macro" ref @[implemented_by mkMacroAttributeUnsafe] opaque mkMacroAttribute (ref : Name) : IO (KeyedDeclsAttribute Macro) builtin_initialize macroAttribute : KeyedDeclsAttribute Macro ← mkMacroAttribute decl_name% /-- Try to expand macro at syntax tree root and return macro declaration name and new syntax if successful. Return none if all macros threw `Macro.Exception.unsupportedSyntax`. -/ def expandMacroImpl? (env : Environment) : Syntax → MacroM (Option (Name × Except Macro.Exception Syntax)) := fun stx => do for e in macroAttribute.getEntries env stx.getKind do try let stx' ← withFreshMacroScope (e.value stx) return (e.declName, Except.ok stx') catch | Macro.Exception.unsupportedSyntax => pure () | ex => return (e.declName, Except.error ex) return none class MonadMacroAdapter (m : Type → Type) where getCurrMacroScope : m MacroScope getNextMacroScope : m MacroScope setNextMacroScope : MacroScope → m Unit @[always_inline] instance (m n) [MonadLift m n] [MonadMacroAdapter m] : MonadMacroAdapter n := { getCurrMacroScope := liftM (MonadMacroAdapter.getCurrMacroScope : m _) getNextMacroScope := liftM (MonadMacroAdapter.getNextMacroScope : m _) setNextMacroScope := fun s => liftM (MonadMacroAdapter.setNextMacroScope s : m _) } def liftMacroM [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLiftT IO m] (x : MacroM α) : m α := do let env ← getEnv let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let methods := Macro.mkMethods { -- TODO: record recursive expansions in info tree? expandMacro? := fun stx => do match (← expandMacroImpl? env stx) with | some (_, stx?) => liftExcept stx? | none => return none hasDecl := fun declName => return env.contains declName getCurrNamespace := return currNamespace resolveNamespace := fun n => return ResolveName.resolveNamespace env currNamespace openDecls n resolveGlobalName := fun n => return ResolveName.resolveGlobalName env currNamespace openDecls n } match x { methods := methods ref := ← getRef currMacroScope := ← MonadMacroAdapter.getCurrMacroScope mainModule := env.mainModule currRecDepth := ← MonadRecDepth.getRecDepth maxRecDepth := ← MonadRecDepth.getMaxRecDepth } { macroScope := (← MonadMacroAdapter.getNextMacroScope) } with | EStateM.Result.error Macro.Exception.unsupportedSyntax _ => throwUnsupportedSyntax | EStateM.Result.error (Macro.Exception.error ref msg) _ => if msg == maxRecDepthErrorMessage then -- Make sure we can detect exception using `Exception.isMaxRecDepth` throwMaxRecDepthAt ref else throwErrorAt ref msg | EStateM.Result.ok a s => MonadMacroAdapter.setNextMacroScope s.macroScope s.traceMsgs.reverse.forM fun (clsName, msg) => trace clsName fun _ => msg return a @[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] [MonadEnv m] [MonadRecDepth m] [MonadError m] [MonadResolveName m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLiftT IO m] (x : Macro) (stx : Syntax) : m Syntax := liftMacroM (x stx) partial def mkUnusedBaseName (baseName : Name) : MacroM Name := do let currNamespace ← Macro.getCurrNamespace if ← Macro.hasDecl (currNamespace ++ baseName) then let rec loop (idx : Nat) := do let name := baseName.appendIndexAfter idx if ← Macro.hasDecl (currNamespace ++ name) then loop (idx+1) else return name loop 1 else return baseName def logException [Monad m] [MonadLog m] [AddMessageContext m] [MonadOptions m] [MonadLiftT IO m] (ex : Exception) : m Unit := do match ex with | Exception.error ref msg => logErrorAt ref msg | Exception.internal id _ => unless isAbortExceptionId id do let name ← id.getName logError m!"internal exception: {name}" def withLogging [Monad m] [MonadLog m] [MonadExcept Exception m] [AddMessageContext m] [MonadOptions m] [MonadLiftT IO m] (x : m Unit) : m Unit := do try x catch ex => logException ex def nestedExceptionToMessageData [Monad m] [MonadLog m] (ex : Exception) : m MessageData := do let pos ← getRefPos match ex.getRef.getPos? with | none => return ex.toMessageData | some exPos => if pos == exPos then return ex.toMessageData else let exPosition := (← getFileMap).toPosition exPos return m!"{exPosition.line}:{exPosition.column} {ex.toMessageData}" def throwErrorWithNestedErrors [MonadError m] [Monad m] [MonadLog m] (msg : MessageData) (exs : Array Exception) : m α := do throwError "{msg}, errors {toMessageList (← exs.mapM fun | ex => nestedExceptionToMessageData ex)}" builtin_initialize registerTraceClass `Elab registerTraceClass `Elab.step registerTraceClass `Elab.step.result (inherited := true) end Lean.Elab
3f2fc74981076784c197600295bd9480b6afe136
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/ring_theory/ideal_operations.lean
40e72caa2ab847c6ce731acf62f1a8656aaa9f42
[ "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
24,843
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau More operations on modules and ideals. -/ import ring_theory.ideals data.nat.choose order.zorn import linear_algebra.tensor_product import data.equiv.algebra import ring_theory.algebra_operations local attribute [instance, priority 0] nat.cast_coe universes u v w x open lattice namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Type w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Type w) (f : ι₁ → submodule R M) (ι₂ : Type x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul _ r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul _ r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (s.erase i).prod g, split, { rw [← quotient.eq, quotient.mk_one, ← finset.prod_hom (quotient.mk (f i))], apply finset.prod_eq_one, intros, rw [← quotient.mk_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ← finset.prod_hom (quotient.mk (f j))], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, use λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use finset.univ.sum (λ i, g i * φ i), intros i, rw [← quotient.eq, ← finset.sum_hom (quotient.mk (f i))], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, quotient.mk_one] at hφ1, rw [quotient.mk_mul, hφ1, mul_one] end def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient → Π i, (f i).quotient := @@quotient.lift _ _ (⨅ i, f i) (λ r i, ideal.quotient.mk (f i) r) (@pi.is_ring_hom_pi ι (λ i, (f i).quotient) _ R _ _ _) (λ r hr, funext $ λ i, quotient.eq_zero_iff_mem.2 $ (submodule.mem_infi _).1 hr i) theorem is_ring_hom_quotient_inf_to_pi_quotient (f : ι → ideal R) : is_ring_hom (quotient_inf_to_pi_quotient f) := @@quotient.is_ring_hom _ _ _ (@pi.is_ring_hom_pi ι (λ i, (f i).quotient) _ R _ _ _) _ theorem bijective_quotient_inf_to_pi_quotient [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃r Π i, (f i).quotient := { hom := is_ring_hom_quotient_inf_to_pi_quotient f, .. equiv.of_bijective (bijective_quotient_inf_to_pi_quotient hf) } end chinese_remainder section mul_and_radical variables {R : Type u} [comm_ring R] variables {I J K L: ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right hri, J.mul_mem_left hsj⟩ theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right $ I.mul_mem_left $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right hyni) (λ hmc, I.mul_mem_right $ I.mul_mem_right $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right hxmi)⟩, smul := λ r s ⟨n, hsni⟩, ⟨n, show (r * s)^n ∈ I, from (mul_pow r s n).symm ▸ I.mul_mem_left hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right hrm, (pow_add r m n).symm ▸ J.mul_mem_left hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := submodule.mem_Sup_of_directed hrnc y hyc hcc.directed_on in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, classical.or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right hpm) (m.add_mem (m.mul_mem_left hfm) (m.mul_mem_left hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr instance : comm_semiring (ideal R) := submodule.comm_semiring @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : radical_mul _ _ ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R → S) [is_ring_hom f] variables {I J : ideal R} {K L : ideal S} def map (I : ideal R) : ideal S := span (f '' I) def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, zero := show f 0 ∈ I, by rw is_ring_hom.map_zero f; exact I.zero_mem, add := λ x y hx hy, show f (x + y) ∈ I, by rw is_ring_hom.map_add f; exact I.add_mem hx hy, smul := λ c x hx, show f (c * x) ∈ I, by rw is_ring_hom.map_mul f; exact I.mul_mem_left hx } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono h variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, is_ring_hom.map_one f]; exact (ne_top_iff_one _).1 hK instance is_prime.comap {hK : K.is_prime} : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, is_ring_hom.map_mul f]; apply hK.2⟩ variables (I J K L) theorem map_bot : map f ⊥ = ⊥ := le_antisymm (map_le_iff_le_comap.2 bot_le) bot_le theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, is_ring_hom.map_one f⟩ theorem comap_top : comap f ⊤ = ⊤ := (eq_top_iff_one _).2 trivial theorem map_sup : map f (I ⊔ J) = map f I ⊔ map f J := le_antisymm (map_le_iff_le_comap.2 $ sup_le (map_le_iff_le_comap.1 le_sup_left) (map_le_iff_le_comap.1 le_sup_right)) (sup_le (map_mono le_sup_left) (map_mono le_sup_right)) theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw is_ring_hom.map_mul f; exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← is_ring_hom.map_mul f]; exact mem_map_of_mem (mul_mem_mul hri hsj)) theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (is_semiring_hom.map_pow f r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, is_semiring_hom.map_pow f r n ▸ hfrnk⟩) variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := map_le_iff_le_comap.2 $ (comap_inf f (map f I) (map f J)).symm ▸ inf_le_inf (map_le_iff_le_comap.1 $ le_refl _) (map_le_iff_le_comap.1 $ le_refl _) theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, is_semiring_hom.map_pow f r n ▸ mem_map_of_mem hrni⟩ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := map_le_iff_le_comap.1 $ (map_sup f (comap f K) (comap f L)).symm ▸ sup_le_sup (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) section surjective variables (hf : function.surjective f) include hf theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi)) theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, is_ring_hom.map_zero f⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ is_ring_hom.map_add f⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ is_ring_hom.map_mul f⟩) theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [is_ring_hom.map_sub f, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) /-- Correspondence theorem -/ def order_iso_of_surjective : ((≤) : ideal S → ideal S → Prop) ≃o ((≤) : { p : ideal R // comap f ⊥ ≤ p } → { p : ideal R // comap f ⊥ ≤ p } → Prop) := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, ord := λ I1 I2, ⟨comap_mono, λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H⟩ } def le_order_embedding_of_surjective : ((≤) : ideal S → ideal S → Prop) ≼o ((≤) : ideal R → ideal R → Prop) := (order_iso_of_surjective f hf).to_order_embedding.trans (subtype.order_embedding _ _) def lt_order_embedding_of_surjective : ((<) : ideal S → ideal S → Prop) ≼o ((<) : ideal R → ideal R → Prop) := (le_order_embedding_of_surjective f hf).lt_embedding_of_le_embedding end surjective end map_and_comap end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- It is even a semialgebra. But those aren't in mathlib yet. instance : semimodule (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule
e827123db5b7d1fe403545716b611f0a14182d1c
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0703.lean
f64dc8c84991faa79a9cd00b870776cb5b4b7902
[]
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
49
lean
open list #check nil #check cons #check append
be950c3a659f7bce54fd2d8b9732d9f32d452e58
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_330.lean
70864bffe96830db0363c1c2106f599d6058abed
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
137
lean
import tactic variable {α : Type*} variables (s t u : set α) -- BEGIN example : s ∩ t = t ∩ s := by ext x; simp [and.comm] -- END
02e9dd4d3ad9c5201760ad7ffe0147a6e8800dbf
76ce87faa6bc3c2aa9af5962009e01e04f2a074a
/HW/HW3-key.lean
a99300042785ba9d208c78c5f2cc3f51723f84a6
[]
no_license
Mnormansell/Discrete-Notes
db423dd9206bbe7080aecb84b4c2d275b758af97
61f13b98be590269fc4822be7b47924a6ddc1261
refs/heads/master
1,585,412,435,424
1,540,919,483,000
1,540,919,483,000
148,684,638
0
0
null
null
null
null
UTF-8
Lean
false
false
6,635
lean
/- Produce a proof, pf1, of the proposition that 0 = 0 ∧ (1 = 1 ∧ 2 = 2). -/ lemma pf1 : 0 = 0 ∧ (1 = 1 ∧ 2 = 2) := and.intro rfl (and.intro rfl rfl) /- Produce a proof, pf2, of the proposition that (0 = 0 ∧ 1 = 1) ∧ 2 = 2 -/ lemma pf2 : (0 = 0 ∧ 1 = 1) ∧ 2 = 2 := and.intro (and.intro rfl rfl) rfl /- Produce a proof, pf3, of the proposition that 0 = 0 ∧ 1 = 1 ∧ 2 = 2. Hint, one of the two preceding proofs can be used to prove this proposition; there's no need to type out a whole new proof. -/ lemma pf3 : 0 = 0 ∧ 1 = 1 ∧ 2 = 2 := pf1 /- An operator, *, is "right associative" if X * Y * Z means X * (Y * Z), and is "left associative" if X * Y * Z means (X * Y) * Y. Is the logical connective, ∧, left or right associative? Explain. -/ -- It's right associative as we just proved -- pf3 with pf1, and pf1 is in the form -- X * (Y * Z). /- Use Lean to produce a proof, pf4, that 0 = 0 ∧ 1 = 1 ∧ 2 = 2 is exactly the same proposition as one of the two parenthesized forms. It will be a proof that two propositions are equal. Put parentheses around each of the propositions. -/ lemma pf4 : (0 = 0 ∧ 1 = 1 ∧ 2 = 2) = (0 = 0 ∧ (1 = 1 ∧ 2 = 2)) := rfl /- Given arbitrary propositions, P, Q and R it should be possible to produce a proof, pf5, showing that if P ∧ (Q ∧ R) is true then so is (P ∧ Q) ∧ R. Written in inference rule form, this would say the following: { P Q R: Prop }, pqr_left : P ∧ (Q ∧ R) ---------------------------------- ∧.assoc' pqr_right : (P ∧ Q) ∧ R Proving that this is a valid rule can be done by defining a function, let's call it and_assoc_l, that when given any propositions, P, Q, and R (implicitly), and when given a proof of P ∧ (Q ∧ R), constructs and returns a proof of (P ∧ Q) ∧ R. Here we give you this function, and we explain each part in comments. You will then apply what you learn by studying this example to solve the same problem but going in the other direction. Here's the solution. -/ -- define the function name def and_assoc_l -- specify the arguments and their types {P Q R: Prop} (pf: P ∧ (Q ∧ R)) : -- note colon -- the return type (P ∧ Q) ∧ R /- What we've given so far is what we call the function signature: its name, the names and types of the arguments that it takes, and the type of the return value. In this case, the return value is of type (P ∧ Q) ∧ R, and will thus serve as a proof of this proposition. This is a function that takes a proof and returns a (different) proof. It thus provides a general recipe for turning any proof of P ∧ (Q ∧ R) into a proof of (P ∧ Q) ∧ R. -/ := -- now give function body /- Usually we'd expect to see an expression here, involving multiple, nested and.elim and and.intro expressions. We could write the function body that way, but it's a bit tricky to get all the nested expressions right. Here's a revelation: We can use a tactic script to produce the same result. Open your Messages window, put your cursor on begin, study carefully the tactic state, notice that the arguments are given in the context to the left of the turnstile and the goal remaining to be proved is to the right. You can use the context values as arguments to tactics. Now click through each line of the script and study very carefully how it changes the context. By the end of the script, you should see how we've been able to use elimination rules take apart the proof that was given as an argument, giving names to the parts, and how we can then further take apart those parts, giving names to the subparts, and finally how we can intro rules to put all these pieces together again into the proof we need. -/ begin have pfP := and.elim_left pf, have pfQR := and.elim_right pf, have pfQ := and.elim_left pfQR, have pfR := and.elim_right pfQR, have pfPQ := and.intro pfP pfQ, have pfPQ_R := and.intro pfPQ pfR, exact pfPQ_R end /- Define another function, and_assoc_r, that goes the other direction: given a proof of (P ∧ Q) ∧ R it derives and returns a proof of P ∧ (Q ∧ R). Write the entire solution yourself. -/ def and_assoc_r {P Q R: Prop} (pf: (P ∧ Q) ∧ R) : P ∧ (Q ∧ R) := begin have pfPQ := and.elim_left pf, have pfR := and.elim_right pf, have pfP := and.elim_left pfPQ, have pfQ := and.elim_right pfPQ, have pfQR := and.intro pfQ pfR, have pfP_QR := and.intro pfP pfQR, exact pfP_QR end /- It's important to learn how you would give such proofs in natural langage. Let's take our first example. Here is a natural language version. "Given arbitrary propositions, P, Q, and R, and the assumption that P ∧ (Q ∧ R) is true, we are to show that (P ∧ Q) ∧ R is true. Given that P ∧ (Q ∧ R) is true, it must be that P is true and that Q ∧ R is also true. Given that Q ∧ R is true, it must be that Q is true, and R is also true. So we have that P, Q, and R are all true. From these conclusions we can in turn deduce that P ∧ Q must be true. And so we now have that P ∧ Q is true and so is R, from which, finally we can deduce that (P ∧ Q) ∧ R must be true as well. QED." Now it's your turn: write an English language proof for the theorem in the other direction. -/ /- "Given arbitrary propositions, P, Q, and R, and the assumption that (P ∧ Q) ∧ R is true, we are to show that P ∧ (Q ∧ R) is true. Given that (P ∧ Q) ∧ R, it must be that (P ∧ Q) is true and also that R is true. Given that (P ∧ Q) is true, then P must be true, and Q must be true. Therefore P, Q, and R are all true. From this conclusion we can deduce that Q ∧ R must be true. Since P is true and (Q ∧ R) is true, it follows that P ∧ (Q ∧ R) must be true as well. QED." -/ /- Use Lean to produce a proof, tnott, of the proposition that truth isn't truth. I.e., true is not true. We'll write this is Lean like this: theorem tnott: true ≠ true := _. To make it a little easier to solve this otherwise difficult problem, we allow you to stipulate one "axiom" of your choice, which you can then use to produce the required proof. -/ -- You can introduce an axiom here axiom f: false -- Now prove the theorem theorem tnott : true ≠ true := false.elim f /- What did you have to accept to be able to prove that truth isn't truth? -/ /- We had to accept that there was an axiom for false, which is an absurdity, which then allows us to create a proof for a proposition for which there is not proof -/
e8c5391168a49c3b5809b2406c304fb393702d6f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/transfer.lean
a4302fd6b9c76ff87d10fbb5665d0d5750a95805
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,495
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 (CMU) -/ prelude import init.meta.tactic import init.meta.match_tactic import init.meta.mk_dec_eq_instance import init.data.list.instances import logic.relator open tactic expr list monad namespace transfer /- Transfer rules are of the shape: rel_t : {u} Πx, R t₁ t₂ where `u` is a list of universe parameters, `x` is a list of dependent variables, and `R` is a relation. Then this rule will translate `t₁` (depending on `u` and `x`) into `t₂`. `u` and `x` will be called parameters. When `R` is a relation on functions lifted from `S` and `R` the variables bound by `S` are called arguments. `R` is generally constructed using `⇒` (i.e. `relator.lift_fun`). As example: rel_eq : (R ⇒ R ⇒ iff) eq t transfer will match this rule when it sees: (@eq α a b) and transfer it to (t a b) Here `α` is a parameter and `a` and `b` are arguments. TODO: add trace statements TODO: currently the used relation must be fixed by the matched rule or through type class inference. Maybe we want to replace this by type inference similar to Isabelle's transfer. -/ private meta structure rel_data := (in_type : expr) (out_type : expr) (relation : expr) meta instance has_to_tactic_format_rel_data : has_to_tactic_format rel_data := ⟨λr, do R ← pp r.relation, α ← pp r.in_type, β ← pp r.out_type, return format!"({R}: rel ({α}) ({β}))" ⟩ private meta structure rule_data := (pr : expr) (uparams : list name) -- levels not in pat (params : list (expr × bool)) -- fst : local constant, snd = tt → param appears in pattern (uargs : list name) -- levels not in pat (args : list (expr × rel_data)) -- fst : local constant (pat : pattern) -- `R c` (output : expr) -- right-hand side `d` of rel equation `R c d` meta instance has_to_tactic_format_rule_data : has_to_tactic_format rule_data := ⟨λr, do pr ← pp r.pr, up ← pp r.uparams, mp ← pp r.params, ua ← pp r.uargs, ma ← pp r.args, pat ← pp r.pat.target, output ← pp r.output, return format!"{{ ⟨{pat}⟩ pr: {pr} → {output}, {up} {mp} {ua} {ma} }}" ⟩ private meta def get_lift_fun : expr → tactic (list rel_data × expr) | e := do { guardb (is_constant_of (get_app_fn e) ``relator.lift_fun), [α, β, γ, δ, R, S] ← return $ get_app_args e, (ps, r) ← get_lift_fun S, return (rel_data.mk α β R :: ps, r)} <|> return ([], e) private meta def mark_occurences (e : expr) : list expr → list (expr × bool) | [] := [] | (h :: t) := let xs := mark_occurences t in (h, occurs h e || any xs (λ⟨e, oc⟩, oc && occurs h e)) :: xs private meta def analyse_rule (u' : list name) (pr : expr) : tactic rule_data := do t ← infer_type pr, (params, app (app r f) g) ← mk_local_pis t, (arg_rels, R) ← get_lift_fun r, args ← (enum arg_rels).mmap $ λ⟨n, a⟩, prod.mk <$> mk_local_def (mk_simple_name ("a_" ++ repr n)) a.in_type <*> pure a, a_vars ← return $ prod.fst <$> args, p ← head_beta (app_of_list f a_vars), p_data ← return $ mark_occurences (app R p) params, p_vars ← return $ list.map prod.fst (p_data.filter (λx, ↑x.2)), u ← return $ collect_univ_params (app R p) ∩ u', pat ← mk_pattern (level.param <$> u) (p_vars ++ a_vars) (app R p) (level.param <$> u) (p_vars ++ a_vars), return $ rule_data.mk pr (u'.remove_all u) p_data u args pat g meta def analyse_decls : list name → tactic (list rule_data) := mmap (λn, do d ← get_decl n, c ← return d.univ_params.length, ls ← (repeat () c).mmap (λ_, mk_fresh_name), analyse_rule ls (const n (ls.map level.param))) private meta def split_params_args : list (expr × bool) → list expr → list (expr × option expr) × list expr | ((lc, tt) :: ps) (e :: es) := let (ps', es') := split_params_args ps es in ((lc, some e) :: ps', es') | ((lc, ff) :: ps) es := let (ps', es') := split_params_args ps es in ((lc, none) :: ps', es') | _ es := ([], es) private meta def param_substitutions (ctxt : list expr) : list (expr × option expr) → tactic (list (name × expr) × list expr) | (((local_const n _ bi t), s) :: ps) := do (e, m) ← match s with | (some e) := return (e, []) | none := let ctxt' := list.filter (λv, occurs v t) ctxt in let ty := pis ctxt' t in if bi = binder_info.inst_implicit then do guard (bi = binder_info.inst_implicit), e ← instantiate_mvars ty >>= mk_instance, return (e, []) else do mv ← mk_meta_var ty, return (app_of_list mv ctxt', [mv]) end, sb ← return $ instantiate_local n e, ps ← return $ prod.map sb ((<$>) sb) <$> ps, (ms, vs) ← param_substitutions ps, return ((n, e) :: ms, m ++ vs) | _ := return ([], []) /- input expression a type `R a`, it finds a type `b`, s.t. there is a proof of the type `R a b`. It return (`a`, pr : `R a b`) -/ meta def compute_transfer : list rule_data → list expr → expr → tactic (expr × expr × list expr) | rds ctxt e := do -- Select matching rule (i, ps, args, ms, rd) ← first (rds.map (λrd, do (l, m) ← match_pattern rd.pat e semireducible, level_map ← rd.uparams.mmap $ λl, prod.mk l <$> mk_meta_univ, inst_univ ← return $ λe, instantiate_univ_params e (level_map ++ zip rd.uargs l), (ps, args) ← return $ split_params_args (rd.params.map (prod.map inst_univ id)) m, (ps, ms) ← param_substitutions ctxt ps, /- this checks type class parameters -/ return (instantiate_locals ps ∘ inst_univ, ps, args, ms, rd))) <|> (do trace e, fail "no matching rule"), (bs, hs, mss) ← (zip rd.args args).mmap (λ⟨⟨_, d⟩, e⟩, do -- Argument has function type (args, r) ← get_lift_fun (i d.relation), ((a_vars, b_vars), (R_vars, bnds)) ← (enum args).mmap (λ⟨n, arg⟩, do a ← mk_local_def sformat!"a{n}" arg.in_type, b ← mk_local_def sformat!"b{n}" arg.out_type, R ← mk_local_def sformat!"R{n}" (arg.relation a b), return ((a, b), (R, [a, b, R]))) >>= (return ∘ prod.map unzip unzip ∘ unzip), rds' ← R_vars.mmap (analyse_rule []), -- Transfer argument a ← return $ i e, a' ← head_beta (app_of_list a a_vars), (b, pr, ms) ← compute_transfer (rds ++ rds') (ctxt ++ a_vars) (app r a'), b' ← head_eta (lambdas b_vars b), return (b', [a, b', lambdas (list.join bnds) pr], ms)) >>= (return ∘ prod.map id unzip ∘ unzip), -- Combine b ← head_beta (app_of_list (i rd.output) bs), pr ← return $ app_of_list (i rd.pr) (prod.snd <$> ps ++ list.join hs), return (b, pr, ms ++ mss.join) end transfer open transfer meta def tactic.transfer (ds : list name) : tactic unit := do rds ← analyse_decls ds, tgt ← target, (guard (¬ tgt.has_meta_var) <|> fail "Target contains (universe) meta variables. This is not supported by transfer."), (new_tgt, pr, ms) ← compute_transfer rds [] ((const `iff [] : expr) tgt), new_pr ← mk_meta_var new_tgt, /- Setup final tactic state -/ exact ((const `iff.mpr [] : expr) tgt new_tgt pr new_pr), ms ← ms.mmap (λm, (get_assignment m >> return []) <|> return [m]), gs ← get_goals, set_goals (ms.join ++ new_pr :: gs)
59be4c8bfa5c62beab09a93486e1ac88eab9b034
367134ba5a65885e863bdc4507601606690974c1
/src/data/polynomial/eval.lean
c5f252ab8e26776cb6510a6cde3d8daa383cf0c7
[ "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
26,299
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.induction import data.polynomial.degree.definitions import deprecated.ring /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_eq_lift_nc {f : R →+* S} {x : S} : eval₂ f x = lift_nc ↑f (powers_hom S x) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : polynomial R} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_at_zero : p.eval₂ f 0 = f (coeff p 0) := begin -- This proof is lame, and the `finsupp` API shows through. simp only [eval₂_eq_sum, zero_pow_eq, mul_ite, mul_zero, mul_one, finsupp.sum_ite_eq'], split_ifs, { refl, }, { simp only [not_not, finsupp.mem_support_iff, ne.def] at h, apply_fun f at h, simpa using h.symm, }, end @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by simp [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [f.map_zero, zero_mul]).trans $ by rw [f.map_one, one_mul, pow_one] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := begin apply sum_single_index, simp, end @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [f.map_zero, zero_mul]) (λ _ _ _, by rw [f.map_add, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : polynomial R) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := begin simp only [eval₂, sum_smul_index, forall_const, zero_mul, g.map_zero, g.map_mul, mul_assoc], rw [←finsupp.mul_sum], end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, monomial_eq_smul_X, C_mul']) instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : polynomial R).eval₂ f x = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] variables [semiring T] lemma eval₂_sum (p : polynomial T) (g : ℕ → T → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) lemma eval₂_finset_sum (s : finset ι) (g : ι → polynomial R) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := begin classical, induction s using finset.induction with p hp s hs, simp, rw [sum_insert, eval₂_add, hs, sum_insert]; assumption, end lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := begin simp only [eval₂_eq_lift_nc], exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n) end @[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x := begin refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X), rcases em (k = 1) with (rfl|hk), { simp }, { simp [coeff_X_of_ne_one hk] } end @[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x := by rw [X_mul, eval₂_mul_X] lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a := begin rw [eval₂_mul_noncomm, eval₂_C], intro k, obtain (hk|(hk : _ = _)) : (C a).coeff k ∈ ({0, a} : set R) := finsupp.single_apply_mem _; simp [hk, h] end lemma eval₂_list_prod_noncomm (ps : list (polynomial R)) (hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) : eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps using list.reverse_rec_on with ps p ihp, { simp }, { simp only [list.forall_mem_append, list.forall_mem_singleton] at hf, simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : polynomial R →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k), map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ variables [comm_semiring S] variables (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := eval₂_mul_noncomm _ _ $ λ k, commute.all _ _ lemma eval₂_mul_eq_zero_of_left (q : polynomial R) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : polynomial R) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = sum p (λ e a, a * x ^ e) := rfl lemma eval_eq_finset_sum (P : polynomial R) (x : R) : eval x P = ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i := begin rw eval_eq_sum, refine P.sum_of_support_subset _ _ _, { intros a, rw [mem_range, nat.lt_add_one_iff], exact le_nat_degree_of_mem_supp a }, { intros, exact zero_mul _ } end lemma eval_eq_finset_sum' (P : polynomial R) : (λ x, eval x P) = (λ x, ∑ i in range (P.nat_degree + 1), P.coeff i * x ^ i) := begin ext, exact P.eval_eq_finset_sum x end @[simp] lemma eval₂_at_apply {S : Type*} [semiring S] (f : R →+* S) (r : R) : p.eval₂ f (f r) = f (p.eval r) := begin rw [eval₂_eq_sum, eval_eq_sum, finsupp.sum, finsupp.sum, f.map_sum], simp only [f.map_mul, f.map_pow], end @[simp] lemma eval₂_at_one {S : Type*} [semiring S] (f : R →+* S) : p.eval₂ f 1 = f (p.eval 1) := begin convert eval₂_at_apply f 1, simp, end @[simp] lemma eval₂_at_nat_cast {S : Type*} [semiring S] (f : R →+* S) (n : ℕ) : p.eval₂ f n = f (p.eval n) := begin convert eval₂_at_apply f n, simp, end @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : polynomial R).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul (p : polynomial R) (x : R) {s : R} : (s • p).eval x = s * p.eval x := eval₂_smul (ring_hom.id _) _ _ @[simp] lemma eval_C_mul : (C a * p).eval x = a * p.eval x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [mul_add, eval_add, ph, qh], }, { intros n b, simp [mul_assoc], } end @[simp] lemma eval_nat_cast_mul {n : ℕ} : ((n : polynomial R) * p).eval x = n * p.eval x := by rw [←C_eq_nat_cast, eval_C_mul] @[simp] lemma eval_mul_X : (p * X).eval x = p.eval x * x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [add_mul, eval_add, ph, qh], }, { intros n a, simp only [←monomial_one_one_eq_X, monomial_mul_monomial, eval_monomial, mul_one, pow_succ', mul_assoc], } end @[simp] lemma eval_mul_X_pow {k : ℕ} : (p * X^k).eval x = p.eval x * x^k := begin induction k with k ih, { simp, }, { simp [pow_succ', ←mul_assoc, ih], } end lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → polynomial R) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, ← single_eq_C_mul_X], exact finsupp.sum_single _, end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, sum_def], rw [← p.support.sum_hom (@C R _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma nat_cast_comp {n : ℕ} : (n : polynomial R).comp p = n := by rw [←C_eq_nat_cast, C_comp] @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma monomial_comp (n : ℕ) : (monomial n a).comp p = C a * p^n := eval₂_monomial _ _ @[simp] lemma mul_X_comp : (p * X).comp r = p.comp r * r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, add_mul], }, { intros n b, simp [pow_succ', mul_assoc], } end @[simp] lemma X_pow_comp {k : ℕ} : (X^k).comp p = p^k := begin induction k with k ih, { simp, }, { simp [pow_succ', mul_X_comp, ih], }, end @[simp] lemma mul_X_pow_comp {k : ℕ} : (p * X^k).comp r = p.comp r * r^k := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, mul_X_comp], }, end @[simp] lemma C_mul_comp : (C a * p).comp r = C a * p.comp r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, mul_add], }, { intros n b, simp [mul_assoc], } end @[simp] lemma nat_cast_mul_comp {n : ℕ} : ((n : polynomial R) * p).comp r = n * p.comp r := by rw [←C_eq_nat_cast, C_mul_comp, C_eq_nat_cast] @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : polynomial R) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ @[simp] lemma pow_comp {R : Type*} [comm_semiring R] (p q : polynomial R) (n : ℕ) : (p^n).comp q = (p.comp q)^n := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end @[simp] lemma bit0_comp : comp (bit0 p : polynomial R) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : polynomial R) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : polynomial R) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C.comp f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, single_eq_C_mul_X], refl, end @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] theorem map_nat_cast (n : ℕ) : (n : polynomial R).map f = n := nat.rec_on n rfl $ λ n ih, by rw [n.cast_succ, map_add, ih, map_one, n.cast_succ] @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum, sum_def], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, sum_def, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, f.map_mul], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map [semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) variables {f} lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp [hp] ... = f x * (p.map f).coeff p.nat_degree : by { congr, apply (coeff_map _ _).symm } ... = 0 : by simp [hfp], λ h, ext (λ n, trans (coeff_map f n) (h _)) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) variables (f) open is_semiring_hom -- If the rings were commutative, we could prove this just using `eval₂_mul`. -- TODO this proof is just a hack job on the proof of `eval₂_mul`, -- using that `X` is central. It should probably be golfed! @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := begin dunfold map, dunfold eval₂, rw [add_monoid_algebra.mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, (C.comp f).map_mul, pow_add], { simp [←mul_assoc], conv_lhs { rw ←@X_pow_mul_assoc _ _ _ _ i }, }, { simp, } }, { intro, simp, }, { intros, simp [add_mul], } }, { intro, simp, }, { intros, simp [add_mul], } end instance map.is_semiring_hom : is_semiring_hom (map f) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ _ _, eval₂_add _ _, map_mul := λ _ _, map_mul f, } /-- `polynomial.map` as a `ring_hom` -/ def map_ring_hom (f : R →+* S) : polynomial R →+* polynomial S := { to_fun := polynomial.map f, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ _ _, map_mul f, map_one' := eval₂_one _ _ } @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl lemma map_list_prod (L : list (polynomial R)) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (monoid_hom.of (map f)) @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := is_monoid_hom.map_pow (map f) _ _ lemma mem_map_range {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := begin convert finsupp.sum_map_range_index _, { change map f p = map_range f _ p, ext, rw map_range_apply, exact coeff_map f a, }, { exact f.map_zero, }, { intro a, simp only [ring_hom.map_zero, zero_mul], }, end lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map f (ring_hom.id _) x lemma map_sum {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := eq.symm $ sum_hom _ _ lemma map_comp (p q : polynomial R) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp) (by simp {contextual := tt}) (by simp [pow_succ', ← mul_assoc, polynomial.comp] {contextual := tt}) @[simp] lemma eval_zero_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 0 = f (p.eval 0) := by simp [←coeff_zero_eq_eval_zero] @[simp] lemma eval_one_map (f : R →+* S) (p : polynomial R) : (p.map f).eval 1 = f (p.eval 1) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end @[simp] lemma eval_nat_cast_map (f : R →+* S) (p : polynomial R) (n : ℕ) : (p.map f).eval n = f (p.eval n) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end @[simp] lemma eval_int_cast_map {R S : Type*} [ring R] [ring S] (f : R →+* S) (p : polynomial R) (i : ℤ) : (p.map f).eval i = f (p.eval i) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ -- TODO: Here we need commutativity in both `S` and `T`? variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C], refl, }, { intros p q hp hq, simp only [hp, hq, eval₂_add, g.map_add] }, { intros n a ih, simp only [eval₂_mul, eval₂_C, eval₂_X_pow, g.map_mul, g.map_pow], refl, } end end hom_eval₂ end semiring section comm_semiring section eval variables [comm_semiring R] {p q : polynomial R} {x : R} lemma eval₂_comp [comm_semiring S] (f : R →+* S) {x : S} : eval₂ f x (p.comp q) = eval₂ f (eval₂ f x q) p := by rw [comp, p.as_sum_range]; simp [eval₂_finset_sum, eval₂_pow] @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ @[simp] lemma eval_comp : (p.comp q).eval x = p.eval (q.eval x) := begin apply polynomial.induction_on' p, { intros r s hr hs, simp [add_comp, hr, hs], }, { intros n a, simp, } end instance comp.is_semiring_hom : is_semiring_hom (λ q : polynomial R, q.comp p) := by unfold comp; apply_instance lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] /-- Polynomial evaluation commutes with finset.prod -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → polynomial R) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := begin classical, apply finset.induction_on s, { simp only [finset.prod_empty, eval_one] }, { intros j s hj hpj, have h0 : ∏ i in insert j s, eval x (p i) = (eval x (p j)) * ∏ i in s, eval x (p i), { apply finset.prod_insert hj }, rw [h0, ← hpj, finset.prod_insert hj, eval_mul] }, end end eval section map variables [comm_semiring R] [comm_semiring S] (f : R →+* S) lemma map_multiset_prod (m : multiset (polynomial R)) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (monoid_hom.of (map f)) lemma map_prod {ι : Type*} (g : ι → polynomial R) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := eq.symm $ prod_hom _ _ lemma support_map_subset (p : polynomial R) : (map f p).support ⊆ p.support := begin intros x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f, end end map end comm_semiring section ring variables [ring R] {p q r : polynomial R} lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b instance map.is_ring_hom {S} [ring S] (f : R →+* S) : is_ring_hom (map f) := by apply is_ring_hom.of_semiring @[simp] lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := (ring_hom.of (map f)).map_int_cast n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : polynomial R).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ @[simp] lemma cast_int_comp (i : ℤ) : comp (i : polynomial R) p = i := by cases i; simp end ring section comm_ring variables [comm_ring R] {p q : polynomial R} instance eval₂.is_ring_hom {S} [comm_ring S] (f : R →+* S) {x : S} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _ end comm_ring end polynomial
a831cb05c1d18f1ec895603ad517f313fd7b14bf
54deab7025df5d2df4573383df7e1e5497b7a2c2
/data/list/sort.lean
4a1bb9136e75317b61cc7e43db8bb65390356cbf
[ "Apache-2.0" ]
permissive
HGldJ1966/mathlib
f8daac93a5b4ae805cfb0ecebac21a9ce9469009
c5c5b504b918a6c5e91e372ee29ed754b0513e85
refs/heads/master
1,611,340,395,683
1,503,040,489,000
1,503,040,489,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,792
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Insertion sort and merge sort. -/ import data.list.perm namespace list section sorted universe variable uu variables {α : Type uu} (r : α → α → Prop) def sorted : list α → Prop | [] := true | (a :: l) := sorted l ∧ ∀ b ∈ l, r a b theorem sorted_nil : sorted r nil := trivial theorem sorted_singleton (a : α) : sorted r [a] := ⟨sorted_nil r, λ b h, absurd h (not_mem_nil b)⟩ theorem sorted_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : sorted r l := h.left theorem forall_mem_rel_of_sorted_cons {a : α} {l : list α} (h : sorted r (a :: l)) : ∀ b ∈ l, r a b := h.right theorem sorted_cons {a : α} {l : list α} (h₁ : sorted r l) (h₂ : ∀ b ∈ l, r a b) : sorted r (a :: l) := ⟨h₁, h₂⟩ end sorted /- sorting procedures -/ section sort universe variable uu parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix `≼` : 50 := r /- insertion sort -/ section insertion_sort def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: b :: l else b :: ordered_insert l --@[simp] theorem ordered_insert_nil (a : α) : ordered_insert a [] = [a] := rfl --@[simp] theorem ordered_insert_cons (a b : α) (l : list α) : -- ordered_insert a (b :: l) = if a ≼ b then a :: (b :: l) else b :: ordered_insert a l := --rfl def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert b (insertion_sort l) --attribute [simp] insertion_sort.equations.eqn_1 insertion_sort.equations.eqn_2 section correctness parameter [deceqα : decidable_eq α] include deceqα open perm theorem perm_ordered_insert (a) : ∀ l : list α, ordered_insert a l ~ a :: l | [] := perm.refl _ | (b :: l) := by simp [ordered_insert]; by_cases a ≼ b; simp [h]; exact (perm.skip _ (perm_ordered_insert l)).trans (perm.swap _ _ _) theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l | [] := perm.nil | (b :: l) := by simp [insertion_sort]; exact (perm_ordered_insert _ _ _).trans (perm.skip b (perm_insertion_sort l)) section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l) | [] h := sorted_singleton r a | (b :: l) h := begin simp [ordered_insert]; by_cases a ≼ b with h'; simp [h'], { rw [sorted], refine ⟨h, λ b' bm, _⟩, simp at bm, cases bm with be bm, { subst b', exact h' }, { exact transr h' (h.right _ bm) } }, { rw [sorted], refine ⟨sorted_ordered_insert l h.left, λ b' bm, _⟩, have bm := mem_of_perm (perm_ordered_insert _ _ _) bm, simp at bm, cases bm with be bm, { subst b', exact (totr _ _).resolve_left h' }, { exact h.right _ bm } } end theorem sorted_insert_sort : ∀ l, sorted r (insertion_sort l) | [] := sorted_nil r | (a :: l) := sorted_ordered_insert totr transr a _ (sorted_insert_sort l) end total_and_transitive end correctness end insertion_sort /- merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation def split : list α → list α × list α | [] := ([], []) | (a :: l) := let (l₁, l₂) := split l in (a :: l₂, l₁) attribute [simp] split theorem split_cons_of_eq (a : α) {l l₁ l₂ : list α} (h : split l = (l₁, l₂)) : split (a :: l) = (a :: l₂, l₁) := by rw [split, h]; refl theorem length_split_le : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l | [] ._ ._ rfl := ⟨nat.le_refl 0, nat.le_refl 0⟩ | (a::l) l₁' l₂' h := begin ginduction split l with e l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, subst l₁', subst l₂', cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ h₂, nat.le_succ_of_le h₁⟩ end theorem length_split_lt {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : length l₁ < length (a::b::l) ∧ length l₂ < length (a::b::l) := begin ginduction split l with e l₁' l₂', injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h, subst l₁, subst l₂, cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ (nat.succ_le_succ h₁), nat.succ_le_succ (nat.succ_le_succ h₂)⟩ end theorem perm_split : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂ | [] ._ ._ rfl := perm.refl _ | (a::l) l₁' l₂' h := begin ginduction split l with e l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, subst l₁', subst l₂', exact perm.skip a ((perm_split e).trans perm.perm_app_comm), end def merge : list α → list α → list α | [] l' := l' | l [] := l | (a :: l) (b :: l') := if a ≼ b then a :: merge l (b :: l') else b :: merge (a :: l) l' include r def merge_sort : list α → list α | [] := [] | [a] := [a] | (a::b::l) := begin ginduction split (a::b::l) with e l₁ l₂, cases length_split_lt e with h₁ h₂, exact merge r (merge_sort l₁) (merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_cons_cons {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : merge_sort (a::b::l) = merge (merge_sort l₁) (merge_sort l₂) := begin simp [merge_sort, h], dsimp, have : ∀ (L : list α) h1, @@and.rec (λ a a (_ : length l₁ < length l + 1 + 1 ∧ length l₂ < length l + 1 + 1), L) h1 h1 = L, { intros, cases h1, refl }, apply this end section correctness parameter [deceqα : decidable_eq α] include deceqα theorem perm_merge : ∀ (l l' : list α), merge l l' ~ l ++ l' | [] [] := perm.nil | [] (b :: l') := by simp [merge] | (a :: l) [] := by simp [merge] | (a :: l) (b :: l') := by simp [merge]; by_cases a ≼ b; simp [h]; [exact perm.skip _ (perm_merge _ _), exact (perm.skip _ (perm_merge _ _)).trans (perm.trans (perm.swap _ _ _) (perm.skip _ (perm.perm_middle _ _ _)))] theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l | [] := perm.refl _ | [a] := perm.refl _ | (a::b::l) := begin ginduction split (a::b::l) with e l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], apply (perm_merge r _ _).trans, exact (perm.perm_app (perm_merge_sort l₁) (perm_merge_sort l₂)).trans (perm_split e).symm end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } section total_and_transitive variables (totr : total r) (transr : transitive r) include totr transr theorem sorted_merge : ∀ {l l' : list α}, sorted r l → sorted r l' → sorted r (merge l l') | [] [] h₁ h₂ := trivial | [] (b :: l') h₁ h₂ := by simp [merge]; exact h₂ | (a :: l) [] h₁ h₂ := by simp [merge]; exact h₁ | (a :: l) (b :: l') h₁ h₂ := begin simp [merge]; by_cases a ≼ b; simp [h], { refine ⟨sorted_merge h₁.left h₂, λ b' bm, _⟩, have bm := perm.mem_of_perm (perm_merge _ _ _) bm, simp at bm, cases bm with be bm, { subst b', assumption }, cases bm with bl bl', { exact h₁.right _ bl }, { exact transr h (h₂.right _ bl') } }, { refine ⟨sorted_merge h₁ h₂.left, λ b' bm, _⟩, have bm := perm.mem_of_perm (perm_merge _ _ _) bm, simp at bm, have ba : b ≼ a := (totr _ _).resolve_left h, cases bm with be bm, { subst b', assumption }, cases bm with bl bl', { exact transr ba (h₁.right _ bl) }, { exact h₂.right _ bl' } } end theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l) | [] := sorted_nil _ | [a] := sorted_singleton _ _ | (a::b::l) := begin ginduction split (a::b::l) with e l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], exact sorted_merge r totr transr (sorted_merge_sort l₁) (sorted_merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } end total_and_transitive end correctness end merge_sort end sort /- try them out! -/ --#eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --#eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
9d2e2ab5008f92291cfefcb81be783a7327bd5a0
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/cycle.lean
259637ee19d6430a18f8ae5b21acf62a6b404248
[ "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
29,987
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.multiset.sort import data.fintype.list import data.list.rotate /-! # Cycles of a list Lists have an equivalence relation of whether they are rotational permutations of one another. This relation is defined as `is_rotated`. Based on this, we define the quotient of lists by the rotation relation, called `cycle`. We also define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ namespace list variables {α : Type*} [decidable_eq α] /-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/ def next_or : Π (xs : list α) (x default : α), α | [] x default := default | [y] x default := default -- Handles the not-found and the wraparound case | (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default @[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl @[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl @[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) : next_or (x :: y :: xs) x d = y := if_pos rfl lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) : next_or (y :: xs) x d = next_or xs x d := begin cases xs with z zs, { refl }, { exact if_neg h } end /-- `next_or` does not depend on the default value, if the next value appears. -/ lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α) (x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) : next_or xs x d = next_or xs x d' := begin induction xs with y ys IH, { cases x_mem }, cases ys with z zs, { simp at x_mem x_ne, contradiction }, by_cases h : x = y, { rw [h, next_or_self_cons_cons, next_or_self_cons_cons] }, { rw [next_or, next_or, IH]; simpa [h] using x_mem } end lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) : x ∈ xs := begin induction xs with y ys IH, { simpa using h }, cases ys with z zs, { simpa using h }, { by_cases hx : x = y, { simp [hx] }, { rw [next_or_cons_of_ne _ _ _ _ hx] at h, simpa [hx] using IH h } } end lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) : next_or (xs ++ [x]) x d = d := begin induction xs with z zs IH, { simp }, { obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h), rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] } end lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) : next_or xs x d ∈ xs := begin revert hd, suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs', { exact this xs (λ _, id) }, intros xs' hxs' hd, induction xs with y ys ih, { exact hd }, cases ys with z zs, { exact hd }, rw next_or, split_ifs with h, { exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) }, { exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) }, end /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. For example: * `next [1, 2, 3] 2 _ = 3` * `next [1, 2, 3] 3 _ = 1` * `next [1, 2, 3, 2, 4] 2 _ = 3` * `next [1, 2, 3, 2] 2 _ = 3` * `next [1, 1, 2, 3, 2] 1 _ = 1` -/ def next (l : list α) (x : α) (h : x ∈ l) : α := next_or l x (l.nth_le 0 (length_pos_of_mem h)) /-- Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. * `prev [1, 2, 3] 2 _ = 1` * `prev [1, 2, 3] 1 _ = 3` * `prev [1, 2, 3, 2, 4] 2 _ = 1` * `prev [1, 2, 3, 4, 2] 2 _ = 1` * `prev [1, 1, 2] 1 _ = 2` -/ def prev : Π (l : list α) (x : α) (h : x ∈ l), α | [] _ h := by simpa using h | [y] _ _ := y | (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else if x = z then y else prev (z :: xs) x (by simpa [hx] using h) variables (l : list α) (x : α) (h : x ∈ l) @[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) : next [y] x h = y := rfl @[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) : prev [y] x h = y := rfl lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : next (y :: z :: l) x h = z := by rw [next, next_or, if_pos hx] @[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : next (x :: z :: l) x h = z := next_cons_cons_eq' l x x z h rfl lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x ≠ last (y :: l) (cons_ne_nil _ _)) : next (y :: l) x h = next l x (by simpa [hy] using h) := begin rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne], { rwa last_cons at hx }, { simpa [hy] using h } end lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l) (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) : next (y :: l ++ [x]) x h = y := begin rw [next, next_or_concat], { refl }, { simp [hy, hx] } end lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y) (hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) : next (y :: l) x h = y := begin rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat], subst hx, intro H, obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H, { simpa [init_eq_take, nth_le_take', hy.symm] using hk' }, suffices : k.succ = l.length, { simpa [this] using hk }, cases l with hd tl, { simpa using hk }, { rw nodup_iff_nth_le_inj at hl, rw [length, nat.succ_inj'], apply hl, simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' } end lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) : prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) := begin cases l; simp [prev, hx] end @[simp] lemma prev_last_cons (h : x ∈ (x :: l)) : prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) := prev_last_cons' l x x h rfl lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) : prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx] @[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) : prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) := prev_cons_cons_eq' l x x z h rfl lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) : prev (y :: z :: l) x h = y := begin cases l, { simp [prev, hy, hz] }, { rw [prev, dif_neg hy, if_pos hz] } end lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) : prev (y :: x :: l) x h = y := prev_cons_cons_of_ne' _ _ _ _ _ hy rfl lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) : prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := begin cases l, { simpa [hy, hz] using h }, { rw [prev, dif_neg hy, if_neg hz] } end include h lemma next_mem : l.next x h ∈ l := next_or_mem (nth_le_mem _ _ _) lemma prev_mem : l.prev x h ∈ l := begin cases l with hd tl, { simpa using h }, induction tl with hd' tl hl generalizing hd, { simp }, { by_cases hx : x = hd, { simp only [hx, prev_cons_cons_eq], exact mem_cons_of_mem _ (last_mem _) }, { rw [prev, dif_neg hx], split_ifs with hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ (hl _ _) } } } end lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing x n, { simp }, { cases n, { simp }, { have hn' : n.succ ≤ l.length.succ, { refine nat.succ_le_of_lt _, simpa [nat.succ_lt_succ_iff] using hn }, have hx': (x :: y :: l).nth_le n.succ hn ≠ x, { intro H, suffices : n.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, rcases hn'.eq_or_lt with hn''|hn'', { rw [next_last_cons], { simp [hn''] }, { exact hx' }, { simp [last_eq_nth_le, hn''] }, { exact h.of_cons } }, { have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' , rw [next_ne_head_ne_last _ _ _ _ hx'], { simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)), hl _ _ h.of_cons, nat.mod_eq_of_lt (nat.succ_lt_succ this)] }, { rw last_eq_nth_le, intro H, suffices : n.succ = l.length.succ, { exact absurd hn'' this.ge.not_lt }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn _ _, { simp }, { simpa using H } } } } } end lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) : prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases l with x l, { simpa using hn }, induction l with y l hl generalizing n x, { simp }, { rcases n with _|_|n, { simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] }, { simp only [mem_cons_iff, nodup_cons] at h, push_neg at h, simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] }, { rw [prev_ne_cons_cons], { convert hl _ _ h.of_cons _ using 1, have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk), { intros, simpa }, rw [this], congr, simp only [nat.add_succ_sub_one, add_zero, length], simp only [length, nat.succ_lt_succ_iff] at hn, set k := l.length, rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k, nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt], { exact nat.lt_succ_of_lt hn }, { exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } }, { intro H, suffices : n.succ.succ = 0, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn nat.succ_pos' _, simpa using H }, { intro H, suffices : n.succ.succ = 1, { simpa }, rw nodup_iff_nth_le_inj at h, refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _, simpa using H } } } end lemma pmap_next_eq_rotate_one (h : nodup l) : l.pmap l.next (λ _ h, h) = l.rotate 1 := begin apply list.ext_le, { simp }, { intros, rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] } end lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) : l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) := begin apply list.ext_le, { simp }, { intros n hn hn', rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] } end lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l (next l x hx) (next_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l (prev l x hx) (prev_mem _ _ _) = x := begin obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod], cases l with hd tl, { simp }, { have : n < 1 + tl.length := by simpa [add_comm] using hn, simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] } end lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : prev l.reverse x (mem_reverse.mpr hx) = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, have lpos : 0 < l.length := k.zero_le.trans_lt hk, have key : l.length - 1 - k < l.length := (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos'), rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk), simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h], rw ←nth_le_pmap l.reverse.prev (λ _ h, h), { simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse, length_reverse, nat.mod_eq_of_lt (tsub_lt_self lpos nat.succ_pos'), tsub_tsub_cancel_of_le (nat.succ_le_of_lt lpos)], rw ←nth_le_reverse, { simp [tsub_tsub_cancel_of_le (nat.le_pred_of_lt hk)] }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } }, { simpa using (nat.sub_le _ _).trans_lt (tsub_lt_self lpos nat.succ_pos') } end lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) : next l.reverse x (mem_reverse.mpr hx) = prev l x hx := begin convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm, exact (reverse_reverse l).symm end lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.next x hx = l'.next x (h.mem_iff.mp hx) := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, obtain ⟨n, rfl⟩ := id h, rw [next_nth_le _ hn], simp_rw ←nth_le_rotate' _ n k, rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n], simp [add_assoc] end lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) : l.prev x hx = l'.prev x (h.mem_iff.mp hx) := begin rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)], exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _ end end list open list /-- `cycle α` is the quotient of `list α` by cyclic permutation. Duplicates are allowed. -/ def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α) namespace cycle variables {α : Type*} instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩ @[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) := @quotient.eq _ (is_rotated.setoid _) _ _ @[simp] lemma mk_eq_coe (l : list α) : quot.mk _ l = (l : cycle α) := rfl @[simp] lemma mk'_eq_coe (l : list α) : quotient.mk' l = (l : cycle α) := rfl lemma coe_cons_eq_coe_append (l : list α) (a : α) : (↑(a :: l) : cycle α) = ↑(l ++ [a]) := quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩ /-- The unique empty cycle. -/ def nil : cycle α := ([] : list α) @[simp] lemma coe_nil : ↑([] : list α) = @nil α := rfl @[simp] lemma coe_eq_nil (l : list α) : (l : cycle α) = nil ↔ l = [] := coe_eq_coe.trans is_rotated_nil_iff /-- For consistency with `list.has_emptyc`. -/ instance : has_emptyc (cycle α) := ⟨nil⟩ @[simp] lemma empty_eq : ∅ = @nil α := rfl instance : inhabited (cycle α) := ⟨nil⟩ /-- An induction principle for `cycle`. Use as `induction s using cycle.induction_on`. -/ @[elab_as_eliminator] lemma induction_on {C : cycle α → Prop} (s : cycle α) (H0 : C nil) (HI : ∀ a (l : list α), C ↑l → C ↑(a :: l)) : C s := quotient.induction_on' s $ λ l, by { apply list.rec_on l; simp, assumption' } /-- For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/ def mem (a : α) (s : cycle α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ e, propext $ e.mem_iff) instance : has_mem α (cycle α) := ⟨mem⟩ @[simp] lemma mem_coe_iff {a : α} {l : list α} : a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl @[simp] lemma not_mem_nil : ∀ a, a ∉ @nil α := not_mem_nil instance [decidable_eq α] : decidable_eq (cycle α) := λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂, decidable_of_iff' _ quotient.eq') instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) := quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l) /-- Reverse a `s : cycle α` by reversing the underlying `list`. -/ def reverse (s : cycle α) : cycle α := quot.map reverse (λ l₁ l₂, is_rotated.reverse) s @[simp] lemma reverse_coe (l : list α) : (l : cycle α).reverse = l.reverse := rfl @[simp] lemma mem_reverse_iff {a : α} {s : cycle α} : a ∈ s.reverse ↔ a ∈ s := quot.induction_on s (λ _, mem_reverse) @[simp] lemma reverse_reverse (s : cycle α) : s.reverse.reverse = s := quot.induction_on s (λ _, by simp) @[simp] lemma reverse_nil : nil.reverse = @nil α := rfl /-- The length of the `s : cycle α`, which is the number of elements, counting duplicates. -/ def length (s : cycle α) : ℕ := quot.lift_on s length (λ l₁ l₂ e, e.perm.length_eq) @[simp] lemma length_coe (l : list α) : length (l : cycle α) = l.length := rfl @[simp] lemma length_nil : length (@nil α) = 0 := rfl @[simp] lemma length_reverse (s : cycle α) : s.reverse.length = s.length := quot.induction_on s length_reverse /-- A `s : cycle α` that is at most one element. -/ def subsingleton (s : cycle α) : Prop := s.length ≤ 1 lemma subsingleton_nil : subsingleton (@nil α) := zero_le_one lemma length_subsingleton_iff {s : cycle α} : subsingleton s ↔ length s ≤ 1 := iff.rfl @[simp] lemma subsingleton_reverse_iff {s : cycle α} : s.reverse.subsingleton ↔ s.subsingleton := by simp [length_subsingleton_iff] lemma subsingleton.congr {s : cycle α} (h : subsingleton s) : ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y := begin induction s using quot.induction_on with l, simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff, length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h, rcases h with rfl|⟨z, rfl⟩; simp end /-- A `s : cycle α` that is made up of at least two unique elements. -/ def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s @[simp] lemma nontrivial_coe_nodup_iff {l : list α} (hl : l.nodup) : nontrivial (l : cycle α) ↔ 2 ≤ l.length := begin rw nontrivial, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simp }, { simp }, { simp only [mem_cons_iff, exists_prop, mem_coe_iff, list.length, ne.def, nat.succ_le_succ_iff, zero_le, iff_true], refine ⟨hd, hd', _, by simp⟩, simp only [not_or_distrib, mem_cons_iff, nodup_cons] at hl, exact hl.left.left } end @[simp] lemma nontrivial_reverse_iff {s : cycle α} : s.reverse.nontrivial ↔ s.nontrivial := by simp [nontrivial] lemma length_nontrivial {s : cycle α} (h : nontrivial s) : 2 ≤ length s := begin obtain ⟨x, y, hxy, hx, hy⟩ := h, induction s using quot.induction_on with l, rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩), { simpa using hx }, { simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy, simpa [hx, hy] using hxy }, { simp [bit0] } end /-- The `s : cycle α` contains no duplicates. -/ def nodup (s : cycle α) : Prop := quot.lift_on s nodup (λ l₁ l₂ e, propext $ e.nodup_iff) @[simp] lemma nodup_nil : nodup (@nil α) := nodup_nil @[simp] lemma nodup_coe_iff {l : list α} : nodup (l : cycle α) ↔ l.nodup := iff.rfl @[simp] lemma nodup_reverse_iff {s : cycle α} : s.reverse.nodup ↔ s.nodup := quot.induction_on s (λ _, nodup_reverse) lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) : nodup s := begin induction s using quot.induction_on with l, cases l with hd tl, { simp }, { have : tl = [] := by simpa [subsingleton, length_eq_zero] using h, simp [this] } end lemma nodup.nontrivial_iff {s : cycle α} (h : nodup s) : nontrivial s ↔ ¬ subsingleton s := begin rw length_subsingleton_iff, induction s using quotient.induction_on', simp only [mk'_eq_coe, nodup_coe_iff] at h, simp [h, nat.succ_le_iff] end /-- The `s : cycle α` as a `multiset α`. -/ def to_multiset (s : cycle α) : multiset α := quotient.lift_on' s coe (λ l₁ l₂ h, multiset.coe_eq_coe.mpr h.perm) @[simp] lemma coe_to_multiset (l : list α) : (l : cycle α).to_multiset = l := rfl @[simp] lemma nil_to_multiset : nil.to_multiset = (0 : multiset α) := rfl @[simp] lemma card_to_multiset (s : cycle α) : s.to_multiset.card = s.length := quotient.induction_on' s (by simp) @[simp] lemma to_multiset_eq_nil {s : cycle α} : s.to_multiset = 0 ↔ s = cycle.nil := quotient.induction_on' s (by simp) /-- The lift of `list.map`. -/ def map {β : Type*} (f : α → β) : cycle α → cycle β := quotient.map' (list.map f) $ λ l₁ l₂ h, h.map _ @[simp] lemma map_nil {β : Type*} (f : α → β) : map f nil = nil := rfl @[simp] lemma map_coe {β : Type*} (f : α → β) (l : list α) : map f ↑l = list.map f l := rfl @[simp] lemma map_eq_nil {β : Type*} (f : α → β) (s : cycle α) : map f s = nil ↔ s = nil := quotient.induction_on' s (by simp) /-- The `multiset` of lists that can make the cycle. -/ def lists (s : cycle α) : multiset (list α) := quotient.lift_on' s (λ l, (l.cyclic_permutations : multiset (list α))) $ λ l₁ l₂ h, by simpa using h.cyclic_permutations.perm @[simp] lemma lists_coe (l : list α) : lists (l : cycle α) = ↑l.cyclic_permutations := rfl @[simp] lemma mem_lists_iff_coe_eq {s : cycle α} {l : list α} : l ∈ s.lists ↔ (l : cycle α) = s := quotient.induction_on' s $ λ l, by { rw [lists, quotient.lift_on'_mk'], simp } @[simp] lemma lists_nil : lists (@nil α) = [([] : list α)] := by rw [nil, lists_coe, cyclic_permutations_nil] section decidable variable [decidable_eq α] /-- Auxiliary decidability algorithm for lists that contain at least two unique elements. -/ def decidable_nontrivial_coe : Π (l : list α), decidable (nontrivial (l : cycle α)) | [] := is_false (by simp [nontrivial]) | [x] := is_false (by simp [nontrivial]) | (x :: y :: l) := if h : x = y then @decidable_of_iff' _ (nontrivial ((x :: l) : cycle α)) (by simp [h, nontrivial]) (decidable_nontrivial_coe (x :: l)) else is_true ⟨x, y, h, by simp, by simp⟩ instance {s : cycle α} : decidable (nontrivial s) := quot.rec_on_subsingleton s decidable_nontrivial_coe instance {s : cycle α} : decidable (nodup s) := quot.rec_on_subsingleton s list.nodup_decidable instance fintype_nodup_cycle [fintype α] : fintype {s : cycle α // s.nodup} := fintype.of_surjective (λ (l : {l : list α // l.nodup}), ⟨l.val, by simpa using l.prop⟩) (λ ⟨s, hs⟩, by { induction s using quotient.induction_on', exact ⟨⟨s, hs⟩, by simp⟩ }) instance fintype_nodup_nontrivial_cycle [fintype α] : fintype {s : cycle α // s.nodup ∧ s.nontrivial} := fintype.subtype (((finset.univ : finset {s : cycle α // s.nodup}).map (function.embedding.subtype _)).filter cycle.nontrivial) (by simp) /-- The `s : cycle α` as a `finset α`. -/ def to_finset (s : cycle α) : finset α := s.to_multiset.to_finset @[simp] theorem to_finset_to_multiset (s : cycle α) : s.to_multiset.to_finset = s.to_finset := rfl @[simp] lemma coe_to_finset (l : list α) : (l : cycle α).to_finset = l.to_finset := rfl @[simp] lemma nil_to_finset : (@nil α).to_finset = ∅ := rfl @[simp] lemma to_finset_eq_nil {s : cycle α} : s.to_finset = ∅ ↔ s = cycle.nil := quotient.induction_on' s (by simp) /-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/ def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, next l x hx) (λ l₁ l₂ h, function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _))))) /-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/ def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α := λ s, quot.hrec_on s (λ l hn x hx, prev l x hx) (λ l₁ l₂ h, function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl (λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff)) (λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _))))) @[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx := (quotient.induction_on' s prev_reverse_eq_next) hs x hx @[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by simp [←prev_reverse_eq_next] @[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs x hx ∈ s := by { induction s using quot.induction_on, apply next_mem } lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs x hx ∈ s := by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], apply next_mem } @[simp] lemma prev_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x := (quotient.induction_on' s prev_next) hs x hx @[simp] lemma next_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) : s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x := (quotient.induction_on' s next_prev) hs x hx end decidable /-- We define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representatble types. For example, the cycle `(2 1 4 3)` will be shown as `c[1, 4, 3, 2]`. The representation of the cycle sorts the elements by the string value of the underlying element. This representation also supports cycles that can contain duplicates. -/ instance [has_repr α] : has_repr (cycle α) := ⟨λ s, "c[" ++ string.intercalate ", " ((s.map repr).lists.sort (≤)).head ++ "]"⟩ /-- `chain R s` means that `R` holds between adjacent elements of `s`. `chain R ([a, b, c] : cycle α) ↔ R a b ∧ R b c ∧ R c a` -/ def chain (r : α → α → Prop) (c : cycle α) : Prop := quotient.lift_on' c (λ l, match l with | [] := true | (a :: m) := chain r a (m ++ [a]) end) $ λ a b hab, propext $ begin cases a with a l; cases b with b m, { refl }, { have := is_rotated_nil_iff'.1 hab, contradiction }, { have := is_rotated_nil_iff.1 hab, contradiction }, { unfold chain._match_1, cases hab with n hn, induction n with d hd generalizing a b l m, { simp only [rotate_zero] at hn, rw [hn.1, hn.2] }, { cases l with c s, { simp only [rotate_singleton] at hn, rw [hn.1, hn.2] }, { rw [nat.succ_eq_one_add, ←rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at hn, rw [←hd c _ _ _ hn], simp [and.comm] } } } end @[simp] lemma chain.nil (r : α → α → Prop) : cycle.chain r (@nil α) := by trivial @[simp] lemma chain_coe_cons (r : α → α → Prop) (a : α) (l : list α) : chain r (a :: l) ↔ list.chain r a (l ++ [a]) := iff.rfl @[simp] lemma chain_singleton (r : α → α → Prop) (a : α) : chain r [a] ↔ r a a := by rw [chain_coe_cons, nil_append, chain_singleton] lemma chain_ne_nil (r : α → α → Prop) {l : list α} : Π hl : l ≠ [], chain r l ↔ list.chain r (last l hl) l := begin apply l.reverse_rec_on, exact λ hm, hm.irrefl.elim, intros m a H _, rw [←coe_cons_eq_coe_append, chain_coe_cons, last_append_singleton] end lemma chain_map {β : Type*} {r : α → α → Prop} (f : β → α) {s : cycle β} : chain r (s.map f) ↔ chain (λ a b, r (f a) (f b)) s := quotient.induction_on' s $ λ l, begin cases l with a l, refl, convert list.chain_map f, rw map_append f l [a], refl end variables {r : α → α → Prop} {s : cycle α} theorem chain_of_pairwise : (∀ (a ∈ s) (b ∈ s), r a b) → chain r s := begin induction s using cycle.induction_on with a l _, exact λ _, cycle.chain.nil r, intro hs, have Ha : a ∈ ((a :: l) : cycle α) := by simp, have Hl : ∀ {b} (hb : b ∈ l), b ∈ ((a :: l) : cycle α) := λ b hb, by simp [hb], rw cycle.chain_coe_cons, apply pairwise.chain, rw pairwise_cons, refine ⟨λ b hb, _, pairwise_append.2 ⟨pairwise_of_forall_mem_list (λ b hb c hc, hs b (Hl hb) c (Hl hc)), pairwise_singleton r a, λ b hb c hc, _⟩⟩, { rw mem_append at hb, cases hb, { exact hs a Ha b (Hl hb) }, { rw mem_singleton at hb, rw hb, exact hs a Ha a Ha } }, { rw mem_singleton at hc, rw hc, exact hs b (Hl hb) a Ha } end theorem chain_iff_pairwise (hr : transitive r) : chain r s ↔ ∀ (a ∈ s) (b ∈ s), r a b := ⟨begin induction s using cycle.induction_on with a l _, exact λ _ b hb, hb.elim, intros hs b hb c hc, rw [cycle.chain_coe_cons, chain_iff_pairwise hr] at hs, simp only [pairwise_append, pairwise_cons, mem_append, mem_singleton, list.not_mem_nil, forall_false_left, implies_true_iff, pairwise.nil, forall_eq, true_and] at hs, simp only [mem_coe_iff, mem_cons_iff] at hb hc, rcases hb with rfl | hb; rcases hc with rfl | hc, { exact hs.1 c (or.inr rfl) }, { exact hs.1 c (or.inl hc) }, { exact hs.2.2 b hb }, { exact hr (hs.2.2 b hb) (hs.1 c (or.inl hc)) } end, cycle.chain_of_pairwise⟩ theorem forall_eq_of_chain (hr : transitive r) (hr' : anti_symmetric r) (hs : chain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : a = b := by { rw chain_iff_pairwise hr at hs, exact hr' (hs a ha b hb) (hs b hb a ha) } end cycle
15304ffed0c3705c0c6e5fef31b41997a1d95c55
43390109ab88557e6090f3245c47479c123ee500
/src/M3P14/lemmas_for_prime_int.lean
1d7f749ebb80f639e591d90712579e94640220ff
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,116
lean
import data.int.basic import data.int.modeq import data.int.order import algebra.group_power import tactic.ring import chris_hughes_various.zmod open nat --#check int.le --theorem l_to_le {a b : ℤ} (hab : a < b) : a ≤ b := begin --unfold has_le.le, --unfold int.le, --have h1 : b < b+1, by lt_succ_self b, --end definition prime_int (p : ℤ) := nat.prime(int.nat_abs p) theorem prime_int_to_nat {p : ℤ} (h : prime_int p) : prime (int.nat_abs p) := sorry definition quadratic_res (a n : ℤ) := ∃ x : ℤ, a ≡ x^2 [ZMOD (int.nat_abs n)] --definition quadratic_res' (p : ℤ) (hp : prime_int_int p ∧ p ≠ 2) (a n : zmod p) := ∃ x : ℕ, a ≡ x^2 [ZMOD n] attribute [instance, priority 0] classical.prop_decidable noncomputable definition legendre_sym {p : ℤ} (a : ℤ) (H1 : prime_int p ∧ p ≠ 2) : ℤ := if quadratic_res a p ∧ ¬ ((p : ℤ) ∣ a) then 1 else if ¬ quadratic_res a p then -1 else 0 -- lemmas lemma legendre_strong_mul {p : ℤ} (a b : ℤ) (H1 : prime_int p ∧ p ≠ 2) : legendre_sym (a*b) H1 = (legendre_sym a H1) * (legendre_sym b H1) := sorry lemma if_cong_legendre_eq {p : ℤ} (a b : ℤ) (H1 : prime_int p ∧ p ≠ 2) : a % p = b → legendre_sym a H1 = legendre_sym b H1 := sorry lemma euler_criterion {p : ℤ} (a : ℤ) (H1 : prime_int p ∧ p ≠ 2) : legendre_sym a H1 = a^(int.nat_abs p-1) % p := sorry theorem legendre_sym_one_implies_quadratic_res {p : ℤ} (a : ℤ)(H1 : prime_int p ∧ p ≠ 2): legendre_sym a H1 = 1 → quadratic_res a p := begin intro h, unfold legendre_sym at h, split_ifs at h, exact h_1.1, exfalso, revert h, norm_num, revert h, norm_num, end theorem minus_one_quad_res_of_p {p : ℤ} (hp : prime_int p ∧ p ≠ 2) : (p ≡ 1 [ZMOD 4] ↔ (legendre_sym (-1: ℤ) hp) = 1) ∧ (p ≡ 3 [ZMOD 4] ↔ legendre_sym (-1 : ℤ) hp = (-1 : ℤ)) := sorry definition is_sum_of_two_squares (n : ℕ) := ∃ x y : ℤ, (n : ℤ) = x ^ 2 + y ^ 2 theorem is_sum_of_two_squares_mul (m n : ℕ) : is_sum_of_two_squares m ∧ is_sum_of_two_squares n → is_sum_of_two_squares (m * n) := begin intro h, unfold is_sum_of_two_squares, unfold is_sum_of_two_squares at h, rcases h with ⟨⟨a, b, hab⟩, ⟨c, d, hcd⟩⟩, existsi [a * c - b * d, a * d + b * c], rw int.coe_nat_mul, rw hab, rw hcd, ring, end theorem one_mod_four_prime (p : ℤ)(h : prime_int p ∧ p ≠ 2) : p ^ 2 ≡ 1 [ZMOD 4] := sorry theorem fermat_descent (p : ℤ)(h : prime_int p ∧ p ≠ 2) : ∃ a b r : ℤ, (a ^ 2 + b ^ 2 = p * r) ∧ (1 < r) ∧ (r < p) → ∃ x y r' : ℤ, (1 ≤ r') ∧ (r'< r) ∧ (x ^ 2 + y ^ 2 = p * r') := begin sorry end theorem fermat_two_square (p : ℤ)(h : prime_int p ∧ p ≠ 2)(H: p ≥ 0) : p ≡ 1 [ZMOD 4] → is_sum_of_two_squares (int.nat_abs p) := begin intro hpp, have b1 := (minus_one_quad_res_of_p h).1.1, have b2 := b1 hpp, have b3 := legendre_sym_one_implies_quadratic_res (-1) h b2, unfold quadratic_res at b3, rcases b3 with x, let y := x % ↑(int.nat_abs p), have b3_hh : -1 ≡ y ^ 2 [ZMOD ↑(int.nat_abs p)], begin haveI : pos_nat p.nat_abs := sorry, rw ← zmod.eq_iff_modeq_int, rw ← zmod.eq_iff_modeq_int at b3_h, have : x ≡ y [ZMOD ↑(p.nat_abs)], exact (int.mod_mod x p.nat_abs).symm, rw ← zmod.eq_iff_modeq_int at this, rw int.cast_pow at b3_h, rw int.cast_pow, exact eq.subst this b3_h, end, have b4 : 1 ≡ 1 [ZMOD ↑(int.nat_abs p)], by refl, have b5 := int.modeq.modeq_add b3_hh b4, have b6 : (-1 :ℤ) + 1 = 0, by simp, rw b6 at b5, have b7 := int.modeq.symm b5, rw int.nat_abs_of_nonneg at b7, have b8:= int.modeq.modeq_zero_iff.1 b7, have b9 := exists_eq_mul_right_of_dvd b8, rcases b9 with r, have c5 : (int.nat_abs p : ℤ) ≠ 0, begin by_contradiction, simp at a, have c6 := int.eq_zero_of_nat_abs_eq_zero a, have c7 : 0 ≡ 1 [ZMOD 4], from eq.subst c6 hpp, rw int.modeq.modeq_iff_dvd at c7, revert c7, simp, norm_num, end, have c : (1 ≤ r) ∧ (r < p), begin split, have c1 : 0 < y ^ 2 + 1, { rw int.lt_add_one_iff, exact pow_two_nonneg y, }, have c2 : p * r > 0, from eq.subst b9_h c1, have c3 := pos_of_mul_pos_left c2 H, exact c3, have c4 : y ≥ 0 ∧ y ≤ p - 1, split, have c8 : x % ↑(int.nat_abs p) ≥ 0, from int.mod_nonneg x c5, exact c8, rw ← int.lt_add_one_iff, simp, have d1 := int.mod_lt x c5, conv at d1 {to_rhs, rw int.nat_abs_of_nonneg H}, rw abs_of_nonneg H at d1, exact d1, have d2 : y ^ 2 ≤ (p-1) ^ 2 , sorry, have d3 : y ^ 2 + 1 ≤ (p-1) ^ 2 + 1, sorry, have d4 : p * r ≤ (p-1) ^ 2 + 1, from eq.subst b9_h d3, rw mul_comm at d4, have d5 : p > 0, sorry, have d6 := le_div_of_mul_le d5 d4, sorry, end, sorry, exact H, end #check abs #check int.nat_abs_of_nonneg --inductive less_than_or_equal (a : ℤ) : ℤ → Prop --| refl : less_than_or_equal a --| step : Π {b}, less_than_or_equal b → less_than_or_equal (succ b) --def le_refl : ∀ a : ℤ, a ≤ a := --less_than_or_equal.refl --lemma le_succ (n:ℤ) : n ≤ succ n := --less_than_or_equal.step (int.le_refl n) --theorem le_of_succ_le {n m : ℤ} (h : succ n ≤ m) : n ≤ m := --int.le_trans (le_succ n) h
799a6aa18bc827688a00a5522a093122b5d3864d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/conformal_groupoid.lean
6a75afe7a26f1bc4a8d88f21c8f45b5b3b12bfcc
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,189
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.calculus.conformal.normed_space import geometry.manifold.charted_space /-! # Conformal Groupoid > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the groupoid of conformal maps on normed spaces. ## Main definitions * `conformal_groupoid`: the groupoid of conformal local homeomorphisms. ## Tags conformal, groupoid -/ variables {X : Type*} [normed_add_comm_group X] [normed_space ℝ X] /-- The pregroupoid of conformal maps. -/ def conformal_pregroupoid : pregroupoid X := { property := λ f u, ∀ x, x ∈ u → conformal_at f x, comp := λ f g u v hf hg hu hv huv x hx, (hg (f x) hx.2).comp x (hf x hx.1), id_mem := λ x hx, conformal_at_id x, locality := λ f u hu h x hx, let ⟨v, h₁, h₂, h₃⟩ := h x hx in h₃ x ⟨hx, h₂⟩, congr := λ f g u hu h hf x hx, (hf x hx).congr hx hu h, } /-- The groupoid of conformal maps. -/ def conformal_groupoid : structure_groupoid X := conformal_pregroupoid.groupoid
eafd2941b2a72dd3a3ba498e7dd40c407e8d5d12
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/lie/ideal_operations.lean
c557c562c3b76587b4b0b70fc22fbb3b18f5846d
[ "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
14,349
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.submodule /-! # Ideal operations for Lie algebras Given a Lie module `M` over a Lie algebra `L`, there is a natural action of the Lie ideals of `L` on the Lie submodules of `M`. In the special case that `M = L` with the adjoint action, this provides a pairing of Lie ideals which is especially important. For example, it can be used to define solvability / nilpotency of a Lie algebra via the derived / lower-central series. ## Main definitions * `lie_submodule.has_bracket` * `lie_submodule.lie_ideal_oper_eq_linear_span` * `lie_ideal.map_bracket_le` * `lie_ideal.comap_bracket_le` ## Notation Given a Lie module `M` over a Lie algebra `L`, together with a Lie submodule `N ⊆ M` and a Lie ideal `I ⊆ L`, we introduce the notation `⁅I, N⁆` for the Lie submodule of `M` corresponding to the action defined in this file. ## Tags lie algebra, ideal operation -/ universes u v w w₁ w₂ namespace lie_submodule variables {R : Type u} {L : Type v} {M : Type w} {M₂ : Type w₁} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group M₂] [module R M₂] [lie_ring_module L M₂] [lie_module R L M₂] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) (N₂ : lie_submodule R L M₂) section lie_ideal_operations /-- Given a Lie module `M` over a Lie algebra `L`, the set of Lie ideals of `L` acts on the set of submodules of `M`. -/ instance has_bracket : has_bracket (lie_ideal R L) (lie_submodule R L M) := ⟨λ I N, lie_span R L { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m }⟩ lemma lie_ideal_oper_eq_span : ⁅I, N⁆ = lie_span R L { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m } := rfl /-- See also `lie_submodule.lie_ideal_oper_eq_linear_span'` and `lie_submodule.lie_ideal_oper_eq_tensor_map_range`. -/ lemma lie_ideal_oper_eq_linear_span : (↑⁅I, N⁆ : submodule R M) = submodule.span R { m | ∃ (x : I) (n : N), ⁅(x : L), (n : M)⁆ = m } := begin apply le_antisymm, { let s := {m : M | ∃ (x : ↥I) (n : ↥N), ⁅(x : L), (n : M)⁆ = m}, have aux : ∀ (y : L) (m' ∈ submodule.span R s), ⁅y, m'⁆ ∈ submodule.span R s, { intros y m' hm', apply submodule.span_induction hm', { rintros m'' ⟨x, n, hm''⟩, rw [← hm'', leibniz_lie], refine submodule.add_mem _ _ _; apply submodule.subset_span, { use [⟨⁅y, ↑x⁆, I.lie_mem x.property⟩, n], refl, }, { use [x, ⟨⁅y, ↑n⁆, N.lie_mem n.property⟩], refl, }, }, { simp only [lie_zero, submodule.zero_mem], }, { intros m₁ m₂ hm₁ hm₂, rw lie_add, exact submodule.add_mem _ hm₁ hm₂, }, { intros t m'' hm'', rw lie_smul, exact submodule.smul_mem _ t hm'', }, }, change _ ≤ ↑({ lie_mem := aux, ..submodule.span R s } : lie_submodule R L M), rw [coe_submodule_le_coe_submodule, lie_ideal_oper_eq_span, lie_span_le], exact submodule.subset_span, }, { rw lie_ideal_oper_eq_span, apply submodule_span_le_lie_span, }, end lemma lie_ideal_oper_eq_linear_span' : (↑⁅I, N⁆ : submodule R M) = submodule.span R { m | ∃ (x ∈ I) (n ∈ N), ⁅x, n⁆ = m } := begin rw lie_ideal_oper_eq_linear_span, congr, ext m, split, { rintros ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, exact ⟨x, hx, n, hn, rfl⟩, }, { rintros ⟨x, hx, n, hn, rfl⟩, exact ⟨⟨x, hx⟩, ⟨n, hn⟩, rfl⟩, }, end lemma lie_le_iff : ⁅I, N⁆ ≤ N' ↔ ∀ (x ∈ I) (m ∈ N), ⁅x, m⁆ ∈ N' := begin rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], refine ⟨λ h x hx m hm, h ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, _⟩, rintros h _ ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, exact h x hx m hm, end lemma lie_coe_mem_lie (x : I) (m : N) : ⁅(x : L), (m : M)⁆ ∈ ⁅I, N⁆ := by { rw lie_ideal_oper_eq_span, apply subset_lie_span, use [x, m], } lemma lie_mem_lie {x : L} {m : M} (hx : x ∈ I) (hm : m ∈ N) : ⁅x, m⁆ ∈ ⁅I, N⁆ := N.lie_coe_mem_lie I ⟨x, hx⟩ ⟨m, hm⟩ lemma lie_comm : ⁅I, J⁆ = ⁅J, I⁆ := begin suffices : ∀ (I J : lie_ideal R L), ⁅I, J⁆ ≤ ⁅J, I⁆, { exact le_antisymm (this I J) (this J I), }, clear I J, intros I J, rw [lie_ideal_oper_eq_span, lie_span_le], rintros x ⟨y, z, h⟩, rw ← h, rw [← lie_skew, ← lie_neg, ← submodule.coe_neg], apply lie_coe_mem_lie, end lemma lie_le_right : ⁅I, N⁆ ≤ N := begin rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨x, n, hn⟩, rw ← hn, exact N.lie_mem n.property, end lemma lie_le_left : ⁅I, J⁆ ≤ I := by { rw lie_comm, exact lie_le_right I J, } lemma lie_le_inf : ⁅I, J⁆ ≤ I ⊓ J := by { rw le_inf_iff, exact ⟨lie_le_left I J, lie_le_right J I⟩, } @[simp] lemma lie_bot : ⁅I, (⊥ : lie_submodule R L M)⁆ = ⊥ := by { rw eq_bot_iff, apply lie_le_right, } @[simp] lemma bot_lie : ⁅(⊥ : lie_ideal R L), N⁆ = ⊥ := begin suffices : ⁅(⊥ : lie_ideal R L), N⁆ ≤ ⊥, { exact le_bot_iff.mp this, }, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨⟨x, hx⟩, n, hn⟩, rw ← hn, change x ∈ (⊥ : lie_ideal R L) at hx, rw mem_bot at hx, simp [hx], end lemma lie_eq_bot_iff : ⁅I, N⁆ = ⊥ ↔ ∀ (x ∈ I) (m ∈ N), ⁅(x : L), m⁆ = 0 := begin rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_eq_bot_iff], refine ⟨λ h x hx m hm, h ⁅x, m⁆ ⟨⟨x, hx⟩, ⟨m, hm⟩, rfl⟩, _⟩, rintros h - ⟨⟨x, hx⟩, ⟨⟨n, hn⟩, rfl⟩⟩, exact h x hx n hn, end lemma mono_lie (h₁ : I ≤ J) (h₂ : N ≤ N') : ⁅I, N⁆ ≤ ⁅J, N'⁆ := begin intros m h, rw [lie_ideal_oper_eq_span, mem_lie_span] at h, rw [lie_ideal_oper_eq_span, mem_lie_span], intros N hN, apply h, rintros m' ⟨⟨x, hx⟩, ⟨n, hn⟩, hm⟩, rw ← hm, apply hN, use [⟨x, h₁ hx⟩, ⟨n, h₂ hn⟩], refl, end lemma mono_lie_left (h : I ≤ J) : ⁅I, N⁆ ≤ ⁅J, N⁆ := mono_lie _ _ _ _ h (le_refl N) lemma mono_lie_right (h : N ≤ N') : ⁅I, N⁆ ≤ ⁅I, N'⁆ := mono_lie _ _ _ _ (le_refl I) h @[simp] lemma lie_sup : ⁅I, N ⊔ N'⁆ = ⁅I, N⁆ ⊔ ⁅I, N'⁆ := begin have h : ⁅I, N⁆ ⊔ ⁅I, N'⁆ ≤ ⁅I, N ⊔ N'⁆, { rw sup_le_iff, split; apply mono_lie_right; [exact le_sup_left, exact le_sup_right], }, suffices : ⁅I, N ⊔ N'⁆ ≤ ⁅I, N⁆ ⊔ ⁅I, N'⁆, { exact le_antisymm this h, }, clear h, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨x, ⟨n, hn⟩, h⟩, erw lie_submodule.mem_sup, erw lie_submodule.mem_sup at hn, rcases hn with ⟨n₁, hn₁, n₂, hn₂, hn'⟩, use ⁅(x : L), (⟨n₁, hn₁⟩ : N)⁆, split, { apply lie_coe_mem_lie, }, use ⁅(x : L), (⟨n₂, hn₂⟩ : N')⁆, split, { apply lie_coe_mem_lie, }, simp [← h, ← hn'], end @[simp] lemma sup_lie : ⁅I ⊔ J, N⁆ = ⁅I, N⁆ ⊔ ⁅J, N⁆ := begin have h : ⁅I, N⁆ ⊔ ⁅J, N⁆ ≤ ⁅I ⊔ J, N⁆, { rw sup_le_iff, split; apply mono_lie_left; [exact le_sup_left, exact le_sup_right], }, suffices : ⁅I ⊔ J, N⁆ ≤ ⁅I, N⁆ ⊔ ⁅J, N⁆, { exact le_antisymm this h, }, clear h, rw [lie_ideal_oper_eq_span, lie_span_le], rintros m ⟨⟨x, hx⟩, n, h⟩, erw lie_submodule.mem_sup, erw lie_submodule.mem_sup at hx, rcases hx with ⟨x₁, hx₁, x₂, hx₂, hx'⟩, use ⁅((⟨x₁, hx₁⟩ : I) : L), (n : N)⁆, split, { apply lie_coe_mem_lie, }, use ⁅((⟨x₂, hx₂⟩ : J) : L), (n : N)⁆, split, { apply lie_coe_mem_lie, }, simp [← h, ← hx'], end @[simp] lemma lie_inf : ⁅I, N ⊓ N'⁆ ≤ ⁅I, N⁆ ⊓ ⁅I, N'⁆ := by { rw le_inf_iff, split; apply mono_lie_right; [exact inf_le_left, exact inf_le_right], } @[simp] lemma inf_lie : ⁅I ⊓ J, N⁆ ≤ ⁅I, N⁆ ⊓ ⁅J, N⁆ := by { rw le_inf_iff, split; apply mono_lie_left; [exact inf_le_left, exact inf_le_right], } variables (f : M →ₗ⁅R,L⁆ M₂) lemma map_bracket_eq : map f ⁅I, N⁆ = ⁅I, map f N⁆ := begin rw [← coe_to_submodule_eq_iff, coe_submodule_map, lie_ideal_oper_eq_linear_span, lie_ideal_oper_eq_linear_span, submodule.map_span], congr, ext m, split, { rintros ⟨-, ⟨⟨x, ⟨n, hn⟩, rfl⟩, hm⟩⟩, simp only [lie_module_hom.coe_to_linear_map, lie_module_hom.map_lie] at hm, exact ⟨x, ⟨f n, (mem_map (f n)).mpr ⟨n, hn, rfl⟩⟩, hm⟩, }, { rintros ⟨x, ⟨m₂, hm₂ : m₂ ∈ map f N⟩, rfl⟩, obtain ⟨n, hn, rfl⟩ := (mem_map m₂).mp hm₂, exact ⟨⁅x, n⁆, ⟨x, ⟨n, hn⟩, rfl⟩, by simp⟩, }, end lemma map_comap_le : map f (comap f N₂) ≤ N₂ := (N₂ : set M₂).image_preimage_subset f lemma map_comap_eq (hf : N₂ ≤ f.range) : map f (comap f N₂) = N₂ := begin rw set_like.ext'_iff, exact set.image_preimage_eq_of_subset hf, end lemma le_comap_map : N ≤ comap f (map f N) := (N : set M).subset_preimage_image f lemma comap_map_eq (hf : f.ker = ⊥) : comap f (map f N) = N := begin rw set_like.ext'_iff, exact (N : set M).preimage_image_eq (f.ker_eq_bot.mp hf), end lemma comap_bracket_eq (hf₁ : f.ker = ⊥) (hf₂ : N₂ ≤ f.range) : comap f ⁅I, N₂⁆ = ⁅I, comap f N₂⁆ := begin conv_lhs { rw ← map_comap_eq N₂ f hf₂, }, rw [← map_bracket_eq, comap_map_eq _ f hf₁], end @[simp] lemma map_comap_incl : map N.incl (comap N.incl N') = N ⊓ N' := begin rw ← coe_to_submodule_eq_iff, exact (N : submodule R M).map_comap_subtype N', end end lie_ideal_operations end lie_submodule namespace lie_ideal open lie_algebra variables {R : Type u} {L : Type v} {L' : Type w₂} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L'] variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L') /-- Note that the inequality can be strict; e.g., the inclusion of an Abelian subalgebra of a simple algebra. -/ lemma map_bracket_le {I₁ I₂ : lie_ideal R L} : map f ⁅I₁, I₂⁆ ≤ ⁅map f I₁, map f I₂⁆ := begin rw map_le_iff_le_comap, erw lie_submodule.lie_span_le, intros x hx, obtain ⟨⟨y₁, hy₁⟩, ⟨y₂, hy₂⟩, hx⟩ := hx, rw ← hx, let fy₁ : ↥(map f I₁) := ⟨f y₁, mem_map hy₁⟩, let fy₂ : ↥(map f I₂) := ⟨f y₂, mem_map hy₂⟩, change _ ∈ comap f ⁅map f I₁, map f I₂⁆, simp only [submodule.coe_mk, mem_comap, lie_hom.map_lie], exact lie_submodule.lie_coe_mem_lie _ _ fy₁ fy₂, end lemma map_bracket_eq {I₁ I₂ : lie_ideal R L} (h : function.surjective f) : map f ⁅I₁, I₂⁆ = ⁅map f I₁, map f I₂⁆ := begin suffices : ⁅map f I₁, map f I₂⁆ ≤ map f ⁅I₁, I₂⁆, { exact le_antisymm (map_bracket_le f) this, }, rw [← lie_submodule.coe_submodule_le_coe_submodule, coe_map_of_surjective h, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.lie_ideal_oper_eq_linear_span, linear_map.map_span], apply submodule.span_mono, rintros x ⟨⟨z₁, h₁⟩, ⟨z₂, h₂⟩, rfl⟩, obtain ⟨y₁, rfl⟩ := mem_map_of_surjective h h₁, obtain ⟨y₂, rfl⟩ := mem_map_of_surjective h h₂, use [⁅(y₁ : L), (y₂ : L)⁆, y₁, y₂], apply f.map_lie, end lemma comap_bracket_le {J₁ J₂ : lie_ideal R L'} : ⁅comap f J₁, comap f J₂⁆ ≤ comap f ⁅J₁, J₂⁆ := begin rw ← map_le_iff_le_comap, exact le_trans (map_bracket_le f) (lie_submodule.mono_lie _ _ _ _ map_comap_le map_comap_le), end variables {f} lemma map_comap_incl {I₁ I₂ : lie_ideal R L} : map I₁.incl (comap I₁.incl I₂) = I₁ ⊓ I₂ := by { conv_rhs { rw ← I₁.incl_ideal_range, }, rw ← map_comap_eq, exact I₁.incl_is_ideal_morphism, } lemma comap_bracket_eq {J₁ J₂ : lie_ideal R L'} (h : f.is_ideal_morphism) : comap f ⁅f.ideal_range ⊓ J₁, f.ideal_range ⊓ J₂⁆ = ⁅comap f J₁, comap f J₂⁆ ⊔ f.ker := begin rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, ← submodule.comap_map_eq, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.lie_ideal_oper_eq_linear_span, linear_map.map_span], congr, simp only [lie_hom.coe_to_linear_map, set.mem_set_of_eq], ext y, split, { rintros ⟨⟨x₁, hx₁⟩, ⟨x₂, hx₂⟩, hy⟩, rw ← hy, erw [lie_submodule.mem_inf, f.mem_ideal_range_iff h] at hx₁ hx₂, obtain ⟨⟨z₁, hz₁⟩, hz₁'⟩ := hx₁, rw ← hz₁ at hz₁', obtain ⟨⟨z₂, hz₂⟩, hz₂'⟩ := hx₂, rw ← hz₂ at hz₂', use [⁅z₁, z₂⁆, ⟨z₁, hz₁'⟩, ⟨z₂, hz₂'⟩, rfl], simp only [hz₁, hz₂, submodule.coe_mk, lie_hom.map_lie], }, { rintros ⟨x, ⟨⟨z₁, hz₁⟩, ⟨z₂, hz₂⟩, hx⟩, hy⟩, rw [← hy, ← hx], have hz₁' : f z₁ ∈ f.ideal_range ⊓ J₁, { rw lie_submodule.mem_inf, exact ⟨f.mem_ideal_range, hz₁⟩, }, have hz₂' : f z₂ ∈ f.ideal_range ⊓ J₂, { rw lie_submodule.mem_inf, exact ⟨f.mem_ideal_range, hz₂⟩, }, use [⟨f z₁, hz₁'⟩, ⟨f z₂, hz₂'⟩], simp only [submodule.coe_mk, lie_hom.map_lie], }, end lemma map_comap_bracket_eq {J₁ J₂ : lie_ideal R L'} (h : f.is_ideal_morphism) : map f ⁅comap f J₁, comap f J₂⁆ = ⁅f.ideal_range ⊓ J₁, f.ideal_range ⊓ J₂⁆ := by { rw [← map_sup_ker_eq_map, ← comap_bracket_eq h, map_comap_eq h, inf_eq_right], exact le_trans (lie_submodule.lie_le_left _ _) inf_le_left, } lemma comap_bracket_incl {I₁ I₂ : lie_ideal R L} : ⁅comap I.incl I₁, comap I.incl I₂⁆ = comap I.incl ⁅I ⊓ I₁, I ⊓ I₂⁆ := begin conv_rhs { congr, skip, rw ← I.incl_ideal_range, }, rw comap_bracket_eq, simp only [ker_incl, sup_bot_eq], exact I.incl_is_ideal_morphism, end /-- This is a very useful result; it allows us to use the fact that inclusion distributes over the Lie bracket operation on ideals, subject to the conditions shown. -/ lemma comap_bracket_incl_of_le {I₁ I₂ : lie_ideal R L} (h₁ : I₁ ≤ I) (h₂ : I₂ ≤ I) : ⁅comap I.incl I₁, comap I.incl I₂⁆ = comap I.incl ⁅I₁, I₂⁆ := by { rw comap_bracket_incl, rw ← inf_eq_right at h₁ h₂, rw [h₁, h₂], } end lie_ideal
d0c0fa1059ccfeb5e7c199be0cbcec47eb16b4a7
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/sheaves/sheaf.lean
4bff3f4fc034077ae4ec6bacfb99ab66b1d0164f
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
3,522
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.sheaf_condition.equalizer_products import category_theory.full_subcategory /-! # Sheaves We define sheaves on a topological space, with values in an arbitrary category with products. The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`. We provide the instance `category (sheaf C X)` as the full subcategory of presheaves, and the fully faithful functor `sheaf.forget : sheaf C X ⥤ presheaf C X`. -/ 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 open sheaf_condition_equalizer_products /-- The sheaf condition for a `F : presheaf C X` requires that the morphism `F.obj U ⟶ ∏ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ F.obj (U i) ⟶ ∏ F.obj (U i) ⊓ (U j)`. -/ -- One might prefer to work with sets of opens, rather than indexed families, -- which would reduce the universe level here to `max u v`. -- However as it's a subsingleton the universe level doesn't matter much. @[derive subsingleton] def sheaf_condition (F : presheaf C X) : Type (max u (v+1)) := Π ⦃ι : Type v⦄ (U : ι → opens X), is_limit (sheaf_condition_equalizer_products.fork F U) /-- The presheaf valued in `punit` over any topological space is a sheaf. -/ def sheaf_condition_punit (F : presheaf (category_theory.discrete punit) X) : sheaf_condition F := λ ι U, punit_cone_is_limit -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_condition_inhabited (F : presheaf (category_theory.discrete punit) X) : inhabited (sheaf_condition F) := ⟨sheaf_condition_punit F⟩ /-- Transfer the sheaf condition across an isomorphism of presheaves. -/ def sheaf_condition_equiv_of_iso {F G : presheaf C X} (α : F ≅ G) : sheaf_condition F ≃ sheaf_condition G := equiv_of_subsingleton_of_subsingleton (λ c ι U, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α.symm).symm) (λ c ι U, is_limit.of_iso_limit ((is_limit.postcompose_inv_equiv _ _).symm (c U)) (sheaf_condition_equalizer_products.fork.iso_of_iso U α).symm) end presheaf variables (C X) /-- A `sheaf C X` is a presheaf of objects from `C` over a (bundled) topological space `X`, satisfying the sheaf condition. -/ structure sheaf := (presheaf : presheaf C X) (sheaf_condition : presheaf.sheaf_condition) instance : category (sheaf C X) := induced_category.category sheaf.presheaf -- Let's construct a trivial example, to keep the inhabited linter happy. instance sheaf_inhabited : inhabited (sheaf (category_theory.discrete punit) X) := ⟨{ presheaf := functor.star _, sheaf_condition := default _ }⟩ namespace sheaf /-- The forgetful functor from sheaves to presheaves. -/ @[derive [full, faithful]] def forget : Top.sheaf C X ⥤ Top.presheaf C X := induced_functor sheaf.presheaf end sheaf end Top
d7739fb7d219a306880a3806c8bf6d01e872af96
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/continuous_function/stone_weierstrass.lean
6ba08ff989c622510c7f324edf760b61a9e2aa4a
[ "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
19,958
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Heather Macbeth -/ import topology.continuous_function.weierstrass import analysis.complex.basic /-! # The Stone-Weierstrass theorem If a subalgebra `A` of `C(X, ℝ)`, where `X` is a compact topological space, separates points, then it is dense. We argue as follows. * In any subalgebra `A` of `C(X, ℝ)`, if `f ∈ A`, then `abs f ∈ A.topological_closure`. This follows from the Weierstrass approximation theorem on `[-∥f∥, ∥f∥]` by approximating `abs` uniformly thereon by polynomials. * This ensures that `A.topological_closure` is actually a sublattice: if it contains `f` and `g`, then it contains the pointwise supremum `f ⊔ g` and the pointwise infimum `f ⊓ g`. * Any nonempty sublattice `L` of `C(X, ℝ)` which separates points is dense, by a nice argument approximating a given `f` above and below using separating functions. For each `x y : X`, we pick a function `g x y ∈ L` so `g x y x = f x` and `g x y y = f y`. By continuity these functions remain close to `f` on small patches around `x` and `y`. We use compactness to identify a certain finitely indexed infimum of finitely indexed supremums which is then close to `f` everywhere, obtaining the desired approximation. * Finally we put these pieces together. `L = A.topological_closure` is a nonempty sublattice which separates points since `A` does, and so is dense (in fact equal to `⊤`). We then prove the complex version for self-adjoint subalgebras `A`, by separately approximating the real and imaginary parts using the real subalgebra of real-valued functions in `A` (which still separates points, by taking the norm-square of a separating function). ## Future work Extend to cover the case of subalgebras of the continuous functions vanishing at infinity, on non-compact spaces. -/ noncomputable theory namespace continuous_map variables {X : Type*} [topological_space X] [compact_space X] /-- Turn a function `f : C(X, ℝ)` into a continuous map into `set.Icc (-∥f∥) (∥f∥)`, thereby explicitly attaching bounds. -/ def attach_bound (f : C(X, ℝ)) : C(X, set.Icc (-∥f∥) (∥f∥)) := { to_fun := λ x, ⟨f x, ⟨neg_norm_le_apply f x, apply_le_norm f x⟩⟩ } @[simp] lemma attach_bound_apply_coe (f : C(X, ℝ)) (x : X) : ((attach_bound f) x : ℝ) = f x := rfl lemma polynomial_comp_attach_bound (A : subalgebra ℝ C(X, ℝ)) (f : A) (g : polynomial ℝ) : (g.to_continuous_map_on (set.Icc (-∥f∥) ∥f∥)).comp (f : C(X, ℝ)).attach_bound = polynomial.aeval f g := begin ext, simp only [continuous_map.coe_comp, function.comp_app, continuous_map.attach_bound_apply_coe, polynomial.to_continuous_map_on_apply, polynomial.aeval_subalgebra_coe, polynomial.aeval_continuous_map_apply, polynomial.to_continuous_map_apply], end /-- Given a continuous function `f` in a subalgebra of `C(X, ℝ)`, postcomposing by a polynomial gives another function in `A`. This lemma proves something slightly more subtle than this: we take `f`, and think of it as a function into the restricted target `set.Icc (-∥f∥) ∥f∥)`, and then postcompose with a polynomial function on that interval. This is in fact the same situation as above, and so also gives a function in `A`. -/ lemma polynomial_comp_attach_bound_mem (A : subalgebra ℝ C(X, ℝ)) (f : A) (g : polynomial ℝ) : (g.to_continuous_map_on (set.Icc (-∥f∥) ∥f∥)).comp (f : C(X, ℝ)).attach_bound ∈ A := begin rw polynomial_comp_attach_bound, apply set_like.coe_mem, end theorem comp_attach_bound_mem_closure (A : subalgebra ℝ C(X, ℝ)) (f : A) (p : C(set.Icc (-∥f∥) (∥f∥), ℝ)) : p.comp (attach_bound f) ∈ A.topological_closure := begin -- `p` itself is in the closure of polynomials, by the Weierstrass theorem, have mem_closure : p ∈ (polynomial_functions (set.Icc (-∥f∥) (∥f∥))).topological_closure := continuous_map_mem_polynomial_functions_closure _ _ p, -- and so there are polynomials arbitrarily close. have frequently_mem_polynomials := mem_closure_iff_frequently.mp mem_closure, -- To prove `p.comp (attached_bound f)` is in the closure of `A`, -- we show there are elements of `A` arbitrarily close. apply mem_closure_iff_frequently.mpr, -- To show that, we pull back the polynomials close to `p`, refine ((comp_right_continuous_map ℝ (attach_bound (f : C(X, ℝ)))).continuous_at p).tendsto .frequently_map _ _ frequently_mem_polynomials, -- but need to show that those pullbacks are actually in `A`. rintros _ ⟨g, ⟨-,rfl⟩⟩, simp only [set_like.mem_coe, alg_hom.coe_to_ring_hom, comp_right_continuous_map_apply, polynomial.to_continuous_map_on_alg_hom_apply], apply polynomial_comp_attach_bound_mem, end theorem abs_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f : A) : (f : C(X, ℝ)).abs ∈ A.topological_closure := begin let M := ∥f∥, let f' := attach_bound (f : C(X, ℝ)), let abs : C(set.Icc (-∥f∥) (∥f∥), ℝ) := { to_fun := λ x : set.Icc (-∥f∥) (∥f∥), |(x : ℝ)| }, change (abs.comp f') ∈ A.topological_closure, apply comp_attach_bound_mem_closure, end theorem inf_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f g : A) : (f : C(X, ℝ)) ⊓ (g : C(X, ℝ)) ∈ A.topological_closure := begin rw inf_eq, refine A.topological_closure.smul_mem (A.topological_closure.sub_mem (A.topological_closure.add_mem (A.subalgebra_topological_closure f.property) (A.subalgebra_topological_closure g.property)) _) _, exact_mod_cast abs_mem_subalgebra_closure A _, end theorem inf_mem_closed_subalgebra (A : subalgebra ℝ C(X, ℝ)) (h : is_closed (A : set C(X, ℝ))) (f g : A) : (f : C(X, ℝ)) ⊓ (g : C(X, ℝ)) ∈ A := begin convert inf_mem_subalgebra_closure A f g, apply set_like.ext', symmetry, erw closure_eq_iff_is_closed, exact h, end theorem sup_mem_subalgebra_closure (A : subalgebra ℝ C(X, ℝ)) (f g : A) : (f : C(X, ℝ)) ⊔ (g : C(X, ℝ)) ∈ A.topological_closure := begin rw sup_eq, refine A.topological_closure.smul_mem (A.topological_closure.add_mem (A.topological_closure.add_mem (A.subalgebra_topological_closure f.property) (A.subalgebra_topological_closure g.property)) _) _, exact_mod_cast abs_mem_subalgebra_closure A _, end theorem sup_mem_closed_subalgebra (A : subalgebra ℝ C(X, ℝ)) (h : is_closed (A : set C(X, ℝ))) (f g : A) : (f : C(X, ℝ)) ⊔ (g : C(X, ℝ)) ∈ A := begin convert sup_mem_subalgebra_closure A f g, apply set_like.ext', symmetry, erw closure_eq_iff_is_closed, exact h, end open_locale topological_space -- Here's the fun part of Stone-Weierstrass! theorem sublattice_closure_eq_top (L : set C(X, ℝ)) (nA : L.nonempty) (inf_mem : ∀ f g ∈ L, f ⊓ g ∈ L) (sup_mem : ∀ f g ∈ L, f ⊔ g ∈ L) (sep : L.separates_points_strongly) : closure L = ⊤ := begin -- We start by boiling down to a statement about close approximation. apply eq_top_iff.mpr, rintros f -, refine filter.frequently.mem_closure ((filter.has_basis.frequently_iff metric.nhds_basis_ball).mpr (λ ε pos, _)), simp only [exists_prop, metric.mem_ball], -- It will be helpful to assume `X` is nonempty later, -- so we get that out of the way here. by_cases nX : nonempty X, swap, exact ⟨nA.some, (dist_lt_iff pos).mpr (λ x, false.elim (nX ⟨x⟩)), nA.some_spec⟩, /- The strategy now is to pick a family of continuous functions `g x y` in `A` with the property that `g x y x = f x` and `g x y y = f y` (this is immediate from `h : separates_points_strongly`) then use continuity to see that `g x y` is close to `f` near both `x` and `y`, and finally using compactness to produce the desired function `h` as a maximum over finitely many `x` of a minimum over finitely many `y` of the `g x y`. -/ dsimp [set.separates_points_strongly] at sep, let g : X → X → L := λ x y, (sep f x y).some, have w₁ : ∀ x y, g x y x = f x := λ x y, (sep f x y).some_spec.1, have w₂ : ∀ x y, g x y y = f y := λ x y, (sep f x y).some_spec.2, -- For each `x y`, we define `U x y` to be `{z | f z - ε < g x y z}`, -- and observe this is a neighbourhood of `y`. let U : X → X → set X := λ x y, {z | f z - ε < g x y z}, have U_nhd_y : ∀ x y, U x y ∈ 𝓝 y, { intros x y, refine is_open.mem_nhds _ _, { apply is_open_lt; continuity, }, { rw [set.mem_set_of_eq, w₂], exact sub_lt_self _ pos, }, }, -- Fixing `x` for a moment, we have a family of functions `λ y, g x y` -- which on different patches (the `U x y`) are greater than `f z - ε`. -- Taking the supremum of these functions -- indexed by a finite collection of patches which cover `X` -- will give us an element of `A` that is globally greater than `f z - ε` -- and still equal to `f x` at `x`. -- Since `X` is compact, for every `x` there is some finset `ys t` -- so the union of the `U x y` for `y ∈ ys x` still covers everything. let ys : Π x, finset X := λ x, (compact_space.elim_nhds_subcover (U x) (U_nhd_y x)).some, let ys_w : ∀ x, (⋃ y ∈ ys x, U x y) = ⊤ := λ x, (compact_space.elim_nhds_subcover (U x) (U_nhd_y x)).some_spec, have ys_nonempty : ∀ x, (ys x).nonempty := λ x, set.nonempty_of_union_eq_top_of_nonempty _ _ nX (ys_w x), -- Thus for each `x` we have the desired `h x : A` so `f z - ε < h x z` everywhere -- and `h x x = f x`. let h : Π x, L := λ x, ⟨(ys x).sup' (ys_nonempty x) (λ y, (g x y : C(X, ℝ))), finset.sup'_mem _ sup_mem _ _ _ (λ y _, (g x y).2)⟩, have lt_h : ∀ x z, f z - ε < h x z, { intros x z, obtain ⟨y, ym, zm⟩ := set.exists_set_mem_of_union_eq_top _ _ (ys_w x) z, dsimp [h], simp only [coe_fn_coe_base', subtype.coe_mk, sup'_coe, finset.sup'_apply, finset.lt_sup'_iff], exact ⟨y, ym, zm⟩ }, have h_eq : ∀ x, h x x = f x, { intro x, simp only [coe_fn_coe_base'] at w₁, simp [coe_fn_coe_base', w₁], }, -- For each `x`, we define `W x` to be `{z | h x z < f z + ε}`, let W : Π x, set X := λ x, {z | h x z < f z + ε}, -- This is still a neighbourhood of `x`. have W_nhd : ∀ x, W x ∈ 𝓝 x, { intros x, refine is_open.mem_nhds _ _, { apply is_open_lt; continuity, }, { dsimp only [W, set.mem_set_of_eq], rw h_eq, exact lt_add_of_pos_right _ pos}, }, -- Since `X` is compact, there is some finset `ys t` -- so the union of the `W x` for `x ∈ xs` still covers everything. let xs : finset X := (compact_space.elim_nhds_subcover W W_nhd).some, let xs_w : (⋃ x ∈ xs, W x) = ⊤ := (compact_space.elim_nhds_subcover W W_nhd).some_spec, have xs_nonempty : xs.nonempty := set.nonempty_of_union_eq_top_of_nonempty _ _ nX xs_w, -- Finally our candidate function is the infimum over `x ∈ xs` of the `h x`. -- This function is then globally less than `f z + ε`. let k : (L : Type*) := ⟨xs.inf' xs_nonempty (λ x, (h x : C(X, ℝ))), finset.inf'_mem _ inf_mem _ _ _ (λ x _, (h x).2)⟩, refine ⟨k.1, _, k.2⟩, -- We just need to verify the bound, which we do pointwise. rw dist_lt_iff pos, intro z, -- We rewrite into this particular form, -- so that simp lemmas about inequalities involving `finset.inf'` can fire. rw [(show ∀ a b ε : ℝ, dist a b < ε ↔ a < b + ε ∧ b - ε < a, by { intros, simp only [← metric.mem_ball, real.ball_eq_Ioo, set.mem_Ioo, and_comm], })], fsplit, { dsimp [k], simp only [finset.inf'_lt_iff, continuous_map.inf'_apply], exact set.exists_set_mem_of_union_eq_top _ _ xs_w z, }, { dsimp [k], simp only [finset.lt_inf'_iff, continuous_map.inf'_apply], intros x xm, apply lt_h, }, end /-- The **Stone-Weierstrass Approximation Theorem**, that a subalgebra `A` of `C(X, ℝ)`, where `X` is a compact topological space, is dense if it separates points. -/ theorem subalgebra_topological_closure_eq_top_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) : A.topological_closure = ⊤ := begin -- The closure of `A` is closed under taking `sup` and `inf`, -- and separates points strongly (since `A` does), -- so we can apply `sublattice_closure_eq_top`. apply set_like.ext', let L := A.topological_closure, have n : set.nonempty (L : set C(X, ℝ)) := ⟨(1 : C(X, ℝ)), A.subalgebra_topological_closure A.one_mem⟩, convert sublattice_closure_eq_top (L : set C(X, ℝ)) n (λ f fm g gm, inf_mem_closed_subalgebra L A.is_closed_topological_closure ⟨f, fm⟩ ⟨g, gm⟩) (λ f fm g gm, sup_mem_closed_subalgebra L A.is_closed_topological_closure ⟨f, fm⟩ ⟨g, gm⟩) (subalgebra.separates_points.strongly (subalgebra.separates_points_monotone (A.subalgebra_topological_closure) w)), { simp, }, end /-- An alternative statement of the Stone-Weierstrass theorem. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is a uniform limit of elements of `A`. -/ theorem continuous_map_mem_subalgebra_closure_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : C(X, ℝ)) : f ∈ A.topological_closure := begin rw subalgebra_topological_closure_eq_top_of_separates_points A w, simp, end /-- An alternative statement of the Stone-Weierstrass theorem, for those who like their epsilons. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is within any `ε > 0` of some element of `A`. -/ theorem exists_mem_subalgebra_near_continuous_map_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : C(X, ℝ)) (ε : ℝ) (pos : 0 < ε) : ∃ (g : A), ∥(g : C(X, ℝ)) - f∥ < ε := begin have w := mem_closure_iff_frequently.mp (continuous_map_mem_subalgebra_closure_of_separates_points A w f), rw metric.nhds_basis_ball.frequently_iff at w, obtain ⟨g, H, m⟩ := w ε pos, rw [metric.mem_ball, dist_eq_norm] at H, exact ⟨⟨g, m⟩, H⟩, end /-- An alternative statement of the Stone-Weierstrass theorem, for those who like their epsilons and don't like bundled continuous functions. If `A` is a subalgebra of `C(X, ℝ)` which separates points (and `X` is compact), every real-valued continuous function on `X` is within any `ε > 0` of some element of `A`. -/ theorem exists_mem_subalgebra_near_continuous_of_separates_points (A : subalgebra ℝ C(X, ℝ)) (w : A.separates_points) (f : X → ℝ) (c : continuous f) (ε : ℝ) (pos : 0 < ε) : ∃ (g : A), ∀ x, ∥g x - f x∥ < ε := begin obtain ⟨g, b⟩ := exists_mem_subalgebra_near_continuous_map_of_separates_points A w ⟨f, c⟩ ε pos, use g, rwa norm_lt_iff _ pos at b, end end continuous_map section is_R_or_C open is_R_or_C -- Redefine `X`, since for the next few lemmas it need not be compact variables {𝕜 : Type*} {X : Type*} [is_R_or_C 𝕜] [topological_space X] namespace continuous_map /-- A real subalgebra of `C(X, 𝕜)` is `conj_invariant`, if it contains all its conjugates. -/ def conj_invariant_subalgebra (A : subalgebra ℝ C(X, 𝕜)) : Prop := A.map (conj_ae.to_alg_hom.comp_left_continuous ℝ conj_cle.continuous) ≤ A lemma mem_conj_invariant_subalgebra {A : subalgebra ℝ C(X, 𝕜)} (hA : conj_invariant_subalgebra A) {f : C(X, 𝕜)} (hf : f ∈ A) : (conj_ae.to_alg_hom.comp_left_continuous ℝ conj_cle.continuous) f ∈ A := hA ⟨f, hf, rfl⟩ end continuous_map open continuous_map /-- If a conjugation-invariant subalgebra of `C(X, 𝕜)` separates points, then the real subalgebra of its purely real-valued elements also separates points. -/ lemma subalgebra.separates_points.is_R_or_C_to_real {A : subalgebra 𝕜 C(X, 𝕜)} (hA : A.separates_points) (hA' : conj_invariant_subalgebra (A.restrict_scalars ℝ)) : ((A.restrict_scalars ℝ).comap (of_real_am.comp_left_continuous ℝ continuous_of_real)).separates_points := begin intros x₁ x₂ hx, -- Let `f` in the subalgebra `A` separate the points `x₁`, `x₂` obtain ⟨_, ⟨f, hfA, rfl⟩, hf⟩ := hA hx, let F : C(X, 𝕜) := f - const _ (f x₂), -- Subtract the constant `f x₂` from `f`; this is still an element of the subalgebra have hFA : F ∈ A, { refine A.sub_mem hfA _, convert A.smul_mem A.one_mem (f x₂), ext1, simp }, -- Consider now the function `λ x, |f x - f x₂| ^ 2` refine ⟨_, ⟨(⟨is_R_or_C.norm_sq, continuous_norm_sq⟩ : C(𝕜, ℝ)).comp F, _, rfl⟩, _⟩, { -- This is also an element of the subalgebra, and takes only real values rw [set_like.mem_coe, subalgebra.mem_comap], convert (A.restrict_scalars ℝ).mul_mem (mem_conj_invariant_subalgebra hA' hFA) hFA, ext1, rw [mul_comm], exact (is_R_or_C.mul_conj _).symm }, { -- And it also separates the points `x₁`, `x₂` have : f x₁ - f x₂ ≠ 0 := sub_ne_zero.mpr hf, simpa using this }, end variables [compact_space X] /-- The Stone-Weierstrass approximation theorem, `is_R_or_C` version, that a subalgebra `A` of `C(X, 𝕜)`, where `X` is a compact topological space and `is_R_or_C 𝕜`, is dense if it is conjugation-invariant and separates points. -/ theorem continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points (A : subalgebra 𝕜 C(X, 𝕜)) (hA : A.separates_points) (hA' : conj_invariant_subalgebra (A.restrict_scalars ℝ)) : A.topological_closure = ⊤ := begin rw algebra.eq_top_iff, -- Let `I` be the natural inclusion of `C(X, ℝ)` into `C(X, 𝕜)` let I : C(X, ℝ) →ₗ[ℝ] C(X, 𝕜) := of_real_clm.comp_left_continuous ℝ X, -- The main point of the proof is that its range (i.e., every real-valued function) is contained -- in the closure of `A` have key : I.range ≤ (A.to_submodule.restrict_scalars ℝ).topological_closure, { -- Let `A₀` be the subalgebra of `C(X, ℝ)` consisting of `A`'s purely real elements; it is the -- preimage of `A` under `I`. In this argument we only need its submodule structure. let A₀ : submodule ℝ C(X, ℝ) := (A.to_submodule.restrict_scalars ℝ).comap I, -- By `subalgebra.separates_points.complex_to_real`, this subalgebra also separates points, so -- we may apply the real Stone-Weierstrass result to it. have SW : A₀.topological_closure = ⊤, { have := subalgebra_topological_closure_eq_top_of_separates_points _ (hA.is_R_or_C_to_real hA'), exact congr_arg subalgebra.to_submodule this }, rw [← submodule.map_top, ← SW], -- So it suffices to prove that the image under `I` of the closure of `A₀` is contained in the -- closure of `A`, which follows by abstract nonsense have h₁ := A₀.topological_closure_map ((@of_real_clm 𝕜 _).comp_left_continuous_compact X), have h₂ := (A.to_submodule.restrict_scalars ℝ).map_comap_le I, exact h₁.trans (submodule.topological_closure_mono h₂) }, -- In particular, for a function `f` in `C(X, 𝕜)`, the real and imaginary parts of `f` are in the -- closure of `A` intros f, let f_re : C(X, ℝ) := (⟨is_R_or_C.re, is_R_or_C.re_clm.continuous⟩ : C(𝕜, ℝ)).comp f, let f_im : C(X, ℝ) := (⟨is_R_or_C.im, is_R_or_C.im_clm.continuous⟩ : C(𝕜, ℝ)).comp f, have h_f_re : I f_re ∈ A.topological_closure := key ⟨f_re, rfl⟩, have h_f_im : I f_im ∈ A.topological_closure := key ⟨f_im, rfl⟩, -- So `f_re + I • f_im` is in the closure of `A` convert A.topological_closure.add_mem h_f_re (A.topological_closure.smul_mem h_f_im is_R_or_C.I), -- And this, of course, is just `f` ext, apply eq.symm, simp [I, mul_comm is_R_or_C.I _], end end is_R_or_C
b281d7f41ef88577f857c774759ccb1d06e06829
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/st_options.lean
3dcdee85bac2b9aff0b9239394a0cfaccae2560a
[ "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
2,594
lean
set_option structure.eta_thm true set_option structure.proj_mk_thm true structure semigroup [class] (A : Type) extends has_mul A := (mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c)) structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b, mul a b = mul b a) structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c, mul a b = mul a c → b = c) structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c, mul a b = mul c b → a = c) structure add_semigroup [class] (A : Type) extends has_add A := (add_assoc : ∀a b c, add (add a b) c = add a (add b c)) structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b, add a b = add b a) structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c, add a b = add a c → b = c) structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c, add a b = add c b → a = c) structure monoid [class] (A : Type) extends semigroup A, has_one A := (one_mul : ∀a, mul one a = a) (mul_one : ∀a, mul a one = a) structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (zero_add : ∀a, add zero a = a) (add_zero : ∀a, add a zero = a) structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a, mul (inv a) a = one) structure comm_group [class] (A : Type) extends group A, comm_monoid A structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a, add (neg a) a = zero) structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A structure distrib [class] (A : Type) extends has_mul A, has_add A := (left_distrib : ∀a b c, mul a (add b c) = add (mul a b) (mul a c)) (right_distrib : ∀a b c, mul (add a b) c = add (mul a c) (mul b c)) structure mul_zero_class [class] (A : Type) extends has_mul A, has_zero A := (zero_mul : ∀a, mul zero a = zero) (mul_zero : ∀a, mul a zero = zero) structure zero_ne_one_class [class] (A : Type) extends has_zero A, has_one A := (zero_ne_one : zero ≠ one) structure semiring [class] (A : Type) extends add_comm_monoid A, monoid A, distrib A, mul_zero_class A, zero_ne_one_class A set_option pp.implicit true check @semiring.mul.mk check @semiring.eta
014b3d1d08d3afd09657d50b173248f8b021b775
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/analysis/topology/compact_open.lean
58f5a5fe1565cb6d26062c63406d0327d885f2f7
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
5,540
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import analysis.topology.continuity tactic.tidy open set universes u v w section locally_compact -- There are various definitions of "locally compact space" in the -- literature, which agree for Hausdorff spaces but not in general. -- This one is the precise condition on X needed for the evaluation -- map C(X, Y) × X → Y to be continuous for all Y when C(X, Y) is -- given the compact-open topology. class locally_compact_space (α : Type u) [topological_space α] := (local_compact_nhds : ∀ (x : α) (n ∈ (nhds x).sets), ∃ s ∈ (nhds x).sets, s ⊆ n ∧ compact s) variables {α : Type u} [topological_space α] lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ (nhds x).sets ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ (nhds x).sets, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ lemma locally_compact_of_compact [t2_space α] (h : compact (univ : set α)) : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, h⟩) end locally_compact section compact_open variables {α : Type u} {β : Type v} {γ : Type w} variables [topological_space α] [topological_space β] [topological_space γ] local notation `C(` α `, ` β `)` := subtype (continuous : set (α → β)) def compact_open_gen {s : set α} (hs : compact s) {u : set β} (hu : is_open u) : set C(α,β) := {f | f.val '' s ⊆ u} -- The compact-open topology on the space of continuous maps α → β. def compact_open : topological_space C(α, β) := topological_space.generate_from {m | ∃ (s : set α) (hs : compact s) (u : set β) (hu : is_open u), m = compact_open_gen hs hu} local attribute [instance] compact_open private lemma is_open_gen {s : set α} (hs : compact s) {u : set β} (hu : is_open u) : is_open (compact_open_gen hs hu) := topological_space.generate_open.basic _ (by dsimp [mem_set_of_eq]; tauto) section functorial variables {g : β → γ} (hg : continuous g) def continuous_map.induced : C(α, β) → C(α, γ) := λ f, ⟨g ∘ f, f.property.comp hg⟩ private lemma preimage_gen {s : set α} (hs : compact s) {u : set γ} (hu : is_open u) : continuous_map.induced hg ⁻¹' (compact_open_gen hs hu) = compact_open_gen hs (hg _ hu) := begin ext ⟨f, _⟩, change g ∘ f '' s ⊆ u ↔ f '' s ⊆ g ⁻¹' u, rw [image_comp, image_subset_iff] end -- C(α, -) is a functor. lemma continuous_induced : continuous (continuous_map.induced hg : C(α, β) → C(α, γ)) := continuous_generated_from $ assume m ⟨s, hs, u, hu, hm⟩, by rw [hm, preimage_gen]; apply is_open_gen end functorial section ev variables (α β) def ev : C(α, β) × α → β := λ p, p.1.val p.2 variables {α β} -- The evaluation map C(α, β) × α → β is continuous if α is locally compact. lemma continuous_ev [locally_compact_space α] : continuous (ev α β) := continuous_iff_tendsto.mpr $ assume ⟨f, x⟩ n hn, let ⟨v, vn, vo, fxv⟩ := mem_nhds_sets_iff.mp hn in have v ∈ (nhds (f.val x)).sets, from mem_nhds_sets vo fxv, let ⟨s, hs, sv, sc⟩ := locally_compact_space.local_compact_nhds x (f.val ⁻¹' v) (f.property.tendsto x this) in let ⟨u, us, uo, xu⟩ := mem_nhds_sets_iff.mp hs in show (ev α β) ⁻¹' n ∈ (nhds (f, x)).sets, from let w := set.prod (compact_open_gen sc vo) u in have w ⊆ ev α β ⁻¹' n, from assume ⟨f', x'⟩ ⟨hf', hx'⟩, calc f'.val x' ∈ f'.val '' s : mem_image_of_mem f'.val (us hx') ... ⊆ v : hf' ... ⊆ n : vn, have is_open w, from is_open_prod (is_open_gen _ _) uo, have (f, x) ∈ w, from ⟨image_subset_iff.mpr sv, xu⟩, mem_nhds_sets_iff.mpr ⟨w, by assumption, by assumption, by assumption⟩ end ev section coev variables (α β) def coev : β → C(α, β × α) := λ b, ⟨λ a, (b, a), continuous.prod_mk continuous_const continuous_id⟩ variables {α β} lemma image_coev {y : β} (s : set α) : (coev α β y).val '' s = set.prod {y} s := by tidy -- The coevaluation map β → C(α, β × α) is continuous (always). lemma continuous_coev : continuous (coev α β) := continuous_generated_from $ begin rintros _ ⟨s, sc, u, uo, rfl⟩, rw is_open_iff_forall_mem_open, intros y hy, change (coev α β y).val '' s ⊆ u at hy, rw image_coev s at hy, rcases generalized_tube_lemma compact_singleton sc uo hy with ⟨v, w, vo, wo, yv, sw, vwu⟩, refine ⟨v, _, vo, singleton_subset_iff.mp yv⟩, intros y' hy', change (coev α β y').val '' s ⊆ u, rw image_coev s, exact subset.trans (prod_mono (singleton_subset_iff.mpr hy') sw) vwu end end coev end compact_open
35750468aa9feb49b852f898528716359f372d68
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib.lean
c65d2459a6660e169cb460308fa3b3aaeada10a5
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
1,782
lean
import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Defs import Mathlib.Algebra.GroupWithZero.Defs import Mathlib.Algebra.Ring.Basic import Mathlib.Data.Array.Basic import Mathlib.Data.ByteArray import Mathlib.Data.Char import Mathlib.Data.Equiv.Basic import Mathlib.Data.Equiv.Functor import Mathlib.Data.Fin.Basic import Mathlib.Data.Int.Basic import Mathlib.Data.List.Basic import Mathlib.Data.List.Card import Mathlib.Data.List.Perm import Mathlib.Data.Nat.Basic import Mathlib.Data.Nat.Gcd import Mathlib.Data.Prod import Mathlib.Data.String.Defs import Mathlib.Data.String.Lemmas import Mathlib.Data.Subtype import Mathlib.Data.UInt import Mathlib.Init.Algebra.Functions import Mathlib.Init.Algebra.Order import Mathlib.Init.Data.Nat.Basic import Mathlib.Init.Data.Nat.Lemmas import Mathlib.Init.Dvd import Mathlib.Init.Function import Mathlib.Init.Logic import Mathlib.Init.Set import Mathlib.Init.SetNotation import Mathlib.Lean.LocalContext import Mathlib.Logic.Basic import Mathlib.Logic.Function.Basic import Mathlib.Mathport.Attributes import Mathlib.Mathport.Rename import Mathlib.Mathport.SpecialNames import Mathlib.Mathport.Syntax import Mathlib.Tactic.Basic import Mathlib.Tactic.Cache import Mathlib.Tactic.Coe import Mathlib.Tactic.Core import Mathlib.Tactic.Ext import Mathlib.Tactic.Find import Mathlib.Tactic.LibrarySearch import Mathlib.Tactic.NoMatch import Mathlib.Tactic.NormNum import Mathlib.Tactic.OpenPrivate import Mathlib.Tactic.PrintPrefix import Mathlib.Tactic.Rcases import Mathlib.Tactic.Ring import Mathlib.Tactic.RunTac import Mathlib.Tactic.ShowTerm import Mathlib.Tactic.SolveByElim import Mathlib.Tactic.Spread import Mathlib.Tactic.SudoSetOption import Mathlib.Tactic.TryThis import Mathlib.Util.Export import Mathlib.Util.Time
3c9863c7b3043a5c92ba146bd8a394879611019b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/alexandroff.lean
fc0fae833aaa8c31a4afd1561a9f6fc85f4290ca
[ "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
18,795
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang, Yury Kudryashov -/ import data.fintype.option import topology.separation import topology.sets.opens /-! # The Alexandroff Compactification > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We construct the Alexandroff compactification (the one-point compactification) of an arbitrary topological space `X` and prove some properties inherited from `X`. ## Main definitions * `alexandroff`: the Alexandroff compactification, we use coercion for the canonical embedding `X → alexandroff X`; when `X` is already compact, the compactification adds an isolated point to the space. * `alexandroff.infty`: the extra point ## Main results * The topological structure of `alexandroff X` * The connectedness of `alexandroff X` for a noncompact, preconnected `X` * `alexandroff X` is `T₀` for a T₀ space `X` * `alexandroff X` is `T₁` for a T₁ space `X` * `alexandroff X` is normal if `X` is a locally compact Hausdorff space ## Tags one-point compactification, compactness -/ open set filter open_locale classical topology filter /-! ### Definition and basic properties In this section we define `alexandroff X` to be the disjoint union of `X` and `∞`, implemented as `option X`. Then we restate some lemmas about `option X` for `alexandroff X`. -/ variables {X : Type*} /-- The Alexandroff extension of an arbitrary topological space `X` -/ def alexandroff (X : Type*) := option X /-- The repr uses the notation from the `alexandroff` locale. -/ instance [has_repr X] : has_repr (alexandroff X) := ⟨λ o, match o with | none := "∞" | (some a) := "↑" ++ repr a end⟩ namespace alexandroff /-- The point at infinity -/ def infty : alexandroff X := none localized "notation (name := alexandroff.infty) `∞` := alexandroff.infty" in alexandroff instance : has_coe_t X (alexandroff X) := ⟨option.some⟩ instance : inhabited (alexandroff X) := ⟨∞⟩ instance [fintype X] : fintype (alexandroff X) := option.fintype instance infinite [infinite X] : infinite (alexandroff X) := option.infinite lemma coe_injective : function.injective (coe : X → alexandroff X) := option.some_injective X @[norm_cast] lemma coe_eq_coe {x y : X} : (x : alexandroff X) = y ↔ x = y := coe_injective.eq_iff @[simp] lemma coe_ne_infty (x : X) : (x : alexandroff X) ≠ ∞ . @[simp] lemma infty_ne_coe (x : X) : ∞ ≠ (x : alexandroff X) . /-- Recursor for `alexandroff` using the preferred forms `∞` and `↑x`. -/ @[elab_as_eliminator] protected def rec (C : alexandroff X → Sort*) (h₁ : C ∞) (h₂ : Π x : X, C x) : Π (z : alexandroff X), C z := option.rec h₁ h₂ lemma is_compl_range_coe_infty : is_compl (range (coe : X → alexandroff X)) {∞} := is_compl_range_some_none X @[simp] lemma range_coe_union_infty : (range (coe : X → alexandroff X) ∪ {∞}) = univ := range_some_union_none X @[simp] lemma range_coe_inter_infty : (range (coe : X → alexandroff X) ∩ {∞}) = ∅ := range_some_inter_none X @[simp] lemma compl_range_coe : (range (coe : X → alexandroff X))ᶜ = {∞} := compl_range_some X lemma compl_infty : ({∞}ᶜ : set (alexandroff X)) = range (coe : X → alexandroff X) := (@is_compl_range_coe_infty X).symm.compl_eq lemma compl_image_coe (s : set X) : (coe '' s : set (alexandroff X))ᶜ = coe '' sᶜ ∪ {∞} := by rw [coe_injective.compl_image_eq, compl_range_coe] lemma ne_infty_iff_exists {x : alexandroff X} : x ≠ ∞ ↔ ∃ (y : X), (y : alexandroff X) = x := by induction x using alexandroff.rec; simp instance can_lift : can_lift (alexandroff X) X coe (λ x, x ≠ ∞) := with_top.can_lift lemma not_mem_range_coe_iff {x : alexandroff X} : x ∉ range (coe : X → alexandroff X) ↔ x = ∞ := by rw [← mem_compl_iff, compl_range_coe, mem_singleton_iff] lemma infty_not_mem_range_coe : ∞ ∉ range (coe : X → alexandroff X) := not_mem_range_coe_iff.2 rfl lemma infty_not_mem_image_coe {s : set X} : ∞ ∉ (coe : X → alexandroff X) '' s := not_mem_subset (image_subset_range _ _) infty_not_mem_range_coe @[simp] lemma coe_preimage_infty : (coe : X → alexandroff X) ⁻¹' {∞} = ∅ := by { ext, simp } /-! ### Topological space structure on `alexandroff X` We define a topological space structure on `alexandroff X` so that `s` is open if and only if * `coe ⁻¹' s` is open in `X`; * if `∞ ∈ s`, then `(coe ⁻¹' s)ᶜ` is compact. Then we reformulate this definition in a few different ways, and prove that `coe : X → alexandroff X` is an open embedding. If `X` is not a compact space, then we also prove that `coe` has dense range, so it is a dense embedding. -/ variables [topological_space X] instance : topological_space (alexandroff X) := { is_open := λ s, (∞ ∈ s → is_compact ((coe : X → alexandroff X) ⁻¹' s)ᶜ) ∧ is_open ((coe : X → alexandroff X) ⁻¹' s), is_open_univ := by simp, is_open_inter := λ s t, begin rintros ⟨hms, hs⟩ ⟨hmt, ht⟩, refine ⟨_, hs.inter ht⟩, rintros ⟨hms', hmt'⟩, simpa [compl_inter] using (hms hms').union (hmt hmt') end, is_open_sUnion := λ S ho, begin suffices : is_open (coe ⁻¹' ⋃₀ S : set X), { refine ⟨_, this⟩, rintro ⟨s, hsS : s ∈ S, hs : ∞ ∈ s⟩, refine is_compact_of_is_closed_subset ((ho s hsS).1 hs) this.is_closed_compl _, exact compl_subset_compl.mpr (preimage_mono $ subset_sUnion_of_mem hsS) }, rw [preimage_sUnion], exact is_open_bUnion (λ s hs, (ho s hs).2) end } variables {s : set (alexandroff X)} {t : set X} lemma is_open_def : is_open s ↔ (∞ ∈ s → is_compact (coe ⁻¹' s : set X)ᶜ) ∧ is_open (coe ⁻¹' s : set X) := iff.rfl lemma is_open_iff_of_mem' (h : ∞ ∈ s) : is_open s ↔ is_compact (coe ⁻¹' s : set X)ᶜ ∧ is_open (coe ⁻¹' s : set X) := by simp [is_open_def, h] lemma is_open_iff_of_mem (h : ∞ ∈ s) : is_open s ↔ is_closed (coe ⁻¹' s : set X)ᶜ ∧ is_compact (coe ⁻¹' s : set X)ᶜ := by simp only [is_open_iff_of_mem' h, is_closed_compl_iff, and.comm] lemma is_open_iff_of_not_mem (h : ∞ ∉ s) : is_open s ↔ is_open (coe ⁻¹' s : set X) := by simp [is_open_def, h] lemma is_closed_iff_of_mem (h : ∞ ∈ s) : is_closed s ↔ is_closed (coe ⁻¹' s : set X) := have ∞ ∉ sᶜ, from λ H, H h, by rw [← is_open_compl_iff, is_open_iff_of_not_mem this, ← is_open_compl_iff, preimage_compl] lemma is_closed_iff_of_not_mem (h : ∞ ∉ s) : is_closed s ↔ is_closed (coe ⁻¹' s : set X) ∧ is_compact (coe ⁻¹' s : set X) := by rw [← is_open_compl_iff, is_open_iff_of_mem (mem_compl h), ← preimage_compl, compl_compl] @[simp] lemma is_open_image_coe {s : set X} : is_open (coe '' s : set (alexandroff X)) ↔ is_open s := by rw [is_open_iff_of_not_mem infty_not_mem_image_coe, preimage_image_eq _ coe_injective] lemma is_open_compl_image_coe {s : set X} : is_open (coe '' s : set (alexandroff X))ᶜ ↔ is_closed s ∧ is_compact s := begin rw [is_open_iff_of_mem, ← preimage_compl, compl_compl, preimage_image_eq _ coe_injective], exact infty_not_mem_image_coe end @[simp] lemma is_closed_image_coe {s : set X} : is_closed (coe '' s : set (alexandroff X)) ↔ is_closed s ∧ is_compact s := by rw [← is_open_compl_iff, is_open_compl_image_coe] /-- An open set in `alexandroff X` constructed from a closed compact set in `X` -/ def opens_of_compl (s : set X) (h₁ : is_closed s) (h₂ : is_compact s) : topological_space.opens (alexandroff X) := ⟨(coe '' s)ᶜ, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩ lemma infty_mem_opens_of_compl {s : set X} (h₁ : is_closed s) (h₂ : is_compact s) : ∞ ∈ opens_of_compl s h₁ h₂ := mem_compl infty_not_mem_image_coe @[continuity] lemma continuous_coe : continuous (coe : X → alexandroff X) := continuous_def.mpr (λ s hs, hs.right) lemma is_open_map_coe : is_open_map (coe : X → alexandroff X) := λ s, is_open_image_coe.2 lemma open_embedding_coe : open_embedding (coe : X → alexandroff X) := open_embedding_of_continuous_injective_open continuous_coe coe_injective is_open_map_coe lemma is_open_range_coe : is_open (range (coe : X → alexandroff X)) := open_embedding_coe.open_range lemma is_closed_infty : is_closed ({∞} : set (alexandroff X)) := by { rw [← compl_range_coe, is_closed_compl_iff], exact is_open_range_coe } lemma nhds_coe_eq (x : X) : 𝓝 ↑x = map (coe : X → alexandroff X) (𝓝 x) := (open_embedding_coe.map_nhds_eq x).symm lemma nhds_within_coe_image (s : set X) (x : X) : 𝓝[coe '' s] (x : alexandroff X) = map coe (𝓝[s] x) := (open_embedding_coe.to_embedding.map_nhds_within_eq _ _).symm lemma nhds_within_coe (s : set (alexandroff X)) (x : X) : 𝓝[s] ↑x = map coe (𝓝[coe ⁻¹' s] x) := (open_embedding_coe.map_nhds_within_preimage_eq _ _).symm lemma comap_coe_nhds (x : X) : comap (coe : X → alexandroff X) (𝓝 x) = 𝓝 x := (open_embedding_coe.to_inducing.nhds_eq_comap x).symm /-- If `x` is not an isolated point of `X`, then `x : alexandroff X` is not an isolated point of `alexandroff X`. -/ instance nhds_within_compl_coe_ne_bot (x : X) [h : ne_bot (𝓝[≠] x)] : ne_bot (𝓝[≠] (x : alexandroff X)) := by simpa [nhds_within_coe, preimage, coe_eq_coe] using h.map coe lemma nhds_within_compl_infty_eq : 𝓝[≠] (∞ : alexandroff X) = map coe (coclosed_compact X) := begin refine (nhds_within_basis_open ∞ _).ext (has_basis_coclosed_compact.map _) _ _, { rintro s ⟨hs, hso⟩, refine ⟨_, (is_open_iff_of_mem hs).mp hso, _⟩, simp }, { rintro s ⟨h₁, h₂⟩, refine ⟨_, ⟨mem_compl infty_not_mem_image_coe, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩, _⟩, simp [compl_image_coe, ← diff_eq, subset_preimage_image] } end /-- If `X` is a non-compact space, then `∞` is not an isolated point of `alexandroff X`. -/ instance nhds_within_compl_infty_ne_bot [noncompact_space X] : ne_bot (𝓝[≠] (∞ : alexandroff X)) := by { rw nhds_within_compl_infty_eq, apply_instance } @[priority 900] instance nhds_within_compl_ne_bot [∀ x : X, ne_bot (𝓝[≠] x)] [noncompact_space X] (x : alexandroff X) : ne_bot (𝓝[≠] x) := alexandroff.rec _ alexandroff.nhds_within_compl_infty_ne_bot (λ y, alexandroff.nhds_within_compl_coe_ne_bot y) x lemma nhds_infty_eq : 𝓝 (∞ : alexandroff X) = map coe (coclosed_compact X) ⊔ pure ∞ := by rw [← nhds_within_compl_infty_eq, nhds_within_compl_singleton_sup_pure] lemma has_basis_nhds_infty : (𝓝 (∞ : alexandroff X)).has_basis (λ s : set X, is_closed s ∧ is_compact s) (λ s, coe '' sᶜ ∪ {∞}) := begin rw nhds_infty_eq, exact (has_basis_coclosed_compact.map _).sup_pure _ end @[simp] lemma comap_coe_nhds_infty : comap (coe : X → alexandroff X) (𝓝 ∞) = coclosed_compact X := by simp [nhds_infty_eq, comap_sup, comap_map coe_injective] lemma le_nhds_infty {f : filter (alexandroff X)} : f ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' sᶜ ∪ {∞} ∈ f := by simp only [has_basis_nhds_infty.ge_iff, and_imp] lemma ultrafilter_le_nhds_infty {f : ultrafilter (alexandroff X)} : (f : filter (alexandroff X)) ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' s ∉ f := by simp only [le_nhds_infty, ← compl_image_coe, ultrafilter.mem_coe, ultrafilter.compl_mem_iff_not_mem] lemma tendsto_nhds_infty' {α : Type*} {f : alexandroff X → α} {l : filter α} : tendsto f (𝓝 ∞) l ↔ tendsto f (pure ∞) l ∧ tendsto (f ∘ coe) (coclosed_compact X) l := by simp [nhds_infty_eq, and_comm] lemma tendsto_nhds_infty {α : Type*} {f : alexandroff X → α} {l : filter α} : tendsto f (𝓝 ∞) l ↔ ∀ s ∈ l, f ∞ ∈ s ∧ ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s := tendsto_nhds_infty'.trans $ by simp only [tendsto_pure_left, has_basis_coclosed_compact.tendsto_left_iff, forall_and_distrib, and_assoc, exists_prop] lemma continuous_at_infty' {Y : Type*} [topological_space Y] {f : alexandroff X → Y} : continuous_at f ∞ ↔ tendsto (f ∘ coe) (coclosed_compact X) (𝓝 (f ∞)) := tendsto_nhds_infty'.trans $ and_iff_right (tendsto_pure_nhds _ _) lemma continuous_at_infty {Y : Type*} [topological_space Y] {f : alexandroff X → Y} : continuous_at f ∞ ↔ ∀ s ∈ 𝓝 (f ∞), ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s := continuous_at_infty'.trans $ by simp only [has_basis_coclosed_compact.tendsto_left_iff, exists_prop, and_assoc] lemma continuous_at_coe {Y : Type*} [topological_space Y] {f : alexandroff X → Y} {x : X} : continuous_at f x ↔ continuous_at (f ∘ coe) x := by rw [continuous_at, nhds_coe_eq, tendsto_map'_iff, continuous_at] /-- If `X` is not a compact space, then the natural embedding `X → alexandroff X` has dense range. -/ lemma dense_range_coe [noncompact_space X] : dense_range (coe : X → alexandroff X) := begin rw [dense_range, ← compl_infty], exact dense_compl_singleton _ end lemma dense_embedding_coe [noncompact_space X] : dense_embedding (coe : X → alexandroff X) := { dense := dense_range_coe, .. open_embedding_coe } @[simp] lemma specializes_coe {x y : X} : (x : alexandroff X) ⤳ y ↔ x ⤳ y := open_embedding_coe.to_inducing.specializes_iff @[simp] lemma inseparable_coe {x y : X} : inseparable (x : alexandroff X) y ↔ inseparable x y := open_embedding_coe.to_inducing.inseparable_iff lemma not_specializes_infty_coe {x : X} : ¬specializes ∞ (x : alexandroff X) := is_closed_infty.not_specializes rfl (coe_ne_infty x) lemma not_inseparable_infty_coe {x : X} : ¬inseparable ∞ (x : alexandroff X) := λ h, not_specializes_infty_coe h.specializes lemma not_inseparable_coe_infty {x : X} : ¬inseparable (x : alexandroff X) ∞ := λ h, not_specializes_infty_coe h.specializes' lemma inseparable_iff {x y : alexandroff X} : inseparable x y ↔ x = ∞ ∧ y = ∞ ∨ ∃ x' : X, x = x' ∧ ∃ y' : X, y = y' ∧ inseparable x' y' := by induction x using alexandroff.rec; induction y using alexandroff.rec; simp [not_inseparable_infty_coe, not_inseparable_coe_infty, coe_eq_coe] /-! ### Compactness and separation properties In this section we prove that `alexandroff X` is a compact space; it is a T₀ (resp., T₁) space if the original space satisfies the same separation axiom. If the original space is a locally compact Hausdorff space, then `alexandroff X` is a normal (hence, T₃ and Hausdorff) space. Finally, if the original space `X` is *not* compact and is a preconnected space, then `alexandroff X` is a connected space. -/ /-- For any topological space `X`, its one point compactification is a compact space. -/ instance : compact_space (alexandroff X) := { is_compact_univ := begin have : tendsto (coe : X → alexandroff X) (cocompact X) (𝓝 ∞), { rw [nhds_infty_eq], exact (tendsto_map.mono_left cocompact_le_coclosed_compact).mono_right le_sup_left }, convert ← this.is_compact_insert_range_of_cocompact continuous_coe, exact insert_none_range_some X end } /-- The one point compactification of a `t0_space` space is a `t0_space`. -/ instance [t0_space X] : t0_space (alexandroff X) := begin refine ⟨λ x y hxy, _⟩, rcases inseparable_iff.1 hxy with ⟨rfl, rfl⟩|⟨x, rfl, y, rfl, h⟩, exacts [rfl, congr_arg coe h.eq] end /-- The one point compactification of a `t1_space` space is a `t1_space`. -/ instance [t1_space X] : t1_space (alexandroff X) := { t1 := λ z, begin induction z using alexandroff.rec, { exact is_closed_infty }, { rw [← image_singleton, is_closed_image_coe], exact ⟨is_closed_singleton, is_compact_singleton⟩ } end } /-- The one point compactification of a locally compact Hausdorff space is a normal (hence, Hausdorff and regular) topological space. -/ instance [locally_compact_space X] [t2_space X] : normal_space (alexandroff X) := begin have key : ∀ z : X, ∃ u v : set (alexandroff X), is_open u ∧ is_open v ∧ ↑z ∈ u ∧ ∞ ∈ v ∧ disjoint u v, { intro z, rcases exists_open_with_compact_closure z with ⟨u, hu, huy', Hu⟩, exact ⟨coe '' u, (coe '' closure u)ᶜ, is_open_image_coe.2 hu, is_open_compl_image_coe.2 ⟨is_closed_closure, Hu⟩, mem_image_of_mem _ huy', mem_compl infty_not_mem_image_coe, (image_subset _ subset_closure).disjoint_compl_right⟩ }, refine @normal_of_compact_t2 _ _ _ ⟨λ x y hxy, _⟩, induction x using alexandroff.rec; induction y using alexandroff.rec, { exact (hxy rfl).elim }, { rcases key y with ⟨u, v, hu, hv, hxu, hyv, huv⟩, exact ⟨v, u, hv, hu, hyv, hxu, huv.symm⟩ }, { exact key x }, { exact separated_by_open_embedding open_embedding_coe (mt coe_eq_coe.mpr hxy) } end /-- If `X` is not a compact space, then `alexandroff X` is a connected space. -/ instance [preconnected_space X] [noncompact_space X] : connected_space (alexandroff X) := { to_preconnected_space := dense_embedding_coe.to_dense_inducing.preconnected_space, to_nonempty := infer_instance } /-- If `X` is an infinite type with discrete topology (e.g., `ℕ`), then the identity map from `cofinite_topology (alexandroff X)` to `alexandroff X` is not continuous. -/ lemma not_continuous_cofinite_topology_of_symm [infinite X] [discrete_topology X] : ¬(continuous (@cofinite_topology.of (alexandroff X)).symm) := begin inhabit X, simp only [continuous_iff_continuous_at, continuous_at, not_forall], use [cofinite_topology.of ↑(default : X)], simpa [nhds_coe_eq, nhds_discrete, cofinite_topology.nhds_eq] using (finite_singleton ((default : X) : alexandroff X)).infinite_compl end end alexandroff /-- A concrete counterexample shows that `continuous.homeo_of_equiv_compact_to_t2` cannot be generalized from `t2_space` to `t1_space`. Let `α = alexandroff ℕ` be the one-point compactification of `ℕ`, and let `β` be the same space `alexandroff ℕ` with the cofinite topology. Then `α` is compact, `β` is T1, and the identity map `id : α → β` is a continuous equivalence that is not a homeomorphism. -/ lemma continuous.homeo_of_equiv_compact_to_t2.t1_counterexample : ∃ (α β : Type) (Iα : topological_space α) (Iβ : topological_space β), by exactI compact_space α ∧ t1_space β ∧ ∃ f : α ≃ β, continuous f ∧ ¬ continuous f.symm := ⟨alexandroff ℕ, cofinite_topology (alexandroff ℕ), infer_instance, infer_instance, infer_instance, infer_instance, cofinite_topology.of, cofinite_topology.continuous_of, alexandroff.not_continuous_cofinite_topology_of_symm⟩
7137c3becabcfb2a092162ba47e9feef303d0448
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/basis.lean
f5da0f90de12a8e11ce15b55368b4f51c1371006
[ "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
54,253
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, Alexander Bentkamp -/ import algebra.big_operators.finsupp import algebra.big_operators.finprod import data.fintype.big_operators import linear_algebra.finsupp import linear_algebra.linear_independent import linear_algebra.linear_pmap import linear_algebra.projection /-! # Bases This file defines bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`, represented by a linear equiv `M ≃ₗ[R] ι →₀ R`. * the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι` * `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`. The converse, turning this isomorphism into a basis, is called `basis.of_repr`. * If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R` (saving you from having to work with `finsupp`). The converse, turning this isomorphism into a basis, is called `basis.of_equiv_fun`. * `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis elements `⇑b : ι → M₁`. * `basis.reindex` uses an equiv to map a basis to a different indexing set. * `basis.map` uses a linear equiv to map a basis to a different module. ## Main statements * `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis * `basis.ext` states that two linear maps are equal if they coincide on a basis. Similar results are available for linear equivs (if they coincide on the basis vectors), elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`. * `basis.of_vector_space` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. ## Tags basis, bases -/ noncomputable theory universe u open function set submodule open_locale classical big_operators variables {ι : Type*} {ι' : Type*} {R : Type*} {R₂ : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables [semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] section variables (ι) (R) (M) /-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`. The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`. To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`. They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`, available as `basis.repr`. -/ structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R)) end namespace basis instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩ variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M) section repr /-- `b i` is the `i`th basis vector. -/ instance : has_coe_to_fun (basis ι R M) (λ _, ι → M) := { coe := λ b i, b.repr.symm (finsupp.single i 1) } @[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) : ⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) := rfl protected lemma injective [nontrivial R] : injective b := b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp) lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i := calc b.repr.symm (finsupp.single i c) = b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one] ... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one] @[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 := linear_equiv.apply_symm_apply _ _ lemma repr_self_apply (j) [decidable (i = j)] : b.repr (b i) j = if i = j then 1 else 0 := by rw [repr_self, finsupp.single_apply] @[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v := calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp ... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) : by rw [finsupp.sum, linear_equiv.map_sum] ... = finsupp.total ι M R b v : by simp [repr_symm_single, finsupp.total_apply, finsupp.sum] @[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b := linear_map.ext (λ v, b.repr_symm_apply v) @[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v := by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v } @[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x := by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x } lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ := by rw [linear_equiv.range, finsupp.supported_univ] lemma mem_span_repr_support {ι : Type*} (b : basis ι R M) (m : M) : m ∈ span R (b '' (b.repr m).support) := (finsupp.mem_span_image_iff_total _).2 ⟨b.repr m, (by simp [finsupp.mem_supported_support])⟩ lemma repr_support_subset_of_mem_span {ι : Type*} (b : basis ι R M) (s : set ι) {m : M} (hm : m ∈ span R (b '' s)) : ↑(b.repr m).support ⊆ s := begin rcases (finsupp.mem_span_image_iff_total _).1 hm with ⟨l, hl, hlm⟩, rwa [←hlm, repr_total, ←finsupp.mem_supported R l] end end repr section coord /-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector with respect to the basis `b`. `b.coord i` is an element of the dual space. In particular, for finite-dimensional spaces it is the `ι`th basis vector of the dual space. -/ @[simps] def coord : M →ₗ[R] R := (finsupp.lapply i) ∘ₗ ↑b.repr lemma forall_coord_eq_zero_iff {x : M} : (∀ i, b.coord i x = 0) ↔ x = 0 := iff.trans (by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply]) b.repr.map_eq_zero_iff /-- The sum of the coordinates of an element `m : M` with respect to a basis. -/ noncomputable def sum_coords : M →ₗ[R] R := finsupp.lsum ℕ (λ i, linear_map.id) ∘ₗ (b.repr : M →ₗ[R] ι →₀ R) @[simp] lemma coe_sum_coords : (b.sum_coords : M → R) = λ m, (b.repr m).sum (λ i, id) := rfl lemma coe_sum_coords_eq_finsum : (b.sum_coords : M → R) = λ m, ∑ᶠ i, b.coord i m := begin ext m, simp only [basis.sum_coords, basis.coord, finsupp.lapply_apply, linear_map.id_coe, linear_equiv.coe_coe, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsum_eq_sum _ (b.repr m).finite_support, finsupp.sum, finset.finite_to_set_to_finset, id.def, finsupp.fun_support_eq], end @[simp] lemma coe_sum_coords_of_fintype [fintype ι] : (b.sum_coords : M → R) = ∑ i, b.coord i := begin ext m, simp only [sum_coords, finsupp.sum_fintype, linear_map.id_coe, linear_equiv.coe_coe, coord_apply, id.def, fintype.sum_apply, implies_true_iff, eq_self_iff_true, finsupp.coe_lsum, linear_map.coe_comp], end @[simp] lemma sum_coords_self_apply : b.sum_coords (b i) = 1 := by simp only [basis.sum_coords, linear_map.id_coe, linear_equiv.coe_coe, id.def, basis.repr_self, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsupp.sum_single_index] lemma dvd_coord_smul (i : ι) (m : M) (r : R) : r ∣ b.coord i (r • m) := ⟨b.coord i m, by simp⟩ lemma coord_repr_symm (b : basis ι R M) (i : ι) (f : ι →₀ R) : b.coord i (b.repr.symm f) = f i := by simp only [repr_symm_apply, coord_apply, repr_total] end coord section ext variables {R₁ : Type*} [semiring R₁] {σ : R →+* R₁} {σ' : R₁ →+* R} variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] variables {M₁ : Type*} [add_comm_monoid M₁] [module R₁ M₁] /-- Two linear maps are equal if they are equal on basis vectors. -/ theorem ext {f₁ f₂ : M →ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_map.map_sum, linear_map.map_smulₛₗ, h] } include σ' /-- Two linear equivs are equal if they are equal on basis vectors. -/ theorem ext' {f₁ f₂ : M ≃ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, h] } omit σ' /-- Two elements are equal if their coordinates are equal. -/ theorem ext_elem {x y : M} (h : ∀ i, b.repr x i = b.repr y i) : x = y := by { rw [← b.total_repr x, ← b.total_repr y], congr' 1, ext i, exact h i } lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} : ↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} : b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} : b i = x ↔ b.repr x = finsupp.single i 1 := ⟨λ h, h ▸ b.repr_self i, λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩ /-- An unbundled version of `repr_eq_iff` -/ lemma repr_apply_eq (f : M → ι → R) (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) : b.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by { simp [hsmul, pi.smul_apply] } }, have : (finsupp.lapply i) ∘ₗ ↑b.repr = f_i, { refine b.ext (λ j, _), show b.repr (b j) i = f (b j) i, rw [b.repr_self, f_eq] }, calc b.repr x i = f_i x : by { rw ← this, refl } ... = f x i : rfl end /-- Two bases are equal if they assign the same coordinates. -/ lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) : b₁ = b₂ := have b₁.repr = b₂.repr, by { ext, apply h }, by { cases b₁, cases b₂, simpa } /-- Two bases are equal if their basis vectors are the same. -/ @[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} (h : ∀ i, b₁ i = b₂ i) : b₁ = b₂ := suffices b₁.repr = b₂.repr, by { cases b₁, cases b₂, simpa }, repr_eq_iff'.mpr (λ i, by rw [h, b₂.repr_self]) end ext section map variables (f : M ≃ₗ[R] M') /-- Apply the linear equivalence `f` to the basis vectors. -/ @[simps] protected def map : basis ι R M' := of_repr (f.symm.trans b.repr) @[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl end map section map_coeffs variables {R' : Type*} [semiring R'] [module R' M] (f : R ≃+* R') (h : ∀ c (x : M), f c • x = c • x) include f h b local attribute [instance] has_smul.comp.is_scalar_tower /-- If `R` and `R'` are isomorphic rings that act identically on a module `M`, then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. See also `basis.algebra_map_coeffs` for the case where `f` is equal to `algebra_map`. -/ @[simps {simp_rhs := tt}] def map_coeffs : basis ι R' M := begin letI : module R' R := module.comp_hom R (↑f.symm : R' →+* R), haveI : is_scalar_tower R' R M := { smul_assoc := λ x y z, begin dsimp [(•)], rw [mul_smul, ←h, f.apply_symm_apply], end }, exact (of_repr $ (b.repr.restrict_scalars R').trans $ finsupp.map_range.linear_equiv (module.comp_hom.to_linear_equiv f.symm).symm ) end lemma map_coeffs_apply (i : ι) : b.map_coeffs f h i = b i := apply_eq_iff.mpr $ by simp [f.to_add_equiv_eq_coe] @[simp] lemma coe_map_coeffs : (b.map_coeffs f h : ι → M) = b := funext $ b.map_coeffs_apply f h end map_coeffs section reindex variables (b' : basis ι' R M') variables (e : ι ≃ ι') /-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/ def reindex : basis ι' R M := basis.of_repr (b.repr.trans (finsupp.dom_lcongr e)) lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') := show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) = b.repr.symm (finsupp.single (e.symm i') 1), by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single] @[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm := funext (b.reindex_apply e) @[simp] lemma coe_reindex_repr : ((b.reindex e).repr x : ι' → R) = b.repr x ∘ e.symm := funext $ λ i', show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _, by simp @[simp] lemma reindex_repr (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') := by rw coe_reindex_repr @[simp] lemma reindex_refl : b.reindex (equiv.refl ι) = b := eq_of_apply_eq $ λ i, by simp /-- `simp` normal form version of `range_reindex` -/ @[simp] lemma range_reindex' : set.range (b ∘ e.symm) = set.range b := by rw [range_comp, equiv.range_eq_univ, set.image_univ] lemma range_reindex : set.range (b.reindex e) = set.range b := by rw [coe_reindex, range_reindex'] /-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/ def reindex_range : basis (range b) R M := if h : nontrivial R then by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b)) else by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact basis.of_repr (module.subsingleton_equiv R M (range b)) lemma reindex_range_self (i : ι) (h := set.mem_range_self i) : b.reindex_range ⟨b i, h⟩ = b i := begin by_cases htr : nontrivial R, { letI := htr, simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b.injective, subtype.coe_mk] }, { letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr, letI := module.subsingleton R M, simp [reindex_range] } end lemma reindex_range_repr_self (i : ι) : b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 := calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) : congr_arg _ (b.reindex_range_self _ _).symm ... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _ @[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x := by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, } lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) : b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i := begin nontriviality, subst h, refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm, { intros x y, ext i, simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] }, { intros c x, ext i, simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] }, { intros i, ext j, simp only [reindex_range_repr_self], refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _, exact λ i j h, b.injective (subtype.mk.inj h) } end @[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) : b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i := b.reindex_range_repr' _ rfl section fintype variables [fintype ι] /-- `b.reindex_finset_range` is a basis indexed by `finset.univ.image b`, the finite set of basis vectors themselves. -/ def reindex_finset_range : basis (finset.univ.image b) R M := b.reindex_range.reindex ((equiv.refl M).subtype_equiv (by simp)) lemma reindex_finset_range_self (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range ⟨b i, h⟩ = b i := by { rw [reindex_finset_range, reindex_apply, reindex_range_apply], refl } @[simp] lemma reindex_finset_range_apply (x : finset.univ.image b) : b.reindex_finset_range x = x := by { rcases x with ⟨bi, hbi⟩, rcases finset.mem_image.mp hbi with ⟨i, -, rfl⟩, exact b.reindex_finset_range_self i } lemma reindex_finset_range_repr_self (i : ι) : b.reindex_finset_range.repr (b i) = finsupp.single ⟨b i, finset.mem_image_of_mem b (finset.mem_univ i)⟩ 1 := begin ext ⟨bi, hbi⟩, rw [reindex_finset_range, reindex_repr, reindex_range_repr_self], convert finsupp.single_apply_left ((equiv.refl M).subtype_equiv _).symm.injective _ _ _, refl end @[simp] lemma reindex_finset_range_repr (x : M) (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range.repr x ⟨b i, h⟩ = b.repr x i := by simp [reindex_finset_range] end fintype end reindex protected lemma linear_independent : linear_independent R b := linear_independent_iff.mpr $ λ l hl, calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm ... = 0 : by rw [hl, linear_equiv.map_zero] protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 := b.linear_independent.ne_zero i protected lemma mem_span (x : M) : x ∈ span R (range b) := by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) } protected lemma span_eq : span R (range b) = ⊤ := eq_top_iff.mpr $ λ x _, b.mem_span x lemma index_nonempty (b : basis ι R M) [nontrivial M] : nonempty ι := begin obtain ⟨x, y, ne⟩ : ∃ (x y : M), x ≠ y := nontrivial.exists_pair_ne, obtain ⟨i, _⟩ := not_forall.mp (mt b.ext_elem ne), exact ⟨i⟩ end /-- If the submodule `P` has a basis, `x ∈ P` iff it is a linear combination of basis vectors. -/ lemma mem_submodule_iff {P : submodule R M} (b : basis ι R P) {x : M} : x ∈ P ↔ ∃ (c : ι →₀ R), x = finsupp.sum c (λ i x, x • b i) := begin conv_lhs { rw [← P.range_subtype, ← submodule.map_top, ← b.span_eq, submodule.map_span, ← set.range_comp, ← finsupp.range_total] }, simpa only [@eq_comm _ x], end section constr variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] /-- Construct a linear map given the value at the basis. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') := { to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f) ∘ₗ ↑b.repr, inv_fun := λ f i, f (b i), left_inv := λ f, by { ext, simp }, right_inv := λ f, by { refine b.ext (λ i, _), simp }, map_add' := λ f g, by { refine b.ext (λ i, _), simp }, map_smul' := λ c f, by { refine b.ext (λ i, _), simp } } theorem constr_def (f : ι → M') : b.constr S f = (finsupp.total M' M' R id) ∘ₗ ((finsupp.lmap_domain R R f) ∘ₗ ↑b.repr) := rfl theorem constr_apply (f : ι → M') (x : M) : b.constr S f x = (b.repr x).sum (λ b a, a • f b) := by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply], rw finsupp.sum_map_domain_index; simp [add_smul] } @[simp] lemma constr_basis (f : ι → M') (i : ι) : (b.constr S f : M → M') (b i) = f i := by simp [basis.constr_apply, b.repr_self] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (h : ∀i, g i = f (b i)) : b.constr S g = f := b.ext $ λ i, (b.constr_basis S g i).trans (h i) lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f := b.constr_eq S $ λ x, rfl lemma constr_range [nonempty ι] {f : ι → M'} : (b.constr S f).range = span R (range f) := by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range, ← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ, ← finsupp.span_image_eq_map_total, set.image_id] @[simp] lemma constr_comp (f : M' →ₗ[R] M') (v : ι → M') : b.constr S (f ∘ v) = f.comp (b.constr S v) := b.ext (λ i, by simp only [basis.constr_basis, linear_map.comp_apply]) end constr section equiv variables (b' : basis ι' R M') (e : ι ≃ ι') variables [add_comm_monoid M''] [module R M''] /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent, `b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/ protected def equiv : M ≃ₗ[R] M' := b.repr.trans (b'.reindex e.symm).repr.symm @[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) := by simp [basis.equiv] @[simp] lemma equiv_refl : b.equiv b (equiv.refl ι) = linear_equiv.refl R M := b.ext' (λ i, by simp) @[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm := b'.ext' $ λ i, (b.equiv b' e).injective (by simp) @[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'') (e : ι ≃ ι') (e' : ι' ≃ ι'') : (b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') := b.ext' (λ i, by simp) @[simp] lemma map_equiv (b : basis ι R M) (b' : basis ι' R M') (e : ι ≃ ι') : b.map (b.equiv b' e) = b'.reindex e.symm := by { ext i, simp } end equiv section prod variables (b' : basis ι' R M') /-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'` to a `ι ⊕ ι'`-index basis for `M × M'`. For the specific case of `R × R`, see also `basis.fin_two_prod`. -/ protected def prod : basis (ι ⊕ ι') R (M × M') := of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm) @[simp] lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl @[simp] lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl lemma prod_apply_inl_fst (i) : (b.prod b' (sum.inl i)).1 = b i := b.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inl_injective } lemma prod_apply_inr_fst (i) : (b.prod b' (sum.inr i)).1 = 0 := b.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inr_ne_inl } lemma prod_apply_inl_snd (i) : (b.prod b' (sum.inl i)).2 = 0 := b'.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inl_ne_inr } lemma prod_apply_inr_snd (i) : (b.prod b' (sum.inr i)).2 = b' i := b'.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inr_injective } @[simp] lemma prod_apply (i) : b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i := by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply, prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply, prod_apply_inl_snd, prod_apply_inr_snd, comp_app] } end prod section no_zero_smul_divisors -- Can't be an instance because the basis can't be inferred. protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) : no_zero_smul_divisors R M := ⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin rw [← b.total_repr x, ← linear_map.map_smul] at hcx, have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx, rw smul_eq_zero at this, exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr)) end)⟩ protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := @smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _ lemma _root_.eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, finset.univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, convert (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end end no_zero_smul_divisors section singleton /-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/ protected def singleton (ι R : Type*) [unique ι] [semiring R] : basis ι R R := of_repr { to_fun := λ x, finsupp.single default x, inv_fun := λ f, f default, left_inv := λ x, by simp, right_inv := λ f, finsupp.unique_ext (by simp), map_add' := λ x y, by simp, map_smul' := λ c x, by simp } @[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) : basis.singleton ι R i = 1 := apply_eq_iff.mpr (by simp [basis.singleton]) @[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) : (basis.singleton ι R).repr x i = x := by simp [basis.singleton, unique.eq_default i] lemma basis_singleton_iff {R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (ι : Type*) [unique ι] : nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y := begin fsplit, { rintro ⟨b⟩, refine ⟨b default, b.linear_independent.ne_zero _, _⟩, simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq }, { rintro ⟨x, nz, w⟩, refine ⟨of_repr $ linear_equiv.symm { to_fun := λ f, f default • x, inv_fun := λ y, finsupp.single default (w y).some, left_inv := λ f, finsupp.unique_ext _, right_inv := λ y, _, map_add' := λ y z, _, map_smul' := λ c y, _ }⟩, { rw [finsupp.add_apply, add_smul] }, { rw [finsupp.smul_apply, smul_assoc], simp }, { refine smul_left_injective _ nz _, simp only [finsupp.single_eq_same], exact (w (f default • x)).some_spec }, { simp only [finsupp.single_eq_same], exact (w y).some_spec } } end end singleton section empty variables (M) /-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/ protected def empty [subsingleton M] [is_empty ι] : basis ι R M := of_repr 0 instance empty_unique [subsingleton M] [is_empty ι] : unique (basis ι R M) := { default := basis.empty M, uniq := λ ⟨x⟩, congr_arg of_repr $ subsingleton.elim _ _ } end empty end basis section fintype open basis open fintype variables [fintype ι] (b : basis ι R M) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans b.repr ({ to_fun := coe_fn, map_add' := finsupp.coe_add, map_smul' := finsupp.coe_smul, ..finsupp.equiv_fun_on_finite } : (ι →₀ R) ≃ₗ[R] (ι → R)) /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ b.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) : b.equiv_fun.symm x = ∑ i, x i • b i := by simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype] @[simp] lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl @[simp] lemma basis.map_equiv_fun (f : M ≃ₗ[R] M') : (b.map f).equiv_fun = f.symm.trans b.equiv_fun := rfl lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u := begin conv_rhs { rw ← b.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply] end lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u := b.sum_equiv_fun u @[simp] lemma basis.equiv_fun_self (i j : ι) : b.equiv_fun (b i) j = if i = j then 1 else 0 := by { rw [b.equiv_fun_apply, b.repr_self_apply] } lemma basis.repr_sum_self (c : ι → R) : ⇑(b.repr (∑ i, c i • b i)) = c := begin ext j, simp only [map_sum, linear_equiv.map_smul, repr_self, finsupp.smul_single, smul_eq_mul, mul_one, finset.sum_apply'], rw [finset.sum_eq_single j, finsupp.single_eq_same], { rintros i - hi, exact finsupp.single_eq_of_ne hi }, { intros, have := finset.mem_univ j, contradiction } end /-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`, as long as `ι` is finite. -/ def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M := basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_finite R R ι @[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) : (basis.of_equiv_fun e).repr x i = e x i := rfl @[simp] lemma basis.coe_of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : (basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) := funext $ λ i, e.injective $ funext $ λ j, by simp [basis.of_equiv_fun, ←finsupp.single_eq_pi_single, finsupp.single_eq_update] @[simp] lemma basis.of_equiv_fun_equiv_fun (v : basis ι R M) : basis.of_equiv_fun v.equiv_fun = v := begin ext j, simp only [basis.equiv_fun_symm_apply, basis.coe_of_equiv_fun], simp_rw [function.update_apply, ite_smul], simp only [finset.mem_univ, if_true, pi.zero_apply, one_smul, finset.sum_ite_eq', zero_smul], end variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] @[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) : (b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i := by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype] /-- If the submodule `P` has a finite basis, `x ∈ P` iff it is a linear combination of basis vectors. -/ lemma basis.mem_submodule_iff' {P : submodule R M} (b : basis ι R P) {x : M} : x ∈ P ↔ ∃ (c : ι → R), x = ∑ i, c i • b i := b.mem_submodule_iff.trans $ finsupp.equiv_fun_on_finite.exists_congr_left.trans $ exists_congr $ λ c, by simp [finsupp.sum_fintype] lemma basis.coord_equiv_fun_symm (i : ι) (f : ι → R) : b.coord i (b.equiv_fun.symm f) = f i := b.coord_repr_symm i (finsupp.equiv_fun_on_finite.symm f) end fintype end module section comm_semiring namespace basis variables [comm_semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] variables (b : basis ι R M) (b' : basis ι' R M') /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and `f`, `g` form a bijection between the basis vectors, `b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`. -/ def equiv' (f : M → M') (g : M' → M) (hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b) (hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) : M ≃ₗ[R] M' := { inv_fun := b'.constr R (g ∘ b'), left_inv := have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id, from (b.ext $ λ i, exists.elim (hf i) (λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi', b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])), λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this, right_inv := have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id, from (b'.ext $ λ i, exists.elim (hg i) (λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi', b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])), λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this, .. b.constr R (f ∘ b) } @[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) : b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) := b.constr_basis R _ _ @[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') : (b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) := b'.constr_basis R _ _ lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) : ∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i := begin conv_rhs { rw [← b'.sum_repr x] }, simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'], refine finset.sum_congr rfl (λ j _, _), rw [finsupp.smul_apply, smul_eq_mul, mul_comm] end end basis end comm_semiring section module open linear_map variables {v : ι → M} variables [ring R] [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'] [module R M''] variables {c d : R} {x y : M} variables (b : basis ι R M) namespace basis /-- Any basis is a maximal linear independent set. -/ lemma maximal [nontrivial R] (b : basis ι R M) : b.linear_independent.maximal := λ w hi h, begin -- If `range w` is strictly bigger than `range b`, apply le_antisymm h, -- then choose some `x ∈ range w \ range b`, intros x p, by_contradiction q, -- and write it in terms of the basis. have e := b.total_repr x, -- This then expresses `x` as a linear combination -- of elements of `w` which are in the range of `b`, let u : ι ↪ w := ⟨λ i, ⟨b i, h ⟨i, rfl⟩⟩, λ i i' r, b.injective (by simpa only [subtype.mk_eq_mk] using r)⟩, have r : ∀ i, b i = u i := λ i, rfl, simp_rw [finsupp.total_apply, r] at e, change (b.repr x).sum (λ (i : ι) (a : R), (λ (x : w) (r : R), r • (x : M)) (u i) a) = ((⟨x, p⟩ : w) : M) at e, rw [←finsupp.sum_emb_domain, ←finsupp.total_apply] at e, -- Now we can contradict the linear independence of `hi` refine hi.total_ne_of_not_mem_support _ _ e, simp only [finset.mem_map, finsupp.support_emb_domain], rintro ⟨j, -, W⟩, simp only [embedding.coe_fn_mk, subtype.mk_eq_mk, ←r] at W, apply q ⟨j, W⟩, end section mk variables (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v)) /-- A linear independent family of vectors spanning the whole module is a basis. -/ protected noncomputable def mk : basis ι R M := basis.of_repr { inv_fun := finsupp.total _ _ _ v, left_inv := λ x, hli.total_repr ⟨x, _⟩, right_inv := λ x, hli.repr_eq rfl, .. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp submodule.mem_top)) } @[simp] lemma mk_repr : (basis.mk hli hsp).repr x = hli.repr ⟨x, hsp submodule.mem_top⟩ := rfl lemma mk_apply (i : ι) : basis.mk hli hsp i = v i := show finsupp.total _ _ _ v _ = v i, by simp @[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v := funext (mk_apply _ _) variables {hli hsp} /-- Given a basis, the `i`th element of the dual basis evaluates to 1 on the `i`th element of the basis. -/ lemma mk_coord_apply_eq (i : ι) : (basis.mk hli hsp).coord i (v i) = 1 := show hli.repr ⟨v i, submodule.subset_span (mem_range_self i)⟩ i = 1, by simp [hli.repr_eq_single i] /-- Given a basis, the `i`th element of the dual basis evaluates to 0 on the `j`th element of the basis if `j ≠ i`. -/ lemma mk_coord_apply_ne {i j : ι} (h : j ≠ i) : (basis.mk hli hsp).coord i (v j) = 0 := show hli.repr ⟨v j, submodule.subset_span (mem_range_self j)⟩ i = 0, by simp [hli.repr_eq_single j, h] /-- Given a basis, the `i`th element of the dual basis evaluates to the Kronecker delta on the `j`th element of the basis. -/ lemma mk_coord_apply {i j : ι} : (basis.mk hli hsp).coord i (v j) = if j = i then 1 else 0 := begin cases eq_or_ne j i, { simp only [h, if_true, eq_self_iff_true, mk_coord_apply_eq i], }, { simp only [h, if_false, mk_coord_apply_ne h], }, end end mk section span variables (hli : linear_independent R v) /-- A linear independent family of vectors is a basis for their span. -/ protected noncomputable def span : basis ι R (span R (range v)) := basis.mk (linear_independent_span hli) $ begin intros x _, have h₁ : (coe : span R (range v) → M) '' set.range (λ i, subtype.mk (v i) _) = range v, { rw ← set.range_comp, refl }, have h₂ : map (submodule.subtype (span R (range v))) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), { rw [← span_image, submodule.coe_subtype, h₁] }, have h₃ : (x : M) ∈ map (submodule.subtype (span R (range v))) (span R (set.range (λ i, subtype.mk (v i) _))), { rw h₂, apply subtype.mem x }, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, { rw [subtype.ext_iff, ← hy₂], simp }, rwa h_x_eq_y end protected lemma span_apply (i : ι) : (basis.span hli i : M) = v i := congr_arg (coe : span R (range v) → M) $ basis.mk_apply (linear_independent_span hli) _ i end span lemma group_smul_span_eq_top {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → G} : submodule.span R (set.range (w • v)) = ⊤ := begin rw eq_top_iff, intros j hj, rw ← hv at hj, rw submodule.mem_span at hj ⊢, refine λ p hp, hj p (λ u hu, _), obtain ⟨i, rfl⟩ := hu, have : ((w i)⁻¹ • 1 : R) • w i • v i ∈ p := p.smul_mem ((w i)⁻¹ • 1 : R) (hp ⟨i, rfl⟩), rwa [smul_one_smul, inv_smul_smul] at this, end /-- Given a basis `v` and a map `w` such that for all `i`, `w i` are elements of a group, `group_smul` provides the basis corresponding to `w • v`. -/ def group_smul {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] (v : basis ι R M) (w : ι → G) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge lemma group_smul_apply {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : basis ι R M} {w : ι → G} (i : ι) : v.group_smul w i = (w • v : ι → M) i := mk_apply (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq).ge i lemma units_smul_span_eq_top {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → Rˣ} : submodule.span R (set.range (w • v)) = ⊤ := group_smul_span_eq_top hv /-- Given a basis `v` and a map `w` such that for all `i`, `w i` is a unit, `smul_of_is_unit` provides the basis corresponding to `w • v`. -/ def units_smul (v : basis ι R M) (w : ι → Rˣ) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge lemma units_smul_apply {v : basis ι R M} {w : ι → Rˣ} (i : ι) : v.units_smul w i = w i • v i := mk_apply (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq).ge i @[simp] lemma coord_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (i : ι) : (e.units_smul w).coord i = (w i)⁻¹ • e.coord i := begin apply e.ext, intros j, transitivity ((e.units_smul w).coord i) ((w j)⁻¹ • (e.units_smul w) j), { congr, simp [basis.units_smul, ← mul_smul], }, simp only [basis.coord_apply, linear_map.smul_apply, basis.repr_self, units.smul_def, smul_hom_class.map_smul, finsupp.single_apply], split_ifs with h h, { simp [h] }, { simp } end @[simp] lemma repr_units_smul (e : basis ι R₂ M) (w : ι → R₂ˣ) (v : M) (i : ι) : (e.units_smul w).repr v i = (w i)⁻¹ • e.repr v i := congr_arg (λ f : M →ₗ[R₂] R₂, f v) (e.coord_units_smul w i) /-- A version of `smul_of_units` that uses `is_unit`. -/ def is_unit_smul (v : basis ι R M) {w : ι → R} (hw : ∀ i, is_unit (w i)): basis ι R M := units_smul v (λ i, (hw i).unit) lemma is_unit_smul_apply {v : basis ι R M} {w : ι → R} (hw : ∀ i, is_unit (w i)) (i : ι) : v.is_unit_smul hw i = w i • v i := units_smul_apply i section fin /-- Let `b` be a basis for a submodule `N` of `M`. If `y : M` is linear independent of `N` and `y` and `N` together span the whole of `M`, then there is a basis for `M` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R M := have span_b : submodule.span R (set.range (N.subtype ∘ b)) = N, { rw [set.range_comp, submodule.span_image, b.span_eq, submodule.map_subtype_top] }, @basis.mk _ _ _ (fin.cons y (N.subtype ∘ b) : fin (n + 1) → M) _ _ _ ((b.linear_independent.map' N.subtype (submodule.ker_subtype _)) .fin_cons' _ _ $ by { rintros c ⟨x, hx⟩ hc, rw span_b at hx, exact hli c x hx hc }) (λ x _, by { rw [fin.range_cons, submodule.mem_span_insert', span_b], exact hsp x }) @[simp] lemma coe_mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons y b hli hsp : fin (n + 1) → M) = fin.cons y (coe ∘ b) := coe_mk _ _ /-- Let `b` be a basis for a submodule `N ≤ O`. If `y ∈ O` is linear independent of `N` and `y` and `N` together span the whole of `O`, then there is a basis for `O` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R O := mk_fin_cons ⟨y, yO⟩ (b.map (submodule.comap_subtype_equiv_of_le hNO).symm) (λ c x hc hx, hli c x (submodule.mem_comap.mp hc) (congr_arg coe hx)) (λ z, hsp z z.2) @[simp] lemma coe_mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons_of_le y yO b hNO hli hsp : fin (n + 1) → O) = fin.cons ⟨y, yO⟩ (submodule.of_le hNO ∘ b) := coe_mk_fin_cons _ _ _ _ /-- The basis of `R × R` given by the two vectors `(1, 0)` and `(0, 1)`. -/ protected def fin_two_prod (R : Type*) [semiring R] : basis (fin 2) R (R × R) := basis.of_equiv_fun (linear_equiv.fin_two_arrow R R).symm @[simp] lemma fin_two_prod_zero (R : Type*) [semiring R] : basis.fin_two_prod R 0 = (1, 0) := by simp [basis.fin_two_prod] @[simp] lemma fin_two_prod_one (R : Type*) [semiring R] : basis.fin_two_prod R 1 = (0, 1) := by simp [basis.fin_two_prod] @[simp] lemma coe_fin_two_prod_repr {R : Type*} [semiring R] (x : R × R) : ⇑((basis.fin_two_prod R).repr x) = ![x.fst, x.snd] := rfl end fin end basis end module section induction variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end end induction section division_ring variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule namespace basis section exists_basis /-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/ noncomputable def extend (hs : linear_independent K (coe : s → V)) : basis _ K V := basis.mk (@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _)) (set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s)) lemma extend_apply_self (hs : linear_independent K (coe : s → V)) (x : hs.extend _) : basis.extend hs x = x := basis.mk_apply _ _ _ @[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) : ⇑(basis.extend hs) = coe := funext (extend_apply_self hs) lemma range_extend (hs : linear_independent K (coe : s → V)) : range (basis.extend hs) = hs.extend (subset_univ _) := by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq] /-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/ noncomputable def sum_extend (hs : linear_independent K v) : basis (ι ⊕ _) K V := let s := set.range v, e : ι ≃ s := equiv.of_injective v hs.injective, b := hs.to_subtype_range.extend (subset_univ (set.range v)) in (basis.extend hs.to_subtype_range).reindex $ equiv.symm $ calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _) lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) : s ⊆ hs.extend (set.subset_univ _) := hs.subset_extend _ section variables (K V) /-- A set used to index `basis.of_vector_space`. -/ noncomputable def of_vector_space_index : set V := (linear_independent_empty K V).extend (subset_univ _) /-- Each vector space has a basis. -/ noncomputable def of_vector_space : basis (of_vector_space_index K V) K V := basis.extend (linear_independent_empty K V) lemma of_vector_space_apply_self (x : of_vector_space_index K V) : of_vector_space K V x = x := basis.mk_apply _ _ _ @[simp] lemma coe_of_vector_space : ⇑(of_vector_space K V) = coe := funext (λ x, of_vector_space_apply_self K V x) lemma of_vector_space_index.linear_independent : linear_independent K (coe : of_vector_space_index K V → V) := by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self } lemma range_of_vector_space : range (of_vector_space K V) = of_vector_space_index K V := range_extend _ lemma exists_basis : ∃ s : set V, nonempty (basis s K V) := ⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩ end end exists_basis end basis open fintype variables (K V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := ⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩ section atoms_of_submodule_lattice variables {K V} /-- For a module over a division ring, the span of a nonzero element is an atom of the lattice of submodules. -/ lemma nonzero_span_atom (v : V) (hv : v ≠ 0) : is_atom (span K {v} : submodule K V) := begin split, { rw submodule.ne_bot_iff, exact ⟨v, ⟨mem_span_singleton_self v, hv⟩⟩ }, { intros T hT, by_contra, apply hT.2, change (span K {v}) ≤ T, simp_rw [span_singleton_le_iff_mem, ← ne.def, submodule.ne_bot_iff] at *, rcases h with ⟨s, ⟨hs, hz⟩⟩, cases (mem_span_singleton.1 (hT.1 hs)) with a ha, have h : a ≠ 0, by { intro h, rw [h, zero_smul] at ha, exact hz ha.symm }, apply_fun (λ x, a⁻¹ • x) at ha, simp_rw [← mul_smul, inv_mul_cancel h, one_smul, ha] at *, exact smul_mem T _ hs}, end /-- The atoms of the lattice of submodules of a module over a division ring are the submodules equal to the span of a nonzero element of the module. -/ lemma atom_iff_nonzero_span (W : submodule K V) : is_atom W ↔ ∃ (v : V) (hv : v ≠ 0), W = span K {v} := begin refine ⟨λ h, _, λ h, _ ⟩, { cases h with hbot h, rcases ((submodule.ne_bot_iff W).1 hbot) with ⟨v, ⟨hW, hv⟩⟩, refine ⟨v, ⟨hv, _⟩⟩, by_contra heq, specialize h (span K {v}), rw [span_singleton_eq_bot, lt_iff_le_and_ne] at h, exact hv (h ⟨(span_singleton_le_iff_mem v W).2 hW, ne.symm heq⟩) }, { rcases h with ⟨v, ⟨hv, rfl⟩⟩, exact nonzero_span_atom v hv }, end /-- The lattice of submodules of a module over a division ring is atomistic. -/ instance : is_atomistic (submodule K V) := { eq_Sup_atoms := begin intro W, use {T : submodule K V | ∃ (v : V) (hv : v ∈ W) (hz : v ≠ 0), T = span K {v}}, refine ⟨submodule_eq_Sup_le_nonzero_spans W, _⟩, rintros _ ⟨w, ⟨_, ⟨hw, rfl⟩⟩⟩, exact nonzero_span_atom w hw end } end atoms_of_submodule_lattice variables {K V} lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ[K] V, g.comp f = linear_map.id := begin let B := basis.of_vector_space_index K V, let hB := basis.of_vector_space K V, have hB₀ : _ := hB.linear_independent.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) := @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀ (show disjoint _ _, by simp [hf_inj]), rwa [basis.range_of_vector_space K V] at h₁ }, let C := this.extend (subset_univ _), have BC := this.subset_extend (subset_univ _), let hC := basis.extend this, haveI : inhabited V := ⟨0⟩, refine ⟨hC.constr ℕ (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩, rw image_subset_iff at BC, have fb_eq : f b = hC ⟨f b, BC b.2⟩, { change f b = basis.extend this _, rw [basis.extend_apply_self, subtype.coe_mk] }, dsimp [hB], rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ instance module.submodule.complemented_lattice : complemented_lattice (submodule K V) := ⟨submodule.exists_is_compl⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ[K] V, f.comp g = linear_map.id := begin let C := basis.of_vector_space_index K V', let hC := basis.of_vector_space K V', haveI : inhabited V := ⟨0⟩, use hC.constr ℕ (C.restrict (inv_fun f)), refine hC.ext (λ c, _), rw [linear_map.comp_apply, hC.constr_basis], simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end /-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole space. -/ lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') : ∃ g : V →ₗ[K] V', g.comp p.subtype = f := let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩ open submodule linear_map /-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map `f : V →ₗ[K] K` such that `p ≤ ker f`. -/ lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) : ∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f := begin rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp, rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩, refine ⟨f, _, _⟩, { rintro rfl, rw [linear_map.zero_comp] at hf, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1, simpa using (linear_map.congr_fun hf _).trans this }, { refine λ x hx, mem_ker.2 _, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0, simpa using (linear_map.congr_fun hf _).trans this } end theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty (((V ⧸ p) × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) end division_ring
bcf765795bdf2b440bb01fb76ccb211dbf1ee266
bd30ef9a38da5172e55165b5cf19d92706763afa
/src/array_group.lean
72eed949de941aec887536110375f8d4a9b0e186
[]
no_license
kendfrey/rubiks-cube-group
8838ce34704d8d150e5feba6f1e536b3d228dd37
3baebd73972384294931c75d584a491eb0fbc15c
refs/heads/master
1,671,557,772,358
1,601,554,362,000
1,601,554,362,000
285,715,961
21
0
null
null
null
null
UTF-8
Lean
false
false
1,021
lean
import algebra.group open array variables {n : ℕ} {α : Type*} [group α] (a b c : array n α) instance : has_mul (array n α) := ⟨array.map₂ (*)⟩ instance : has_one (array n α) := ⟨mk_array n 1⟩ instance : has_inv (array n α) := ⟨flip array.map has_inv.inv⟩ private lemma mul_assoc : a * b * c = a * (b * c) := begin apply array.ext, intros i, apply mul_assoc, end private lemma one_mul : 1 * a = a := begin apply array.ext, intros i, apply one_mul, end private lemma mul_one : a * 1 = a := begin apply array.ext, intros i, apply mul_one, end private lemma mul_left_inv : a⁻¹ * a = 1 := begin apply array.ext, intros i, apply mul_left_inv, end instance array_group : group (array n α) := { mul := (*), mul_assoc := mul_assoc, one := 1, one_mul := one_mul, mul_one := mul_one, inv := has_inv.inv, mul_left_inv := mul_left_inv, } @[simp] lemma array.read_mul {a₁ a₂ : array n α} {i : fin n} : (a₁ * a₂).read i = a₁.read i * a₂.read i := rfl
dfae3222a6f2600b160a0793339f23d38a7215e3
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebra/group_power.lean
54256f15b6f4bcea31626ec9ac752123c3065d4a
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
29,110
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import algebra.group import data.int.basic data.list.basic universes u v variable {α : Type u} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [monoid α] (a : α) : ℕ → α | 0 := 1 | (n+1) := a * monoid.pow n def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α := @monoid.pow (multiplicative α) _ a n precedence `•`:70 localized "infix ` • ` := add_monoid.smul" in add_monoid @[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩ /- monoid -/ section monoid variables [monoid α] {β : Type u} [add_monoid β] @[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl @[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl @[simp] theorem pow_one (a : α) : a^1 = a := mul_one _ @[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _ theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; [rw [pow_zero, one_mul, mul_one], rw [pow_succ, mul_assoc, ih]] theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a := @pow_mul_comm' (multiplicative β) _ theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a := by rw [succ_smul, smul_add_comm'] theorem pow_two (a : α) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_smul (a : β) : 2•a = a + a := show a+(a+0)=a+a, by rw add_zero theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ, ← pow_mul_comm', ← mul_assoc, ← ih, ← pow_succ']]; refl theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a := @pow_add (multiplicative β) _ @[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) := by induction n with n ih; [refl, rw [succ_smul, ih, zero_add]] theorem pow_mul (a : α) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) := @pow_mul (multiplicative β) _ theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) := by rw [mul_comm, add_monoid.mul_smul'] @[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n := nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _) theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _ theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a := @pow_bit1 (multiplicative β) _ theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a := @pow_mul_comm (multiplicative β) _ @[simp] theorem list.prod_repeat (a : α) (n : ℕ) : (list.repeat a n).prod = a ^ n := by induction n with n ih; [refl, rw [list.repeat_succ, list.prod_cons, ih]]; refl @[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative β) _ @[simp] lemma units.coe_pow (u : units α) (n : ℕ) : ((u ^ n : units α) : α) = u ^ n := by induction n; simp [*, pow_succ] end monoid namespace is_monoid_hom variables {β : Type v} [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] theorem map_pow (a : α) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := is_monoid_hom.map_one f | (nat.succ n) := by rw [pow_succ, is_monoid_hom.map_mul f, map_pow n]; refl end is_monoid_hom namespace is_add_monoid_hom variables {β : Type*} [add_monoid α] [add_monoid β] (f : α → β) [is_add_monoid_hom f] theorem map_smul (a : α) : ∀(n : ℕ), f (n • a) = n • (f a) | 0 := is_add_monoid_hom.map_zero f | (nat.succ n) := by rw [succ_smul, is_add_monoid_hom.map_add f, map_smul n]; refl end is_add_monoid_hom namespace monoid_hom variables {β : Type v} [monoid α] [monoid β] (f : α →* β) @[simp] theorem map_pow (a : α) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (nat.succ n) := by rw [pow_succ, f.map_mul, map_pow n]; refl end monoid_hom namespace add_monoid_hom variables {β : Type*} [add_monoid α] [add_monoid β] (f : α →+ β) @[simp] theorem map_smul (a : α) : ∀(n : ℕ), f (n • a) = n • (f a) | 0 := f.map_zero | (nat.succ n) := by rw [succ_smul, f.map_add, map_smul n]; refl end add_monoid_hom @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ, mul_comm, ih]] @[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n := by induction m with m ih; [rw [add_monoid.zero_smul, zero_mul], rw [succ_smul', ih, nat.succ_mul]] /- commutative monoid -/ section comm_monoid variables [comm_monoid α] {β : Type*} [add_comm_monoid β] theorem mul_pow (a b : α) (n : ℕ) : (a * b)^n = a^n * b^n := by induction n with n ih; [exact (mul_one _).symm, simp only [pow_succ, ih, mul_assoc, mul_left_comm]] theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b := @mul_pow (multiplicative β) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : α → α) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance add_monoid.smul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (add_monoid.smul n : β → β) := { map_add := λ _ _, add_monoid.smul_add _ _ _, map_zero := add_monoid.smul_zero _ } end comm_monoid section group variables [group α] {β : Type*} [add_group β] section nat @[simp] theorem inv_pow (a : α) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) := @inv_pow (multiplicative β) _ theorem pow_sub (a : α) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, n ≤ m → (m - n)•a = m•a - n•a := @pow_sub (multiplicative β) _ theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _) theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) := @pow_inv_comm (multiplicative β) _ end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : α) : ℤ → α | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ def gsmul (n : ℤ) (a : β) : β := @gpow (multiplicative β) _ a n @[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩ localized "infix ` • `:70 := gsmul" in add_group localized "infix ` •ℕ `:70 := add_monoid.smul" in smul localized "infix ` •ℤ `:70 := gsmul" in smul @[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl @[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl @[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl @[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _ @[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:α), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n • (0 : β) = 0 := @one_gpow (multiplicative β) _ @[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm @[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) := @gpow_neg (multiplicative β) _ theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := congr_arg has_neg.neg $ add_monoid.one_smul x theorem gsmul_one [has_one β] (n : ℤ) : n • (1 : β) = n := begin cases n, { rw [gsmul_of_nat, add_monoid.smul_one, int.cast_of_nat] }, { rw [gsmul_neg_succ, add_monoid.smul_one, int.cast_neg_succ_of_nat, nat.cast_succ] } end theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) private lemma gpow_add_aux (a : α) (m n : nat) : a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] := or.elim (nat.lt_or_ge m (nat.succ n)) (assume h1 : m < succ n, have h2 : m ≤ n, from le_of_lt_succ h1, suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by rwa [of_nat_add_neg_succ_of_nat_of_lt h1], show (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw [← succ_sub h2, pow_sub _ (le_of_lt h1), mul_inv_rev, inv_inv]; refl) (assume : m ≥ succ n, suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux, gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm] | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this, by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a := @gpow_add (multiplicative β) _ theorem gpow_add_one (a : α) (i : ℤ) : a ^ (i + 1) = a ^ i * a := by rw [gpow_add, gpow_one] theorem add_one_gsmul : ∀ (a : β) (i : ℤ), (i + 1) • a = i • a + a := @gpow_add_one (multiplicative β) _ theorem gpow_one_add (a : α) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : β) (i : ℤ), (1 + i) • a = a + i • a := @gpow_one_add (multiplicative β) _ theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a := @gpow_mul_comm (multiplicative β) _ theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n | (m : ℕ) (n : ℕ) := pow_mul _ _ _ | (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $ show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl | -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $ show (a ^ (m.succ * n))⁻¹ = _, by rw [pow_mul, ← inv_pow]; refl | -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ show _ = (_⁻¹^_)⁻¹, by rw [inv_pow, inv_inv] theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) := @gpow_mul (multiplicative β) _ theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _ theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a := @gpow_bit1 (multiplicative β) _ theorem gsmul_neg (a : β) (n : ℤ) : gsmul n (- a) = - gsmul n a := begin induction n using int.induction_on with z ih z ih, { simp }, { rw [add_comm] {occs := occurrences.pos [1]}, simp [add_gsmul, ih, -add_comm] }, { rw [sub_eq_add_neg, add_comm] {occs := occurrences.pos [1]}, simp [ih, add_gsmul, neg_gsmul, -add_comm] } end end group namespace is_group_hom variables {β : Type v} [group α] [group β] (f : α → β) [is_group_hom f] theorem map_pow (a : α) (n : ℕ) : f (a ^ n) = f a ^ n := is_monoid_hom.map_pow f a n theorem map_gpow (a : α) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact is_group_hom.map_pow f _ _, exact (is_group_hom.map_inv f _).trans (congr_arg _ $ is_group_hom.map_pow f _ _)] end is_group_hom namespace is_add_group_hom variables {β : Type v} [add_group α] [add_group β] (f : α → β) [is_add_group_hom f] theorem map_smul (a : α) (n : ℕ) : f (n • a) = n • f a := is_add_monoid_hom.map_smul f a n theorem map_gsmul (a : α) (n : ℤ) : f (gsmul n a) = gsmul n (f a) := @is_group_hom.map_gpow (multiplicative α) (multiplicative β) _ _ f _ a n end is_add_group_hom namespace monoid_hom variables {β : Type v} [group α] [group β] (f : α →* β) @[simp] theorem map_gpow (a : α) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] end monoid_hom namespace add_monoid_hom variables {β : Type v} [add_group α] [add_group β] (f : α →+ β) @[simp] theorem map_gsmul (a : α) (n : ℤ) : f (gsmul n a) = gsmul n (f a) := by cases n; [exact f.map_smul _ _, exact (f.map_neg _).trans (congr_arg _ $ f.map_smul _ _)] end add_monoid_hom local infix ` •ℤ `:70 := gsmul open_locale smul section comm_monoid variables [comm_group α] {β : Type*} [add_comm_group β] theorem mul_gpow (a b : α) : ∀ n:ℤ, (a * b)^n = a^n * b^n | (n : ℕ) := mul_pow a b n | -[1+ n] := show _⁻¹=_⁻¹*_⁻¹, by rw [mul_pow, mul_inv_rev, mul_comm] theorem gsmul_add : ∀ (a b : β) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative β) _ theorem gsmul_sub : ∀ (a b : β) (n : ℤ), gsmul n (a - b) = gsmul n a - gsmul n b := by simp [gsmul_add, gsmul_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : α → α) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : β → β) := { map_add := λ _ _, gsmul_add _ _ n } end comm_monoid section group @[instance] theorem is_add_group_hom.gsmul {α β} [add_group α] [add_comm_group β] (f : α → β) [is_add_group_hom f] (z : ℤ) : is_add_group_hom (λa, gsmul z (f a)) := { map_add := assume a b, by rw [is_add_hom.map_add f, gsmul_add] } end group @[simp] lemma with_bot.coe_smul [add_monoid α] (a : α) (n : ℕ) : ((add_monoid.smul n a : α) : with_bot α) = add_monoid.smul n a := by induction n; simp [*, succ_smul]; refl theorem add_monoid.smul_eq_mul' [semiring α] (a : α) (n : ℕ) : n • a = a * n := by induction n with n ih; [rw [add_monoid.zero_smul, nat.cast_zero, mul_zero], rw [succ_smul', ih, nat.cast_succ, mul_add, mul_one]] theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a := by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm] theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) := by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc] theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b := by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc] lemma zero_pow [semiring α] : ∀ {n : ℕ}, 0 < n → (0 : α) ^ n = 0 | (n+1) _ := zero_mul _ @[simp, move_cast] theorem nat.cast_pow [semiring α] (n m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp, move_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] theorem is_semiring_hom.map_pow {β} [semiring α] [semiring β] (f : α → β) [is_semiring_hom f] (x : α) (n : ℕ) : f (x ^ n) = f x ^ n := by induction n with n ih; [exact is_semiring_hom.map_one f, rw [pow_succ, pow_succ, is_semiring_hom.map_mul f, ih]] @[simp] lemma ring_hom.map_pow {β} [semiring α] [semiring β] (f : α →+* β) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := monoid_hom.map_pow f.to_monoid_hom a theorem neg_one_pow_eq_or {R} [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [comm_semiring α] (a : α) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a | (n : ℕ) := add_monoid.smul_eq_mul _ _ | -[1+ n] := show -(_•_)=-_*_, by rw [neg_mul_eq_neg_mul_symm, add_monoid.smul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, int.mul_cast_comm] theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp, move_cast] theorem int.cast_pow [ring α] (n : ℤ) (m : ℕ) : (↑(n ^ m) : α) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring α] {n : ℕ} : (-1 : α) ^ n = -1 ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem sq_sub_sq [comm_ring α] (a b : α) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [domain α] {x : α} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[field_simps] theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h @[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : (1 / a) ^ n = 1 / a ^ n := by induction n with n ih; [exact (div_one _).symm, rw [pow_succ', ih, division_ring.one_div_mul_one_div (pow_ne_zero _ ha) ha]]; refl @[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ := by simpa only [inv_eq_one_div] using one_div_pow ha n @[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div] theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a | 0 := le_refl _ | (n+1) := add_nonneg' H (add_monoid.smul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring α] (n : ℕ) : abs ((-1 : α)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] @[field_simps] lemma inv_pow' [discrete_field α] (a : α) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ := by induction n; simp [*, pow_succ, mul_inv', mul_comm] @[field_simps] lemma pow_div [discrete_field α] (a b : α) (n : ℕ) : (a / b)^n = a^n / b^n := by simp [div_eq_mul_inv, mul_pow, inv_pow'] lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n | 0 ha := inv_one | (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha] namespace add_monoid variable [ordered_comm_monoid α] theorem smul_le_smul {a : α} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n • a ≤ m • a := let ⟨k, hk⟩ := nat.le.dest h in calc n • a = n • a + 0 : (add_zero _).symm ... ≤ n • a + k • a : add_le_add_left' (smul_nonneg ha _) ... = m • a : by rw [← hk, add_smul] lemma smul_le_smul_of_le_right {a b : α} (hab : a ≤ b) : ∀ i : ℕ, i • a ≤ i • b | 0 := by simp | (k+1) := add_le_add' hab (smul_le_smul_of_le_right _) end add_monoid namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring α] theorem pow_pos {a : α} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := canonically_ordered_semiring.zero_lt_one | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : α} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : α} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring α] theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : α} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_right_inj {x y : α} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : α} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) • a ≤ (1 + a) * (1 + n • a) : by simpa [succ_smul, mul_add, add_mul, add_monoid.mul_smul_left] using add_monoid.smul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : α} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : α} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : α} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : α} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : α} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : α} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : α} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : α} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : α) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring α] (a : α) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring α] {a : α} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n • (a * a * (2 + a)) + a * a, from add_nonneg (add_monoid.smul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) • a ≤ 1 + (n + 2) • a + (n • (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n • a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_smul, add_monoid.smul_add, add_monoid.mul_smul_assoc, (add_monoid.mul_smul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring α] {a : α} (H : -1 ≤ a) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma div_sq_cancel {α} [field α] {a : α} (ha : a ≠ 0) (b : α) : a^2 * b / a = a * b := by rw [pow_two, mul_assoc, mul_div_cancel_left _ ha]
39b6d268dde3ebe8873b9364283d11e85f8f78de
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/order/well_founded_set.lean
5b090b714432dba21170e6c34fb14b5d9a381f57
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,975
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.set.finite import order.well_founded import order.order_iso_nat import algebra.pointwise /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.partially_well_ordered_on s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that ### Definitions for Hahn Series * `set.add_antidiagonal s t a` and `set.mul_antidiagonal s t a` are the sets of pairs of elements from `s` and `t` that add/multiply to `a`. * `finset.add_antidiagonal` and `finset.mul_antidiagonal` are finite versions of `set.add_antidiagonal` and `set.mul_antidiagonal` defined when `s` and `t` are well-founded. ## Main Results * Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`, shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ open_locale pointwise variables {α : Type*} namespace set /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded (λ (a : s) (b : s), r a b) lemma well_founded_on_iff {s : set α} {r : α → α → Prop} : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases well_founded.well_founded_iff_has_min.1 h (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end lemma well_founded_on.induction {s : set α} {r : α → α → Prop} (hs : s.well_founded_on r) {x : α} (hx : x ∈ s) {P : α → Prop} (hP : ∀ (y ∈ s), (∀ (z ∈ s), r z y → P z) → P y) : P x := begin let Q : s → Prop := λ y, P y, change Q ⟨x, hx⟩, refine well_founded.induction hs ⟨x, hx⟩ _, rintros ⟨y, ys⟩ ih, exact hP _ ys (λ z zs zy, ih ⟨z, zs⟩ zy), end instance is_strict_order.subset {s : set α} {r : α → α → Prop} [is_strict_order α r] : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ } theorem well_founded_on_iff_no_descending_seq {s : set α} {r : α → α → Prop} [is_strict_order α r] : s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬ (range f) ⊆ s := begin rw [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq], refine ⟨λ h f con, begin refine h.elim' ⟨⟨f, f.injective⟩, λ a b, _⟩, simp only [con (mem_range_self a), con (mem_range_self b), and_true, gt_iff_lt, function.embedding.coe_fn_mk, f.map_rel_iff] end, λ h, ⟨λ con, _⟩⟩, rcases con with ⟨f, hf⟩, have hfs' : ∀ n : ℕ, f n ∈ s := λ n, (hf.2 n.lt_succ_self).2.2, refine h ⟨f, λ a b, _⟩ (λ n hn, _), { rw ← hf, exact ⟨λ h, ⟨h, hfs' _, hfs' _⟩, λ h, h.1⟩ }, { rcases set.mem_range.1 hn with ⟨m, hm⟩, rw ← hm, apply hfs' } end section has_lt variables [has_lt α] /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] variables {s t : set α} theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := begin rw [is_wf, well_founded_on_iff] at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨xy.1, st xy.2.1, st xy.2.2⟩, end end has_lt section partial_order variables [partial_order α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ (f : (order_dual ℕ) ↪o α), ¬ (range f) ⊆ s := begin haveI : is_strict_order α (λ (a b : α), a < b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ x con, lt_irrefl x con.1⟩, to_is_trans := ⟨λ a b c ab bc, ⟨lt_trans ab.1 bc.1, ab.2.1, bc.2.2⟩⟩, }, rw [is_wf, well_founded_on_iff_no_descending_seq], exact ⟨λ h f, h f.lt_embedding, λ h f, h (order_embedding.of_strict_mono f (λ _ _, f.map_rel_iff.2))⟩, end theorem is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := begin classical, rw [is_wf_iff_no_descending_seq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { apply hs ((nat.order_embedding_of_set (f ⁻¹' s)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' s))) ⊆ s, rw [range_comp, image_subset_iff], simp }, { apply ht ((nat.order_embedding_of_set (f ⁻¹' t)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' t))) ⊆ t, rw [range_comp, image_subset_iff], simp } end end partial_order end set namespace set /-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. -/ def partially_well_ordered_on (s) (r : α → α → Prop) : Prop := ∀ (f : ℕ → α), range f ⊆ s → ∃ (m n : ℕ), m < n ∧ r (f m) (f n) /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_pwo [preorder α] (s) : Prop := partially_well_ordered_on s ((≤) : α → α → Prop) theorem partially_well_ordered_on.mono {s t : set α} {r : α → α → Prop} (ht : t.partially_well_ordered_on r) (hsub : s ⊆ t) : s.partially_well_ordered_on r := λ f hf, ht f (set.subset.trans hf hsub) theorem partially_well_ordered_on.image_of_monotone_on {s : set α} {r : α → α → Prop} {β : Type*} {r' : β → β → Prop} (hs : s.partially_well_ordered_on r) {f : α → β} (hf : ∀ a1 a2 : α, a1 ∈ s → a2 ∈ s → r a1 a2 → r' (f a1) (f a2)) : (f '' s).partially_well_ordered_on r' := λ g hg, begin have h := λ (n : ℕ), ((mem_image _ _ _).1 (hg (mem_range_self n))), obtain ⟨m, n, hlt, hmn⟩ := hs (λ n, classical.some (h n)) _, { refine ⟨m, n, hlt, _⟩, rw [← (classical.some_spec (h m)).2, ← (classical.some_spec (h n)).2], exact hf _ _ (classical.some_spec (h m)).1 (classical.some_spec (h n)).1 hmn }, { rintros _ ⟨n, rfl⟩, exact (classical.some_spec (h n)).1 } end section partial_order variables {s : set α} {t : set α} {r : α → α → Prop} theorem partially_well_ordered_on.exists_monotone_subseq [is_refl α r] [is_trans α r] (h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | heq := lt_or_eq_of_le hle, { exact h1 m n hlt, }, { rw [heq], apply refl_of r } }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (subset.trans (range_comp_subset_range _ _) hf), exact h2 m n hlt hle } end theorem partially_well_ordered_on_iff_exists_monotone_subseq [is_refl α r] [is_trans α r] : s.partially_well_ordered_on r ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, refine ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩, } end lemma partially_well_ordered_on.well_founded_on [is_partial_order α r] (h : s.partially_well_ordered_on r) : s.well_founded_on (λ a b, r a b ∧ a ≠ b) := begin haveI : is_strict_order α (λ a b, r a b ∧ a ≠ b) := { to_is_irrefl := ⟨λ a con, con.2 rfl⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans ab.1 bc.1, λ ac, ab.2 (antisymm ab.1 (ac.symm ▸ bc.1))⟩⟩ }, rw well_founded_on_iff_no_descending_seq, intros f con, obtain ⟨m, n, hlt, hle⟩ := h f con, exact (f.map_rel_iff.2 hlt).2 (antisymm hle (f.map_rel_iff.2 hlt).1).symm, end variables [partial_order α] lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf := begin rw [is_wf], convert h.well_founded_on, ext x y, rw lt_iff_le_and_ne, end theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := h.exists_monotone_subseq f hf theorem is_pwo_iff_exists_monotone_subseq : s.is_pwo ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := partially_well_ordered_on_iff_exists_monotone_subseq lemma is_pwo.prod (hs : s.is_pwo) (ht : t.is_pwo) : (s.prod t).is_pwo := begin classical, rw is_pwo_iff_exists_monotone_subseq at *, intros f hf, obtain ⟨g1, h1⟩ := hs (prod.fst ∘ f) _, swap, { rw [range_comp, image_subset_iff], refine subset.trans hf _, rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.1] }, obtain ⟨g2, h2⟩ := ht (prod.snd ∘ f ∘ g1) _, refine ⟨g2.trans g1, λ m n mn, _⟩, swap, { rw [range_comp, image_subset_iff], refine subset.trans (range_comp_subset_range _ _) (subset.trans hf _), rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.2] }, simp only [rel_embedding.coe_trans, function.comp_app], exact ⟨h1 (g2.le_iff_le.2 mn), h2 mn⟩, end theorem is_pwo.image_of_monotone {β : Type*} [partial_order β] (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) := hs.image_of_monotone_on (λ _ _ _ _ ab, hf ab) theorem is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := begin classical, rw [is_pwo_iff_exists_monotone_subseq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { obtain ⟨g, hg⟩ := hs (f ∘ (nat.order_embedding_of_set (f ⁻¹' s))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp }, { obtain ⟨g, hg⟩ := ht (f ∘ (nat.order_embedding_of_set (f ⁻¹' t))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp } end end partial_order theorem is_wf.is_pwo [linear_order α] {s : set α} (hs : s.is_wf) : s.is_pwo := λ f hf, begin rw [is_wf, well_founded_on_iff] at hs, have hrange : (range f).nonempty := ⟨f 0, mem_range_self 0⟩, let a := hs.min (range f) hrange, obtain ⟨m, hm⟩ := hs.min_mem (range f) hrange, refine ⟨m, m.succ, m.lt_succ_self, le_of_not_lt (λ con, _)⟩, rw hm at con, apply hs.not_lt_min (range f) hrange (mem_range_self m.succ) ⟨con, hf (mem_range_self m.succ), hf _⟩, rw ← hm, apply mem_range_self, end theorem is_wf_iff_is_pwo [linear_order α] {s : set α} : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩ end set namespace finset @[simp] theorem partially_well_ordered_on {r : α → α → Prop} [is_refl α r] (f : finset α) : set.partially_well_ordered_on (↑f : set α) r := begin intros g hg, by_cases hinj : function.injective g, { exact (set.infinite_of_injective_forall_mem hinj (set.range_subset_iff.1 hg) f.finite_to_set).elim }, { rw [function.injective] at hinj, push_neg at hinj, obtain ⟨m, n, gmgn, hne⟩ := hinj, cases lt_or_gt_of_ne hne with hlt hlt; { refine ⟨_, _, hlt, _⟩, rw gmgn, exact refl_of r _, } } end @[simp] theorem is_pwo [partial_order α] (f : finset α) : set.is_pwo (↑f : set α) := f.partially_well_ordered_on @[simp] theorem well_founded_on {r : α → α → Prop} [is_strict_order α r] (f : finset α) : set.well_founded_on (↑f : set α) r := begin rw [set.well_founded_on_iff_no_descending_seq], intros g con, apply set.infinite_of_injective_forall_mem g.injective (set.range_subset_iff.1 con), exact f.finite_to_set, end @[simp] theorem is_wf [partial_order α] (f : finset α) : set.is_wf (↑f : set α) := f.is_pwo.is_wf end finset namespace set variables [partial_order α] {s : set α} {a : α} theorem finite.is_pwo (h : s.finite) : s.is_pwo := begin rw ← h.coe_to_finset, exact h.to_finset.is_pwo, end @[simp] theorem fintype.is_pwo [fintype α] : s.is_pwo := (finite.of_fintype s).is_pwo @[simp] theorem is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo @[simp] theorem is_pwo_singleton (a) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo theorem is_pwo.insert (a) (hs : is_pwo s) : is_pwo (insert a s) := by { rw ← union_singleton, exact hs.union (is_pwo_singleton a) } /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end set @[simp] theorem finset.is_wf_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_wf) : (f.sup g).is_wf := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end @[simp] theorem finset.is_pwo_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_pwo) : (f.sup g).is_pwo := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end namespace set variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end set namespace set variables {s : set α} {t : set α} @[to_additive] theorem is_pwo.mul [ordered_cancel_comm_monoid α] (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s * t) := begin rw ← image_mul_prod, exact (is_pwo.prod hs ht).image_of_monotone (λ _ _ h, mul_le_mul' h.1 h.2), end variable [linear_ordered_cancel_comm_monoid α] @[to_additive] theorem is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) := (hs.is_pwo.mul ht.is_pwo).is_wf @[to_additive] theorem is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := begin refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _, rw is_wf.le_min_iff, rintros _ ⟨x, y, hx, hy, rfl⟩, exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy), end end set namespace set namespace partially_well_ordered_on /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop := set.range f ⊆ s ∧ ∀ (m n : ℕ), m < n → ¬ r (f m) (f n) lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) : s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f := begin rw [set.partially_well_ordered_on], apply forall_congr (λ f, _), simp [is_bad_seq] end /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) : { g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } := begin classical, have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g ∧ rk (g n) = k := ⟨_, f, λ _ _, rfl, hf, rfl⟩, obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h), refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩, refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩, rwa ← h3, end lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) : (∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩, let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f }, { refine nat.rec _ _, { exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1, (min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, }, { exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1, (min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } }, have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m, { intros m n mn, obtain ⟨k, rfl⟩ := exists_add_of_le mn, clear mn, induction k with k ih, { refl }, rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))], refl }, refine ⟨λ n, (fs n).1 n, ⟨set.range_subset_iff.2 (λ n, ((fs n).2).1.1 (mem_range_self n)), λ m n mn, _⟩, λ n g hg1 hg2, _⟩, { dsimp, rw [← subtype.val_eq_coe, h m n (le_of_lt mn)], convert (fs n).2.1.2 m n mn }, { convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 (le_refl _)), rw ← h m n (le_of_lt mn) }, end lemma iff_not_exists_is_min_bad_seq {r : α → α → Prop} (rk : α → ℕ) {s : set α} : s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr], split, { apply exists_min_bad_of_exists_bad }, rintro ⟨f, hf1, hf2⟩, exact ⟨f, hf1⟩, end /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r] {s : set α} (h : s.partially_well_ordered_on r) : { l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩, { apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}), { intros l hl, rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem], exact hl, }, apply_instance }, haveI : inhabited α := ⟨as⟩, rw [iff_not_exists_is_min_bad_seq (list.length)], rintro ⟨f, hf1, hf2⟩, have hnil : ∀ n, f n ≠ list.nil := λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil), obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _, swap, { simp only [set.range_subset_iff, function.comp_apply], exact λ n, hf1.1 (set.mem_range_self n) _ (list.head_mem_self (hnil n)) }, have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0)))) (λ m hm, (if_pos hm).symm) _, swap, { simp only [if_neg (lt_irrefl (g 0)), nat.sub_self], rw [list.length_tail, ← nat.pred_eq_sub_one], exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) }, rw [is_bad_seq] at hf', push_neg at hf', obtain ⟨m, n, mn, hmn⟩ := hf' _, swap, { rw set.range_subset_iff, rintro n x hx, split_ifs at hx with hn hn, { exact hf1.1 (set.mem_range_self _) _ hx }, { refine hf1.1 (set.mem_range_self _) _ (list.tail_subset _ hx), } }, by_cases hn : n < g 0, { apply hf1.2 m n mn, rwa [if_pos hn, if_pos (mn.trans hn)] at hmn }, { obtain ⟨n', rfl⟩ := le_iff_exists_add.1 (not_lt.1 hn), rw [if_neg hn, add_comm (g 0) n', nat.add_sub_cancel] at hmn, split_ifs at hmn with hm hm, { apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)), exact trans hmn (list.tail_sublist_forall₂_self _) }, { rw [← (sub_lt_iff_left (le_of_not_lt hm))] at mn, apply hf1.2 _ _ (g.lt_iff_lt.2 mn), rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))], exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } } end end partially_well_ordered_on namespace is_pwo @[to_additive] lemma submonoid_closure [ordered_cancel_comm_monoid α] {s : set α} (hpos : ∀ x : α, x ∈ s → 1 ≤ x) (h : s.is_pwo) : is_pwo ((submonoid.closure s) : set α) := begin have hl : ((submonoid.closure s) : set α) ⊆ list.prod '' { l : list α | ∀ x, x ∈ l → x ∈ s }, { intros x hx, rw set_like.mem_coe at hx, refine submonoid.closure_induction hx (λ x hx, ⟨_, λ y hy, _, list.prod_singleton⟩) ⟨_, λ y hy, (list.not_mem_nil _ hy).elim, list.prod_nil⟩ _, { rwa list.mem_singleton.1 hy }, rintros _ _ ⟨l, hl, rfl⟩ ⟨l', hl', rfl⟩, refine ⟨_, λ y hy, _, list.prod_append⟩, cases list.mem_append.1 hy with hy hy, { exact hl _ hy }, { exact hl' _ hy } }, apply ((h.partially_well_ordered_on_sublist_forall₂ (≤)).image_of_monotone_on _).mono hl, intros l1 l2 hl1 hl2 h12, obtain ⟨l, hll1, hll2⟩ := list.sublist_forall₂_iff.1 h12, refine le_trans (list.rel_prod (le_refl 1) (λ a b ab c d cd, mul_le_mul' ab cd) hll1) _, obtain ⟨l', hl'⟩ := hll2.exists_perm_append, rw [hl'.prod_eq, list.prod_append, ← mul_one l.prod, mul_assoc, one_mul], apply mul_le_mul_left', have hl's := λ x hx, hl2 x (list.subset.trans (l.subset_append_right _) hl'.symm.subset hx), clear hl', induction l' with x1 x2 x3 x4 x5, { refl }, rw [list.prod_cons, ← one_mul (1 : α)], exact mul_le_mul' (hpos x1 (hl's x1 (list.mem_cons_self x1 x2))) (x3 (λ x hx, hl's x (list.mem_cons_of_mem _ hx))) end end is_pwo /-- `set.mul_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`. -/ @[to_additive "`set.add_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`."] def mul_antidiagonal [monoid α] (s t : set α) (a : α) : set (α × α) := { x | x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t } namespace mul_antidiagonal @[simp, to_additive] lemma mem_mul_antidiagonal [monoid α] {s t : set α} {a : α} {x : α × α} : x ∈ mul_antidiagonal s t a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := iff.refl _ section cancel_comm_monoid variables [cancel_comm_monoid α] {s t : set α} {a : α} @[to_additive] lemma fst_eq_fst_iff_snd_eq_snd {x y : (mul_antidiagonal s t a)} : (x : α × α).fst = (y : α × α).fst ↔ (x : α × α).snd = (y : α × α).snd := ⟨λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_left_cancel (hx.trans y.2.1.symm), end, λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_right_cancel (hx.trans y.2.1.symm), end⟩ @[to_additive] lemma eq_of_fst_eq_fst {x y : (mul_antidiagonal s t a)} (h : (x : α × α).fst = (y : α × α).fst) : x = y := subtype.ext (prod.ext h (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.1 h)) @[to_additive] lemma eq_of_snd_eq_snd {x y : (mul_antidiagonal s t a)} (h : (x : α × α).snd = (y : α × α).snd) : x = y := subtype.ext (prod.ext (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.2 h) h) end cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] (s t : set α) (a : α) @[to_additive] lemma eq_of_fst_le_fst_of_snd_le_snd {x y : (mul_antidiagonal s t a)} (h1 : (x : α × α).fst ≤ (y : α × α).fst) (h2 : (x : α × α).snd ≤ (y : α × α).snd ) : x = y := begin apply eq_of_fst_eq_fst, cases eq_or_lt_of_le h1 with heq hlt, { exact heq }, exfalso, exact ne_of_lt (mul_lt_mul_of_lt_of_le hlt h2) ((mem_mul_antidiagonal.1 x.2).1.trans (mem_mul_antidiagonal.1 y.2).1.symm) end variables {s} {t} @[to_additive] theorem finite_of_is_pwo (hs : s.is_pwo) (ht : t.is_pwo) (a) : (mul_antidiagonal s t a).finite := begin by_contra h, rw [← set.infinite] at h, have h1 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.fst ⁻¹'o (≤)), { intros f hf, refine hs (prod.fst ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.1 }, have h2 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.snd ⁻¹'o (≤)), { intros f hf, refine ht (prod.snd ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.2 }, obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (λ x, h.nat_embedding _ x) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2 }, obtain ⟨m, n, mn, h2'⟩ := h2 (λ x, (h.nat_embedding _) (g x)) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2, }, apply ne_of_lt mn (g.injective ((h.nat_embedding _).injective _)), exact eq_of_fst_le_fst_of_snd_le_snd _ _ _ (hg _ _ (le_of_lt mn)) h2', end end ordered_cancel_comm_monoid @[to_additive] theorem finite_of_is_wf [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (a) : (mul_antidiagonal s t a).finite := finite_of_is_pwo hs.is_pwo ht.is_pwo a end mul_antidiagonal end set namespace finset variables [ordered_cancel_comm_monoid α] variables {s t : set α} (hs : s.is_pwo) (ht : t.is_pwo) (a : α) /-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered. -/ @[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered."] noncomputable def mul_antidiagonal : finset (α × α) := (set.mul_antidiagonal.finite_of_is_pwo hs ht a).to_finset variables {hs} {ht} {u : set α} {hu : u.is_pwo} {a} {x : α × α} @[simp, to_additive] lemma mem_mul_antidiagonal : x ∈ mul_antidiagonal hs ht a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := by simp [mul_antidiagonal] @[to_additive] lemma mul_antidiagonal_mono_left (hus : u ⊆ s) : (finset.mul_antidiagonal hu ht a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hus hx.2.1, hx.2.2⟩, end @[to_additive] lemma mul_antidiagonal_mono_right (hut : u ⊆ t) : (finset.mul_antidiagonal hs hu a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hx.2.1, hut hx.2.2⟩, end @[to_additive] lemma support_mul_antidiagonal_subset_mul : { a : α | (mul_antidiagonal hs ht a).nonempty } ⊆ s * t := (λ x ⟨⟨a1, a2⟩, ha⟩, begin obtain ⟨hmul, h1, h2⟩ := mem_mul_antidiagonal.1 ha, exact ⟨a1, a2, h1, h2, hmul⟩, end) @[to_additive] theorem is_pwo_support_mul_antidiagonal : { a : α | (mul_antidiagonal hs ht a).nonempty }.is_pwo := (hs.mul ht).mono support_mul_antidiagonal_subset_mul @[to_additive] theorem mul_antidiagonal_min_mul_min {α} [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (hns : s.nonempty) (hnt : t.nonempty) : mul_antidiagonal hs.is_pwo ht.is_pwo ((hs.min hns) * (ht.min hnt)) = {(hs.min hns, ht.min hnt)} := begin ext ⟨a1, a2⟩, rw [mem_mul_antidiagonal, finset.mem_singleton, prod.ext_iff], split, { rintro ⟨hast, has, hat⟩, cases eq_or_lt_of_le (hs.min_le hns has) with heq hlt, { refine ⟨heq.symm, _⟩, rw heq at hast, exact mul_left_cancel hast }, { contrapose hast, exact ne_of_gt (mul_lt_mul_of_lt_of_le hlt (ht.min_le hnt hat)) } }, { rintro ⟨ha1, ha2⟩, rw [ha1, ha2], exact ⟨rfl, hs.min_mem _, ht.min_mem _⟩ } end end finset lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono (set.subset_univ s)
f9ad8f1fb7809c48cd843822941a0b55671a2c1d
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/hott/logic.lean
5c47a79f49f713c40f92c7e64db8f489a2c10567
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
7,314
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura abbreviation id {A : Type} (a : A) := a abbreviation compose {A : Type} {B : Type} {C : Type} (g : B → C) (f : A → B) := λ x, g (f x) infixl `∘`:60 := compose inductive path {A : Type} (a : A) : A → Type := | refl : path a a infix `=`:50 := path definition transport {A : Type} {a b : A} {P : A → Type} (H1 : a = b) (H2 : P a) : P b := path_rec H2 H1 namespace logic notation p `*(`:75 u `)` := transport p u end using logic definition symm {A : Type} {a b : A} (p : a = b) : b = a := p*(refl a) definition trans {A : Type} {a b c : A} (p1 : a = b) (p2 : b = c) : a = c := p2*(p1) calc_subst transport calc_refl refl calc_trans trans namespace logic postfix `⁻¹`:100 := symm infixr `⬝`:75 := trans end using logic theorem trans_refl_right {A : Type} {x y : A} (p : x = y) : p = p ⬝ (refl y) := refl p theorem trans_refl_left {A : Type} {x y : A} (p : x = y) : p = (refl x) ⬝ p := path_rec (trans_refl_right (refl x)) p theorem refl_symm {A : Type} (x : A) : (refl x)⁻¹ = (refl x) := refl (refl x) theorem refl_trans {A : Type} (x : A) : (refl x) ⬝ (refl x) = (refl x) := refl (refl x) theorem trans_symm {A : Type} {x y : A} (p : x = y) : p ⬝ p⁻¹ = refl x := have q : (refl x) ⬝ (refl x)⁻¹ = refl x, from ((refl_symm x)⁻¹)*(refl_trans x), path_rec q p theorem symm_trans {A : Type} {x y : A} (p : x = y) : p⁻¹ ⬝ p = refl y := have q : (refl x)⁻¹ ⬝ (refl x) = refl x, from ((refl_symm x)⁻¹)*(refl_trans x), path_rec q p theorem symm_symm {A : Type} {x y : A} (p : x = y) : (p⁻¹)⁻¹ = p := have q : ((refl x)⁻¹)⁻¹ = refl x, from refl (refl x), path_rec q p theorem trans_assoc {A : Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := have e1 : (p ⬝ q) ⬝ (refl z) = p ⬝ q, from (trans_refl_right (p ⬝ q))⁻¹, have e2 : q ⬝ (refl z) = q, from (trans_refl_right q)⁻¹, have e3 : p ⬝ (q ⬝ (refl z)) = p ⬝ q, from e2*(refl (p ⬝ (q ⬝ (refl z)))), path_rec (e3 ⬝ e1⁻¹) r definition ap {A : Type} {B : Type} (f : A → B) {a b : A} (p : a = b) : f a = f b := p*(refl (f a)) theorem ap_refl {A : Type} {B : Type} (f : A → B) (a : A) : ap f (refl a) = refl (f a) := refl (refl (f a)) section parameters {A : Type} {B : Type} {C : Type} parameters (f : A → B) (g : B → C) parameters (x y z : A) (p : x = y) (q : y = z) theorem ap_trans_dist : ap f (p ⬝ q) = (ap f p) ⬝ (ap f q) := have e1 : ap f (p ⬝ refl y) = (ap f p) ⬝ (ap f (refl y)), from refl _, path_rec e1 q theorem ap_inv_dist : ap f (p⁻¹) = (ap f p)⁻¹ := have e1 : ap f ((refl x)⁻¹) = (ap f (refl x))⁻¹, from refl _, path_rec e1 p theorem ap_compose : ap g (ap f p) = ap (g∘f) p := have e1 : ap g (ap f (refl x)) = ap (g∘f) (refl x), from refl _, path_rec e1 p theorem ap_id : ap id p = p := have e1 : ap id (refl x) = (refl x), from refl (refl x), path_rec e1 p end section parameters {A : Type} {B : A → Type} (f : Π x, B x) definition D [private] (x y : A) (p : x = y) := p*(f x) = f y definition d [private] (x : A) : D x x (refl x) := refl (f x) theorem apd {a b : A} (p : a = b) : p*(f a) = f b := path_rec (d a) p end abbreviation homotopy {A : Type} {P : A → Type} (f g : Π x, P x) := Π x, f x = g x namespace logic infix `∼`:50 := homotopy end using logic notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r section parameters {A : Type} {B : Type} theorem hom_refl (f : A → B) : f ∼ f := take x, refl (f x) theorem hom_symm {f g : A → B} : f ∼ g → g ∼ f := assume h, take x, (h x)⁻¹ theorem hom_trans {f g h : A → B} : f ∼ g → g ∼ h → f ∼ h := assume h1 h2, take x, (h1 x) ⬝ (h2 x) theorem hom_fun {f g : A → B} {x y : A} (H : f ∼ g) (p : x = y) : (H x) ⬝ (ap g p) = (ap f p) ⬝ (H y) := have e1 : (H x) ⬝ (refl (g x)) = (refl (f x)) ⬝ (H x), from calc (H x) ⬝ (refl (g x)) = H x : (trans_refl_right (H x))⁻¹ ... = (refl (f x)) ⬝ (H x) : trans_refl_left (H x), have e2 : (H x) ⬝ (ap g (refl x)) = (ap f (refl x)) ⬝ (H x), from calc (H x) ⬝ (ap g (refl x)) = (H x) ⬝ (refl (g x)) : {ap_refl g x} ... = (refl (f x)) ⬝ (H x) : e1 ... = (ap f (refl x)) ⬝ (H x) : {symm (ap_refl f x)}, path_rec e2 p end definition loop_space (A : Type) (a : A) := a = a notation `Ω` `(` A `,` a `)` := loop_space A a definition loop2d_space (A : Type) (a : A) := (refl a) = (refl a) notation `Ω²` `(` A `,` a `)` := loop2d_space A a inductive empty : Type theorem empty_elim (c : Type) (H : empty) : c := empty_rec (λ e, c) H definition not (A : Type) := A → empty prefix `¬`:40 := not theorem not_intro {a : Type} (H : a → empty) : ¬ a := H theorem not_elim {a : Type} (H1 : ¬ a) (H2 : a) : empty := H1 H2 theorem absurd {a : Type} (H1 : a) (H2 : ¬ a) : empty := H2 H1 theorem mt {a b : Type} (H1 : a → b) (H2 : ¬ b) : ¬ a := assume Ha : a, absurd (H1 Ha) H2 theorem contrapos {a b : Type} (H : a → b) : ¬ b → ¬ a := assume Hnb : ¬ b, mt H Hnb theorem absurd_elim {a : Type} (b : Type) (H1 : a) (H2 : ¬ a) : b := empty_elim b (absurd H1 H2) inductive unit : Type := | star : unit notation `⋆`:max := star theorem absurd_not_unit (H : ¬ unit) : empty := absurd star H theorem not_empty_trivial : ¬ empty := assume H : empty, H theorem upun (x : unit) : x = ⋆ := unit_rec (refl ⋆) x inductive product (A : Type) (B : Type) : Type := | pair : A → B → product A B infixr `×`:30 := product infixr `∧`:30 := product notation `(` h `,` t:(foldl `,` (e r, pair r e) h) `)` := t definition pr1 {A : Type} {B : Type} (p : A × B) : A := product_rec (λ a b, a) p definition pr2 {A : Type} {B : Type} (p : A × B) : B := product_rec (λ a b, b) p theorem uppt {A : Type} {B : Type} (p : A × B) : (pr1 p, pr2 p) = p := product_rec (λ x y, refl (x, y)) p inductive sum (A : Type) (B : Type) : Type := | inl : A → sum A B | inr : B → sum A B namespace logic infixr `+`:25 := sum end using logic infixr `∨`:25 := sum theorem sum_elim {a : Type} {b : Type} {c : Type} (H1 : a + b) (H2 : a → c) (H3 : b → c) : c := sum_rec H2 H3 H1 theorem resolve_right {a : Type} {b : Type} (H1 : a + b) (H2 : ¬ a) : b := sum_elim H1 (assume Ha, absurd_elim b Ha H2) (assume Hb, Hb) theorem resolve_left {a : Type} {b : Type} (H1 : a + b) (H2 : ¬ b) : a := sum_elim H1 (assume Ha, Ha) (assume Hb, absurd_elim a Hb H2) theorem sum_flip {a : Type} {b : Type} (H : a + b) : b + a := sum_elim H (assume Ha, inr b Ha) (assume Hb, inl a Hb) inductive Sigma {A : Type} (B : A → Type) : Type := | sigma_intro : Π a, B a → Sigma B notation `Σ` binders `,` r:(scoped P, Sigma P) := r definition dpr1 {A : Type} {B : A → Type} (p : Σ x, B x) : A := Sigma_rec (λ a b, a) p definition dpr2 {A : Type} {B : A → Type} (p : Σ x, B x) : B (dpr1 p) := Sigma_rec (λ a b, b) p
9176db0972f39046e13cb814e981e4d0bba859c4
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0506.lean
1b521dbe3484a2b9d798f12b06e46493af4fa7cd
[]
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
179
lean
variable f : ℕ → ℕ variable h : ∀ x : ℕ, f x ≤ f (x + 1) example : f 0 ≥ f 1 → f 0 = f 1 := assume : f 0 ≥ f 1, show f 0 = f 1, from le_antisymm (h 0) this
fc7ea8683c62d303a384ad6cf5d705dee4c47460
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/analysis/complex/basic.lean
be6a21dbcd34ab1f8f13b7f9c48cf97817572fc2
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
8,485
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.complex.module import data.complex.is_R_or_C /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `continuous_linear_map.re` * `continuous_linear_map.im` * `continuous_linear_map.of_real` They are bundled versions of the real part, the imaginary part, and the embedding of `ℝ` in `ℂ`, as continuous `ℝ`-linear maps. We also register the fact that `ℂ` is an `is_R_or_C` field. -/ noncomputable theory namespace complex instance : has_norm ℂ := ⟨abs⟩ instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } instance normed_algebra_over_reals : normed_algebra ℝ ℂ := { norm_algebra_map_eq := abs_of_real, ..complex.algebra_over_reals } @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn /-- A complex normed vector space is also a real normed vector space. -/ @[priority 900] instance normed_space.restrict_scalars_real (E : Type*) [normed_group E] [normed_space ℂ E] : normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E open continuous_linear_map /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def continuous_linear_map.re : ℂ →L[ℝ] ℝ := linear_map.re.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_re_le_abs]) @[continuity] lemma continuous_re : continuous re := continuous_linear_map.re.continuous @[simp] lemma continuous_linear_map.re_coe : (coe (continuous_linear_map.re) : ℂ →ₗ[ℝ] ℝ) = linear_map.re := rfl @[simp] lemma continuous_linear_map.re_apply (z : ℂ) : (continuous_linear_map.re : ℂ → ℝ) z = z.re := rfl @[simp] lemma continuous_linear_map.re_norm : ∥continuous_linear_map.re∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥continuous_linear_map.re 1∥ : by simp ... ≤ ∥continuous_linear_map.re∥ : unit_le_op_norm _ _ (by simp) /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def continuous_linear_map.im : ℂ →L[ℝ] ℝ := linear_map.im.mk_continuous 1 (λ x, by simp [real.norm_eq_abs, abs_im_le_abs]) @[continuity] lemma continuous_im : continuous im := continuous_linear_map.im.continuous @[simp] lemma continuous_linear_map.im_coe : (coe (continuous_linear_map.im) : ℂ →ₗ[ℝ] ℝ) = linear_map.im := rfl @[simp] lemma continuous_linear_map.im_apply (z : ℂ) : (continuous_linear_map.im : ℂ → ℝ) z = z.im := rfl @[simp] lemma continuous_linear_map.im_norm : ∥continuous_linear_map.im∥ = 1 := le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _) $ calc 1 = ∥continuous_linear_map.im I∥ : by simp ... ≤ ∥continuous_linear_map.im∥ : unit_le_op_norm _ _ (by simp) /-- The complex-conjugation function from `ℂ` to itself is an isometric linear map. -/ def linear_isometry.conj : ℂ →ₗᵢ[ℝ] ℂ := ⟨linear_map.conj, λ x, by simp⟩ /-- Continuous linear map version of the conj function, from `ℂ` to `ℂ`. -/ def continuous_linear_map.conj : ℂ →L[ℝ] ℂ := linear_isometry.conj.to_continuous_linear_map lemma isometry_conj : isometry (conj : ℂ → ℂ) := linear_isometry.conj.isometry @[continuity] lemma continuous_conj : continuous conj := continuous_linear_map.conj.continuous @[simp] lemma continuous_linear_map.conj_coe : (coe (continuous_linear_map.conj) : ℂ →ₗ[ℝ] ℂ) = linear_map.conj := rfl @[simp] lemma continuous_linear_map.conj_apply (z : ℂ) : (continuous_linear_map.conj : ℂ → ℂ) z = z.conj := rfl @[simp] lemma continuous_linear_map.conj_norm : ∥continuous_linear_map.conj∥ = 1 := linear_isometry.conj.norm_to_continuous_linear_map /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def linear_isometry.of_real : ℝ →ₗᵢ[ℝ] ℂ := ⟨linear_map.of_real, λ x, by simp⟩ /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def continuous_linear_map.of_real : ℝ →L[ℝ] ℂ := linear_isometry.of_real.to_continuous_linear_map lemma isometry_of_real : isometry (coe : ℝ → ℂ) := linear_isometry.of_real.isometry @[continuity] lemma continuous_of_real : continuous (coe : ℝ → ℂ) := isometry_of_real.continuous @[simp] lemma continuous_linear_map.of_real_coe : (coe (continuous_linear_map.of_real) : ℝ →ₗ[ℝ] ℂ) = linear_map.of_real := rfl @[simp] lemma continuous_linear_map.of_real_apply (x : ℝ) : (continuous_linear_map.of_real : ℝ → ℂ) x = x := rfl @[simp] lemma continuous_linear_map.of_real_norm : ∥continuous_linear_map.of_real∥ = 1 := linear_isometry.of_real.norm_to_continuous_linear_map noncomputable instance : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } end complex namespace is_R_or_C local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `conjC` := @is_R_or_C.conj ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end is_R_or_C
0d28c44cd11da8e9242e5f18c6597341d3766f40
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/homotopy/homotopy_group.hlean
67326016787b5b66891edb05a57f605a05cd8ea1
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
11,657
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Clive Newstead -/ import .LES_of_homotopy_groups .sphere .complex_hopf open eq is_trunc trunc_index pointed algebra trunc nat is_conn fiber pointed unit namespace is_trunc -- Lemma 8.3.1 theorem trivial_homotopy_group_of_is_trunc (A : Type*) {n k : ℕ} [is_trunc n A] (H : n < k) : is_contr (π[k] A) := begin apply is_trunc_trunc_of_is_trunc, apply is_contr_loop_of_is_trunc, apply @is_trunc_of_le A n _, apply trunc_index.le_of_succ_le_succ, rewrite [succ_sub_two_succ k], exact of_nat_le_of_nat H, end theorem trivial_ghomotopy_group_of_is_trunc (A : Type*) (n k : ℕ) [is_trunc n A] (H : n ≤ k) : is_contr (πg[k+1] A) := trivial_homotopy_group_of_is_trunc A (lt_succ_of_le H) -- Lemma 8.3.2 theorem trivial_homotopy_group_of_is_conn (A : Type*) {k n : ℕ} (H : k ≤ n) [is_conn n A] : is_contr (π[k] A) := begin have H3 : is_contr (ptrunc k A), from is_conn_of_le A (of_nat_le_of_nat H), have H4 : is_contr (Ω[k](ptrunc k A)), from !is_trunc_loop_of_is_trunc, apply is_trunc_equiv_closed_rev, { apply equiv_of_pequiv (homotopy_group_pequiv_loop_ptrunc k A)} end -- Corollary 8.3.3 section open sphere sphere.ops sphere_index theorem homotopy_group_sphere_le (n k : ℕ) (H : k < n) : is_contr (π[k] (S* n)) := begin cases n with n, { exfalso, apply not_lt_zero, exact H}, { have H2 : k ≤ n, from le_of_lt_succ H, apply @(trivial_homotopy_group_of_is_conn _ H2) } end end theorem is_contr_HG_fiber_of_is_connected {A B : Type*} (k n : ℕ) (f : A →* B) [H : is_conn_fun n f] (H2 : k ≤ n) : is_contr (π[k] (pfiber f)) := @(trivial_homotopy_group_of_is_conn (pfiber f) H2) (H pt) theorem homotopy_group_trunc_of_le (A : Type*) (n k : ℕ) (H : k ≤ n) : π[k] (ptrunc n A) ≃* π[k] A := begin refine !homotopy_group_pequiv_loop_ptrunc ⬝e* _, refine loopn_pequiv_loopn _ (ptrunc_ptrunc_pequiv_left _ _) ⬝e* _, exact of_nat_le_of_nat H, exact !homotopy_group_pequiv_loop_ptrunc⁻¹ᵉ*, end /- Corollaries of the LES of homotopy groups -/ local attribute ab_group.to_group [coercion] local attribute is_equiv_tinverse [instance] open prod chain_complex group fin equiv function is_equiv lift /- Because of the construction of the LES this proof only gives us this result when A and B live in the same universe (because Lean doesn't have universe cumulativity). However, below we also proof that it holds for A and B in arbitrary universes. -/ theorem is_equiv_π_of_is_connected'.{u} {A B : pType.{u}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin cases k with k, { /- k = 0 -/ change (is_equiv (trunc_functor 0 f)), apply is_equiv_trunc_functor_of_is_conn_fun, refine is_conn_fun_of_le f (zero_le_of_nat n)}, { /- k > 0 -/ have H2' : k ≤ n, from le.trans !self_le_succ H2, exact @is_equiv_of_trivial _ (LES_of_homotopy_groups f) _ (is_exact_LES_of_homotopy_groups f (k, 2)) (is_exact_LES_of_homotopy_groups f (succ k, 0)) (@is_contr_HG_fiber_of_is_connected A B k n f H H2') (@is_contr_HG_fiber_of_is_connected A B (succ k) n f H H2) (@pgroup_of_group _ (group_LES_of_homotopy_groups f k 0) idp) (@pgroup_of_group _ (group_LES_of_homotopy_groups f k 1) idp) (homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun f (k, 0)))}, end theorem is_equiv_π_of_is_connected.{u v} {A : pType.{u}} {B : pType.{v}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin have π→[k] pdown.{v u} ∘* π→[k] (plift_functor f) ∘* π→[k] pup.{u v} ~* π→[k] f, begin refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply plift_functor_phomotopy end, have π→[k] pdown.{v u} ∘ π→[k] (plift_functor f) ∘ π→[k] pup.{u v} ~ π→[k] f, from this, apply is_equiv.homotopy_closed, rotate 1, { exact this}, { do 2 apply is_equiv_compose, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift}, { refine @(is_equiv_π_of_is_connected' _ H2) _, apply is_conn_fun_lift_functor}, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift⁻¹ᵉ}} end definition π_equiv_π_of_is_connected {A B : Type*} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : π[k] A ≃* π[k] B := pequiv_of_pmap (π→[k] f) (is_equiv_π_of_is_connected f H2) -- TODO: prove this for A and B in different universe levels theorem is_surjective_π_of_is_connected.{u} {A B : pType.{u}} (n : ℕ) (f : A →* B) [H : is_conn_fun n f] : is_surjective (π→[n + 1] f) := @is_surjective_of_trivial _ (LES_of_homotopy_groups f) _ (is_exact_LES_of_homotopy_groups f (n, 2)) (@is_contr_HG_fiber_of_is_connected A B n n f H !le.refl) /- Theorem 8.8.3: Whitehead's principle and its corollaries -/ definition whitehead_principle (n : ℕ₋₂) {A B : Type} [HA : is_trunc n A] [HB : is_trunc n B] (f : A → B) (H' : is_equiv (trunc_functor 0 f)) (H : Πa k, is_equiv (π→[k + 1] (pmap_of_map f a))) : is_equiv f := begin revert A B HA HB f H' H, induction n with n IH: intros, { apply is_equiv_of_is_contr}, have Πa, is_equiv (Ω→ (pmap_of_map f a)), begin intro a, apply IH, do 2 (esimp; exact _), { rexact H a 0}, intro p k, have is_equiv (π→[k + 1] (Ω→(pmap_of_map f a))), from is_equiv_homotopy_group_functor_ap1 (k+1) (pmap_of_map f a), have Π(b : A) (p : a = b), is_equiv (pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin intro b p, induction p, apply is_equiv.homotopy_closed, exact this, refine homotopy_group_functor_phomotopy _ _, apply ap1_pmap_of_map end, have is_equiv (homotopy_group_pequiv _ (pequiv_of_eq_pt (!idp_con⁻¹ : ap f p = Ω→ (pmap_of_map f a) p)) ∘ pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin apply is_equiv_compose, exact this a p, end, apply is_equiv.homotopy_closed, exact this, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, fapply phomotopy.mk, { esimp, intro q, refine !idp_con⁻¹}, { esimp, refine !idp_con⁻¹}, end, apply is_equiv_of_is_equiv_ap1_of_is_equiv_trunc end definition whitehead_principle_pointed (n : ℕ₋₂) {A B : Type*} [HA : is_trunc n A] [HB : is_trunc n B] [is_conn 0 A] (f : A →* B) (H : Πk, is_equiv (π→[k] f)) : is_equiv f := begin apply whitehead_principle n, rexact H 0, intro a k, revert a, apply is_conn.elim -1, have is_equiv (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* π→[k + 1] f ∘* π→[k + 1] (pointed_eta_pequiv A)⁻¹ᵉ*), begin apply is_equiv_compose (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*)), apply is_equiv_compose (π→[k + 1] f), all_goals apply is_equiv_homotopy_group_functor, end, refine @(is_equiv.homotopy_closed _) _ this _, apply to_homotopy, refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply phomotopy_pmap_of_map end open pointed.ops definition is_contr_of_trivial_homotopy (n : ℕ₋₂) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, is_contr (π[k] (pointed.MK A a))) : is_contr A := begin fapply is_trunc_is_equiv_closed_rev, { exact λa, ⋆}, apply whitehead_principle n, { apply is_equiv_trunc_functor_of_is_conn_fun, apply is_conn_fun_to_unit_of_is_conn}, intro a k, apply @is_equiv_of_is_contr, refine trivial_homotopy_group_of_is_trunc _ !zero_lt_succ, end definition is_contr_of_trivial_homotopy_nat (n : ℕ) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, k ≤ n → is_contr (π[k] (pointed.MK A a))) : is_contr A := begin apply is_contr_of_trivial_homotopy n, intro k a, apply @lt_ge_by_cases _ _ n k, { intro H', exact trivial_homotopy_group_of_is_trunc _ H'}, { intro H', exact H k a H'} end definition is_contr_of_trivial_homotopy_pointed (n : ℕ₋₂) (A : Type*) [is_trunc n A] (H : Πk, is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 qed, fapply is_contr_of_trivial_homotopy n A, intro k, apply is_conn.elim -1, cases A with A a, exact H k end definition is_contr_of_trivial_homotopy_nat_pointed (n : ℕ) (A : Type*) [is_trunc n A] (H : Πk, k ≤ n → is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 !zero_le qed, fapply is_contr_of_trivial_homotopy_nat n A, intro k a H', revert a, apply is_conn.elim -1, cases A with A a, exact H k H' end definition is_conn_fun_of_equiv_on_homotopy_groups.{u} (n : ℕ) {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, k ≤ n → is_equiv (homotopy_group_functor k (pmap_of_map f a))) (H2 : Πa, is_surjective (homotopy_group_functor (succ n) (pmap_of_map f a))) : is_conn_fun n f := have H2' : Πa k, k ≤ n → is_surjective (homotopy_group_functor (succ k) (pmap_of_map f a)), begin intro a k H, cases H with n' H', { apply H2}, { apply is_surjective_of_is_equiv, apply H1, exact succ_le_succ H'} end, have H3 : Πa, is_contr (ptrunc n (pfiber (pmap_of_map f a))), begin intro a, apply is_contr_of_trivial_homotopy_nat_pointed n, { intro k H, apply is_trunc_equiv_closed_rev, exact homotopy_group_ptrunc_of_le H _, rexact @is_contr_of_is_embedding_of_is_surjective +3ℕ (LES_of_homotopy_groups (pmap_of_map f a)) (k, 0) (is_exact_LES_of_homotopy_groups _ _) proof @(is_embedding_of_is_equiv _) (H1 a k H) qed proof (H2' a k H) qed} end, show Πb, is_contr (trunc n (fiber f b)), begin intro b, note p := right_inv (trunc_functor 0 f) (tr b), revert p, induction (trunc_functor 0 f)⁻¹ (tr b), esimp, intro p, induction !tr_eq_tr_equiv p with q, rewrite -q, exact H3 a end end is_trunc open is_trunc function /- applications to infty-connected types and maps -/ namespace is_conn definition is_conn_fun_inf_of_equiv_on_homotopy_groups.{u} {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, is_equiv (homotopy_group_functor k (pmap_of_map f a))) : is_conn_fun_inf f := begin apply is_conn_fun_inf.mk_nat, intro n, apply is_conn_fun_of_equiv_on_homotopy_groups, { intro a k H, exact H1 a k}, { intro a, apply is_surjective_of_is_equiv} end definition is_equiv_trunc_functor_of_is_conn_fun_inf.{u} (n : ℕ₋₂) {A B : Type.{u}} (f : A → B) [is_conn_fun_inf f] : is_equiv (trunc_functor n f) := _ definition is_equiv_homotopy_group_functor_of_is_conn_fun_inf.{u} {A B : pType.{u}} (f : A →* B) [is_conn_fun_inf f] (a : A) (k : ℕ) : is_equiv (homotopy_group_functor k f) := is_equiv_π_of_is_connected f (le.refl k) end is_conn
ca35ea672f127d935fe5be0d4ead4aefa7c2e778
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebraic_geometry/prime_spectrum.lean
e6223fb1da68219524f40bfdf417481b6eb741ba
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,181
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.opens import ring_theory.ideal.prod import linear_algebra.finsupp import algebra.punit_instances /-! # Prime spectrum of a commutative ring The prime spectrum of a commutative ring is the type of all prime ideals. It is naturally endowed with a topology: the Zariski topology. (It is also naturally endowed with a sheaf of rings, which is constructed in `algebraic_geometry.structure_sheaf`.) ## Main definitions * `prime_spectrum R`: The prime spectrum of a commutative ring `R`, i.e., the set of all prime ideals of `R`. * `zero_locus s`: The zero locus of a subset `s` of `R` is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`. * `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R` is the intersection of points in `t` (viewed as prime ideals). ## Conventions We denote subsets of rings with `s`, `s'`, etc... whereas we denote subsets of prime spectra with `t`, `t'`, etc... ## Inspiration/contributors The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme> which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau, and Chris Hughes (on an earlier repository). -/ noncomputable theory open_locale classical universe variables u v variables (R : Type u) [comm_ring R] /-- The prime spectrum of a commutative ring `R` is the type of all prime ideals of `R`. It is naturally endowed with a topology (the Zariski topology), and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`). It is a fundamental building block in algebraic geometry. -/ @[nolint has_inhabited_instance] def prime_spectrum := {I : ideal R // I.is_prime} variable {R} namespace prime_spectrum /-- A method to view a point in the prime spectrum of a commutative ring as an ideal of that ring. -/ abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val instance is_prime (x : prime_spectrum R) : x.as_ideal.is_prime := x.2 /-- The prime spectrum of the zero ring is empty. -/ lemma punit (x : prime_spectrum punit) : false := x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem section variables (R) (S : Type v) [comm_ring S] /-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of `R` and the prime spectrum of `S`. -/ noncomputable def prime_spectrum_prod : prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S := ideal.prime_ideals_equiv R S variables {R S} @[simp] lemma prime_spectrum_prod_symm_inl_as_ideal (x : prime_spectrum R) : ((prime_spectrum_prod R S).symm (sum.inl x)).as_ideal = ideal.prod x.as_ideal ⊤ := by { cases x, refl } @[simp] lemma prime_spectrum_prod_symm_inr_as_ideal (x : prime_spectrum S) : ((prime_spectrum_prod R S).symm (sum.inr x)).as_ideal = ideal.prod ⊤ x.as_ideal := by { cases x, refl } end @[ext] lemma ext {x y : prime_spectrum R} : x = y ↔ x.as_ideal = y.as_ideal := subtype.ext_iff_val /-- The zero locus of a set `s` of elements of a commutative ring `R` is the set of all prime ideals of the ring that contain the set `s`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set R) : set (prime_spectrum R) := {x | s ⊆ x.as_ideal} @[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) : x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set R) : zero_locus (ideal.span s : set R) = zero_locus s := by { ext x, exact (submodule.gi R R).gc s x.as_ideal } /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `R` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (prime_spectrum R)) : ideal R := ⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal lemma coe_vanishing_ideal (t : set (prime_spectrum R)) : (vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, submodule.mem_infi], apply forall_congr, intro x, rw [submodule.mem_infi], end lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) : f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : prime_spectrum R) : vanishing_ideal ({x} : set (prime_spectrum R)) = x.as_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) : t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ section gc variable (R) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc : @galois_connection (ideal R) (order_dual (set (prime_spectrum R))) _ _ (λ I, zero_locus I) (λ t, vanishing_ideal t) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set R) (order_dual (set (prime_spectrum R))) _ _ (λ s, zero_locus s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose _ _ _ _ ideal_gc (gc R) lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) : t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t := (gc_set R) s t end gc lemma subset_vanishing_ideal_zero_locus (s : set R) : s ⊆ vanishing_ideal (zero_locus s) := (gc_set R).le_u_l s lemma le_vanishing_ideal_zero_locus (I : ideal R) : I ≤ vanishing_ideal (zero_locus I) := (gc R).le_u_l I @[simp] lemma vanishing_ideal_zero_locus_eq_radical (I : ideal R) : vanishing_ideal (zero_locus (I : set R)) = I.radical := ideal.ext $ λ f, begin rw [mem_vanishing_ideal, ideal.radical_eq_Inf, submodule.mem_Inf], exact ⟨(λ h x hx, h ⟨x, hx.2⟩ hx.1), (λ h x hx, h x.1 ⟨hx, x.2⟩)⟩ end @[simp] lemma zero_locus_radical (I : ideal R) : zero_locus (I.radical : set R) = zero_locus I := vanishing_ideal_zero_locus_eq_radical I ▸ congr_fun (gc R).l_u_l_eq_l I lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) : t ⊆ zero_locus (vanishing_ideal t) := (gc R).l_u_le t lemma zero_locus_anti_mono {s t : set R} (h : s ⊆ t) : zero_locus t ⊆ zero_locus s := (gc_set R).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal R} (h : s ≤ t) : zero_locus (t : set R) ⊆ zero_locus (s : set R) := (gc R).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (prime_spectrum R)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc R).monotone_u h lemma zero_locus_subset_zero_locus_iff (I J : ideal R) : zero_locus (I : set R) ⊆ zero_locus (J : set R) ↔ J ≤ I.radical := ⟨λ h, ideal.radical_le_radical_iff.mp (vanishing_ideal_zero_locus_eq_radical I ▸ vanishing_ideal_zero_locus_eq_radical J ▸ vanishing_ideal_anti_mono h), λ h, zero_locus_radical I ▸ zero_locus_anti_mono_ideal h⟩ lemma zero_locus_subset_zero_locus_singleton_iff (f g : R) : zero_locus ({f} : set R) ⊆ zero_locus {g} ↔ g ∈ (ideal.span ({f} : set R)).radical := by rw [← zero_locus_span {f}, ← zero_locus_span {g}, zero_locus_subset_zero_locus_iff, ideal.span_le, set.singleton_subset_iff, set_like.mem_coe] lemma zero_locus_bot : zero_locus ((⊥ : ideal R) : set R) = set.univ := (gc R).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus ({0} : set R) = set.univ := zero_locus_bot @[simp] lemma zero_locus_empty : zero_locus (∅ : set R) = set.univ := (gc_set R).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ := by simpa using (gc R).u_top lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) : zero_locus s = ∅ := begin rw set.eq_empty_iff_forall_not_mem, intros x hx, rw mem_zero_locus at hx, have x_prime : x.as_ideal.is_prime := by apply_instance, have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h }, apply x_prime.ne_top eq_top, end @[simp] lemma zero_locus_singleton_one : zero_locus ({1} : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_singleton (1 : R)) lemma zero_locus_empty_iff_eq_top {I : ideal R} : zero_locus (I : set R) = ∅ ↔ I = ⊤ := begin split, { contrapose!, intro h, apply set.ne_empty_iff_nonempty.mpr, rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩, exact ⟨⟨M, hM.is_prime⟩, hIM⟩ }, { rintro rfl, apply zero_locus_empty_of_one_mem, trivial } end @[simp] lemma zero_locus_univ : zero_locus (set.univ : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_univ 1) lemma zero_locus_sup (I J : ideal R) : zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J := (gc R).l_sup lemma zero_locus_union (s s' : set R) : zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' := (gc_set R).l_sup lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := (gc R).u_inf lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) : zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) := (gc R).l_supr lemma zero_locus_Union {ι : Sort*} (s : ι → set R) : zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) := (gc_set R).l_supr lemma zero_locus_bUnion (s : set (set R)) : zero_locus (⋃ s' ∈ s, s' : set R) = ⋂ s' ∈ s, zero_locus s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := (gc R).u_infi lemma zero_locus_inf (I J : ideal R) : zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, by simpa using x.2.inf_le lemma union_zero_locus (s s' : set R) : zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) := by { rw zero_locus_inf, simp } lemma zero_locus_mul (I J : ideal R) : zero_locus ((I * J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, by simpa using x.2.mul_le lemma zero_locus_singleton_mul (f g : R) : zero_locus ({f * g} : set R) = zero_locus {f} ∪ zero_locus {g} := set.ext $ λ x, by simpa using x.2.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_pow (I : ideal R) {n : ℕ} (hn : 0 < n) : zero_locus ((I ^ n : ideal R) : set R) = zero_locus I := zero_locus_radical (I ^ n) ▸ (I.radical_pow n hn).symm ▸ zero_locus_radical I @[simp] lemma zero_locus_singleton_pow (f : R) (n : ℕ) (hn : 0 < n) : zero_locus ({f ^ n} : set R) = zero_locus {f} := set.ext $ λ x, by simpa using x.2.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [submodule.mem_sup, mem_vanishing_ideal], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, rw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : R} {I : prime_spectrum R} : I ∈ (zero_locus {f} : set (prime_spectrum R))ᶜ ↔ f ∉ I.as_ideal := by rw [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (prime_spectrum R) := topological_space.of_closed (set.range prime_spectrum.zero_locus) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set R := λ i, classical.some (h i.2), have hf : ∀ i : Zs, ↑i = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union _⟩ end (by { rintro _ _ ⟨s, rfl⟩ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ }) lemma is_open_iff (U : set (prime_spectrum R)) : is_open U ↔ ∃ s, Uᶜ = zero_locus s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ s, Z = zero_locus s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_zero_locus (s : set R) : is_closed (zero_locus s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) : zero_locus (vanishing_ideal t : set R) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal t } end lemma vanishing_ideal_closure (t : set (prime_spectrum R)) : vanishing_ideal (closure t) = vanishing_ideal t := zero_locus_vanishing_ideal_eq_closure t ▸ congr_fun (gc R).u_l_u_eq_u t section comap variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S'] /-- The function between prime spectra of commutative rings induced by a ring homomorphism. This function is continuous. -/ def comap (f : R →+* S) : prime_spectrum S → prime_spectrum R := λ y, ⟨ideal.comap f y.as_ideal, by exact ideal.is_prime.comap _⟩ variables (f : R →+* S) @[simp] lemma comap_as_ideal (y : prime_spectrum S) : (comap f y).as_ideal = ideal.comap f y.as_ideal := rfl @[simp] lemma comap_id : comap (ring_hom.id R) = id := funext $ λ _, subtype.ext $ ideal.ext $ λ _, iff.rfl @[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') : comap (g.comp f) = comap f ∘ comap g := funext $ λ _, subtype.ext $ ideal.ext $ λ _, iff.rfl @[simp] lemma preimage_comap_zero_locus (s : set R) : (comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) := begin ext x, simp only [mem_zero_locus, set.mem_preimage, comap_as_ideal, set.image_subset_iff], refl end lemma comap_continuous (f : R →+* S) : continuous (comap f) := begin rw continuous_iff_is_closed, simp only [is_closed_iff_zero_locus], rintro _ ⟨s, rfl⟩, exact ⟨_, preimage_comap_zero_locus f s⟩ end end comap section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : R) : topological_space.opens (prime_spectrum R) := { val := { x | r ∉ x.as_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : R) (x : prime_spectrum R) : x ∈ basic_open f ↔ f ∉ x.as_ideal := iff.rfl lemma is_open_basic_open {a : R} : is_open ((basic_open a) : set (prime_spectrum R)) := (basic_open a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : R) : (basic_open r : set (prime_spectrum R)) = (zero_locus {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open (1 : R) = ⊤ := topological_space.opens.ext $ by {simp, refl} @[simp] lemma basic_open_zero : basic_open (0 : R) = ⊥ := topological_space.opens.ext $ by {simp, refl} lemma basic_open_le_basic_open_iff (f g : R) : basic_open f ≤ basic_open g ↔ f ∈ (ideal.span ({g} : set R)).radical := by rw [topological_space.opens.le_def, basic_open_eq_zero_locus_compl, basic_open_eq_zero_locus_compl, set.le_eq_subset, set.compl_subset_compl, zero_locus_subset_zero_locus_singleton_iff] lemma basic_open_mul (f g : R) : basic_open (f * g) = basic_open f ⊓ basic_open g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : R) : basic_open (f * g) ≤ basic_open f := by { rw basic_open_mul f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : R) : basic_open (f * g) ≤ basic_open g := by { rw basic_open_mul f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : R) (n : ℕ) (hn : 0 < n) : basic_open (f ^ n) = basic_open f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow f n hn lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : R), (basic_open r : set (prime_spectrum R)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_eq, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono (set.singleton_subset_iff.mpr hfs) } end lemma is_compact_basic_open (f : R) : is_compact (basic_open f : set (prime_spectrum R)) := compact_of_finite_subfamily_closed $ λ ι Z hZc hZ, begin let I : ι → ideal R := λ i, vanishing_ideal (Z i), have hI : ∀ i, Z i = zero_locus (I i) := λ i, by simpa only [zero_locus_vanishing_ideal_eq_closure] using (hZc i).closure_eq.symm, rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq, set.diff_eq_empty, funext hI, ← zero_locus_supr] at hZ, obtain ⟨n, hn⟩ : f ∈ (⨆ (i : ι), I i).radical, { rw ← vanishing_ideal_zero_locus_eq_radical, apply vanishing_ideal_anti_mono hZ, exact (subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f)) }, rcases submodule.exists_finset_of_mem_supr I hn with ⟨s, hs⟩, use s, -- Using simp_rw here, because `hI` and `zero_locus_supr` need to be applied underneath binders simp_rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq, set.diff_eq_empty, hI, ← zero_locus_supr], rw ← zero_locus_radical, -- this one can't be in `simp_rw` because it would loop apply zero_locus_anti_mono, rw set.singleton_subset_iff, exact ⟨n, hs⟩ end end basic_open /-- The prime spectrum of a commutative ring is a compact topological space. -/ instance : compact_space (prime_spectrum R) := { compact_univ := by { convert is_compact_basic_open (1 : R), rw basic_open_one, refl } } section order /-! ## The specialization order We endow `prime_spectrum R` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. TODO: maybe define sober topological spaces, and generalise this instance to those -/ instance : partial_order (prime_spectrum R) := subtype.partial_order _ @[simp] lemma as_ideal_le_as_ideal (x y : prime_spectrum R) : x.as_ideal ≤ y.as_ideal ↔ x ≤ y := subtype.coe_le_coe @[simp] lemma as_ideal_lt_as_ideal (x y : prime_spectrum R) : x.as_ideal < y.as_ideal ↔ x < y := subtype.coe_lt_coe lemma le_iff_mem_closure (x y : prime_spectrum R) : x ≤ y ↔ y ∈ closure ({x} : set (prime_spectrum R)) := by rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton, set_like.coe_subset_coe] end order end prime_spectrum
6228eb006e93be53c75b3a206bcd612ec3e5d1b9
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/structure.lean
e674284fd2835a3b58fe1258fe5502841b61eaa5
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,193
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 let 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
5e2441454163f36b57ea17b437f106d70f95cf3f
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/backward_rule1.lean
e5e505dc96b6e2f3034df804324ceb8b1464c2e3
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
206
lean
constants (A B C : Prop) (H : A → B) (G : A → B → C) constants (T : Type) (f : T → A) attribute H [backward] attribute G [backward] attribute f [backward] print H print G print f print [backward]
1b585803c19f267ec1afec3617206b0c4eff41de
022547453607c6244552158ff25ab3bf17361760
/src/measure_theory/borel_space.lean
86c28580f104cab3d0d0f1739137ed740be2ee44
[ "Apache-2.0" ]
permissive
1293045656/mathlib
5f81741a7c1ff1873440ec680b3680bfb6b7b048
4709e61525a60189733e72a50e564c58d534bed8
refs/heads/master
1,687,010,200,553
1,626,245,646,000
1,626,245,646,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,100
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.ae_measurable_sequence import analysis.complex.basic import analysis.normed_space.finite_dimension import topology.G_delta import measure_theory.arithmetic import topology.semicontinuous import topology.instances.ereal /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.countable_encodable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s t hs ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end section preorder variables [preorder α] [order_closed_topology α] {a b : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b : α} @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra h, push_neg at h, exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1, mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const.smul continuous_id).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section homeomorph /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl @[measurability] lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable end homeomorph lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv'.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv' γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv'⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) : measurable (function.inv_fun g) := begin refine measurable_of_is_closed (λ s hs, _), by_cases h : classical.choice n ∈ s, { rw preimage_inv_fun_of_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set.union hg.closed_range.measurable_set.compl }, { rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set } end lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) : measurable (g ∘ f) ↔ measurable f := begin refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩, apply measurable_of_is_closed, intros s hs, convert hf (hg.is_closed_map s hs).measurable_set, rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj] end lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ} (g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin by_cases h : nonempty β, { resetI, refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩, convert hg.measurable_inv_fun.comp_ae_measurable hf, ext x, exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm }, { have H : ¬ nonempty δ, by { contrapose! h, exact nonempty.map f h }, simp [(measurable_of_not_nonempty H (g ∘ f)).ae_measurable, (measurable_of_not_nonempty H f).ae_measurable] } end lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α} {f : β → δ} (hg : closed_embedding g) : ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) := begin refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩, by_cases hα : nonempty α, swap, { simp [measure.eq_zero_of_not_nonempty hα μ] }, resetI, refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩, have : μ = measure.map (function.inv_fun g) (measure.map g μ), by rw [measure.map_map hg.measurable_inv_fun hg.measurable, (function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id], rw this at h, filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk, ae_map_mem_range g hg.closed_range.measurable_set μ], assume x hx₁ hx₂, convert hx₁, exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm, end section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot := by simpa [ne_bot_iff], by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot := by simpa [ne_bot_iff], by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [second_countable_topology α] [order_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := begin refine measure.ext_of_generate_from_of_cover_subset borel_eq_generate_from_Ioo_rat _ (subset.refl _) _ _ _ _, { simp only [is_pi_system, mem_Union, mem_singleton_iff], rintros _ _ ⟨a₁, b₁, h₁, rfl⟩ ⟨a₂, b₂, h₂, rfl⟩ ne, simp only [Ioo_inter_Ioo, sup_eq_max, inf_eq_min, ← rat.cast_max, ← rat.cast_min, nonempty_Ioo] at ne ⊢, refine ⟨_, _, _, rfl⟩, assumption_mod_cast }, { exact countable_Union (λ a, (countable_encodable _).bUnion $ λ _ _, countable_singleton _) }, { exact is_topological_basis_Ioo_rat.sUnion_eq }, { simp only [mem_Union, mem_singleton_iff], rintros _ ⟨a, b, h, rfl⟩, refine (measure_mono subset_closure).trans_lt _, rw [closure_Ioo], exacts [is_compact_Icc.finite_measure, rat.cast_lt.2 h] }, { simp only [mem_Union, mem_singleton_iff], rintros _ ⟨a, b, hab, rfl⟩, exact h a b } end lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, H⟩, rw [mem_singleton_iff.1 H], rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, g.measurable_set' (Iio q) := λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { simp, rintro r rfl, exact is_open_Iio.measurable_set } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := nnreal.continuous_of_real.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← ennreal.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_group variables [normed_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, nnnorm (f a)) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_group section limits variables [measurable_space β] [metric_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff], have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) := λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq, simp_rw [← this], show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))), exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs, end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) /-- A limit (over a general filter) of measurable functions valued in a metric space is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap, rw [tendsto_pi], rw [tendsto_pi] at lim, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← mem_iff_inf_dist_zero_of_closed h1s h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a metric space is measurable. -/ lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : ae_measurable g μ := begin let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)), let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto, let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some, refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩, refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _, refine tendsto_pi.mpr (λ x, _), simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, }, { exact tendsto_const_nhds, }, end lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) := begin let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l), have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0, from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f 0 x⟩ : nonempty β).some), have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { intros x hx_conv, simp only [f_lim, hx_conv, dif_pos], exact (hp_mem x hx_conv).some_spec, }, have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n), exact (hp_mem x h).some_spec, }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _), exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), }, have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] variables [opens_measurable_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nondiscrete_normed_field section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) end normed_space lemma is_compact.measure_lt_top_of_nhds_within [topological_space α] {s : set α} {μ : measure α} (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) : μ s < ∞ := is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht) (λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ lemma is_compact.measure_lt_top [topological_space α] {s : set α} {μ : measure α} [locally_finite_measure μ] (h : is_compact s) : μ s < ∞ := h.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _
3f4fa6d320ed7c73bf8f93564ecbf3d376167cfa
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/trace.lean
c164ee18444f2bb539764ef096ef9289e243d927
[ "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
11,305
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen, Antoine Labelle -/ import linear_algebra.matrix.to_lin import linear_algebra.matrix.trace import linear_algebra.contraction import linear_algebra.tensor_product_basis import linear_algebra.free_module.strong_rank_condition import linear_algebra.free_module.finite.rank import linear_algebra.projection /-! # Trace of a linear map This file defines the trace of a linear map. See also `linear_algebra/matrix/trace.lean` for the trace of a matrix. ## Tags linear_map, trace, diagonal -/ noncomputable theory universes u v w namespace linear_map open_locale big_operators open_locale matrix open finite_dimensional open_locale tensor_product section variables (R : Type u) [comm_semiring R] {M : Type v} [add_comm_monoid M] [module R M] variables {ι : Type w} [decidable_eq ι] [fintype ι] variables {κ : Type*} [decidable_eq κ] [fintype κ] variables (b : basis ι R M) (c : basis κ R M) /-- The trace of an endomorphism given a basis. -/ def trace_aux : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace_linear_map ι R R) ∘ₗ ↑(linear_map.to_matrix b b) -- Can't be `simp` because it would cause a loop. lemma trace_aux_def (b : basis ι R M) (f : M →ₗ[R] M) : trace_aux R b f = matrix.trace (linear_map.to_matrix b b f) := rfl theorem trace_aux_eq : trace_aux R b = trace_aux R c := linear_map.ext $ λ f, calc matrix.trace (linear_map.to_matrix b b f) = matrix.trace (linear_map.to_matrix b b ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace (linear_map.to_matrix c b linear_map.id ⬝ linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id) : by rw [linear_map.to_matrix_comp _ c, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id ⬝ linear_map.to_matrix c b linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace (linear_map.to_matrix c c ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ b, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical variables (R) (M) /-- Trace of an endomorphism independent of basis. -/ def trace : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ (s : finset M), nonempty (basis s R M) then trace_aux R H.some_spec.some else 0 variables (R) {M} /-- Auxiliary lemma for `trace_eq_matrix_trace`. -/ theorem trace_eq_matrix_trace_of_finset {s : finset M} (b : basis s R M) (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s R M), from ⟨s, ⟨b⟩⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_eq_matrix_trace (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := by rw [trace_eq_matrix_trace_of_finset R b.reindex_finset_range, ← trace_aux_def, ← trace_aux_def, trace_aux_eq R b] theorem trace_mul_comm (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ (s : finset M), nonempty (basis s R M) then let ⟨s, ⟨b⟩⟩ := H in by { simp_rw [trace_eq_matrix_trace R b, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] /-- The trace of an endomorphism is invariant under conjugation -/ @[simp] theorem trace_conj (g : M →ₗ[R] M) (f : (M →ₗ[R] M)ˣ) : trace R M (↑f * g * ↑f⁻¹) = trace R M g := by { rw trace_mul_comm, simp } end section variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] variables (N : Type*) [add_comm_group N] [module R N] variables {ι : Type*} /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis [finite ι] (b : basis ι R M) : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := begin classical, casesI nonempty_fintype ι, apply basis.ext (basis.tensor_product (basis.dual_basis b) b), rintros ⟨i, j⟩, simp only [function.comp_app, basis.tensor_product_apply, basis.coe_dual_basis, coe_comp], rw [trace_eq_matrix_trace R b, to_matrix_dual_tensor_hom], by_cases hij : i = j, { rw [hij], simp }, rw matrix.std_basis_matrix.trace_zero j i (1:R) hij, simp [finsupp.single_eq_pi_single, hij], end /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis' [fintype ι] [decidable_eq ι] (b : basis ι R M) : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv_of_basis b).symm.to_linear_map := by simp [linear_equiv.eq_comp_to_linear_map_symm, trace_eq_contract_of_basis b] variables (R M N) variables [module.free R M] [module.finite R M] [module.free R N] [module.finite R N] [nontrivial R] /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ @[simp] theorem trace_eq_contract : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := trace_eq_contract_of_basis (module.free.choose_basis R M) @[simp] theorem trace_eq_contract_apply (x : module.dual R M ⊗[R] M) : (linear_map.trace R M) ((dual_tensor_hom R M M) x) = contract_left R M x := by rw [←comp_apply, trace_eq_contract] open_locale classical /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ theorem trace_eq_contract' : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv R M M).symm.to_linear_map := trace_eq_contract_of_basis' (module.free.choose_basis R M) /-- The trace of the identity endomorphism is the dimension of the free module -/ @[simp] theorem trace_one : trace R M 1 = (finrank R M : R) := begin have b := module.free.choose_basis R M, rw [trace_eq_matrix_trace R b, to_matrix_one, finrank_eq_card_choose_basis_index], simp, end /-- The trace of the identity endomorphism is the dimension of the free module -/ @[simp] theorem trace_id : trace R M id = (finrank R M : R) := by rw [←one_eq_id, trace_one] @[simp] theorem trace_transpose : trace R (module.dual R M) ∘ₗ module.dual.transpose = trace R M := begin let e := dual_tensor_hom_equiv R M M, have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext f m, simp [e], end theorem trace_prod_map : trace R (M × N) ∘ₗ prod_map_linear R M N M N R = (coprod id id : R × R →ₗ[R] R) ∘ₗ prod_map (trace R M) (trace R N) := begin let e := ((dual_tensor_hom_equiv R M M).prod (dual_tensor_hom_equiv R N N)), have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext, { simp only [dual_tensor_hom_equiv, tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, coe_comp, linear_equiv.coe_to_linear_map, coe_inl, function.comp_app, linear_equiv.prod_apply, dual_tensor_hom_equiv_of_basis_apply, map_zero, prod_map_apply, coprod_apply, id_coe, id.def, add_zero, prod_map_linear_apply, dual_tensor_hom_prod_map_zero, trace_eq_contract_apply, contract_left_apply, fst_apply] }, { simp only [dual_tensor_hom_equiv, tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, coe_comp, linear_equiv.coe_to_linear_map, coe_inr, function.comp_app, linear_equiv.prod_apply, dual_tensor_hom_equiv_of_basis_apply, map_zero, prod_map_apply, coprod_apply, id_coe, id.def, zero_add, prod_map_linear_apply, zero_prod_map_dual_tensor_hom, trace_eq_contract_apply, contract_left_apply, snd_apply], }, end variables {R M N} theorem trace_prod_map' (f : M →ₗ[R] M) (g : N →ₗ[R] N) : trace R (M × N) (prod_map f g) = trace R M f + trace R N g := begin have h := ext_iff.1 (trace_prod_map R M N) (f, g), simp only [coe_comp, function.comp_app, prod_map_apply, coprod_apply, id_coe, id.def, prod_map_linear_apply] at h, exact h, end variables (R M N) open tensor_product function theorem trace_tensor_product : compr₂ (map_bilinear R M N M N) (trace R (M ⊗ N)) = compl₁₂ (lsmul R R : R →ₗ[R] R →ₗ[R] R) (trace R M) (trace R N) := begin apply (compl₁₂_inj (show surjective (dual_tensor_hom R M M), from (dual_tensor_hom_equiv R M M).surjective) (show surjective (dual_tensor_hom R N N), from (dual_tensor_hom_equiv R N N).surjective)).1, ext f m g n, simp only [algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, compl₁₂_apply, compr₂_apply, map_bilinear_apply, trace_eq_contract_apply, contract_left_apply, lsmul_apply, algebra.id.smul_eq_mul, map_dual_tensor_hom, dual_distrib_apply], end theorem trace_comp_comm : compr₂ (llcomp R M N M) (trace R M) = compr₂ (llcomp R N M N).flip (trace R N) := begin apply (compl₁₂_inj (show surjective (dual_tensor_hom R N M), from (dual_tensor_hom_equiv R N M).surjective) (show surjective (dual_tensor_hom R M N), from (dual_tensor_hom_equiv R M N).surjective)).1, ext g m f n, simp only [tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, linear_equiv.coe_to_linear_map, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, compl₁₂_apply, compr₂_apply, flip_apply, llcomp_apply', comp_dual_tensor_hom, map_smul, trace_eq_contract_apply, contract_left_apply, smul_eq_mul, mul_comm], end variables {R M N} @[simp] theorem trace_transpose' (f : M →ₗ[R] M) : trace R _ (module.dual.transpose f) = trace R M f := by { rw [←comp_apply, trace_transpose] } theorem trace_tensor_product' (f : M →ₗ[R] M) (g : N →ₗ[R] N) : trace R (M ⊗ N) (map f g) = trace R M f * trace R N g := begin have h := ext_iff.1 (ext_iff.1 (trace_tensor_product R M N) f) g, simp only [compr₂_apply, map_bilinear_apply, compl₁₂_apply, lsmul_apply, algebra.id.smul_eq_mul] at h, exact h, end theorem trace_comp_comm' (f : M →ₗ[R] N) (g : N →ₗ[R] M) : trace R M (g ∘ₗ f) = trace R N (f ∘ₗ g) := begin have h := ext_iff.1 (ext_iff.1 (trace_comp_comm R M N) g) f, simp only [llcomp_apply', compr₂_apply, flip_apply] at h, exact h, end @[simp] theorem trace_conj' (f : M →ₗ[R] M) (e : M ≃ₗ[R] N) : trace R N (e.conj f) = trace R M f := by rw [e.conj_apply, trace_comp_comm', ←comp_assoc, linear_equiv.comp_coe, linear_equiv.self_trans_symm, linear_equiv.refl_to_linear_map, id_comp] theorem is_proj.trace {p : submodule R M} {f : M →ₗ[R] M} (h : is_proj p f) [module.free R p] [module.finite R p] [module.free R f.ker] [module.finite R f.ker] : trace R M f = (finrank R p : R) := by rw [h.eq_conj_prod_map, trace_conj', trace_prod_map', trace_id, map_zero, add_zero] end end linear_map
138370ec191a79496581b5e11231b92847d3e96c
a6b711a4e8db20755026231f7ed529a9014b2b6d
/ZZ_IGNORE/RAW/02_dm_int/dm_int.lean
7b33b2d6eb1393a7302dccbea58288cce6a3525e
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
119
lean
import ..dm_nat.dm_nat inductive integer : Type | of_nat : natural → integer | neg_succ_of_nat : natural → integer
b814890d2f0a864cde31929819c2eddace66104e
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/list/perm.lean
fdc7b9051c17da0b1f7959f9a157b2642a72e64c
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
40,948
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura List permutations. -/ import data.list.basic data.list.set open list setoid nat binary variables {A B : Type} inductive perm : list A → list A → Prop := | nil : perm [] [] | skip : Π (x : A) {l₁ l₂ : list A}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : A) (l : list A), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list A}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ namespace perm infix ~ := perm theorem eq_nil_of_perm_nil {l₁ : list A} (p : [] ~ l₁) : l₁ = [] := have gen : ∀ (l₂ : list A) (p : l₂ ~ l₁), l₂ = [] → l₁ = [], from take l₂ p, perm.induction_on p (λ h, h) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), gen [] p rfl theorem not_perm_nil_cons (x : A) (l : list A) : ¬ [] ~ (x::l) := have gen : ∀ (l₁ l₂ : list A) (p : l₁ ~ l₂), l₁ = [] → l₂ = (x::l) → false, from take l₁ l₂ p, perm.induction_on p (by contradiction) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e₁ e₂, begin rewrite [e₂ at *, e₁ at *], have e₃ : l₂ = [], from eq_nil_of_perm_nil p₁, exact (r₂ e₃ rfl) end), assume p, gen [] (x::l) p rfl rfl protected theorem refl [refl] : ∀ (l : list A), l ~ l | [] := nil | (x::xs) := skip x (refl xs) protected theorem symm [symm] : ∀ {l₁ l₂ : list A}, l₁ ~ l₂ → l₂ ~ l₁ := take l₁ l₂ p, perm.induction_on p nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute perm.trans [trans] theorem eqv (A : Type) : equivalence (@perm A) := mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A) protected definition is_setoid [instance] (A : Type) : setoid (list A) := setoid.mk (@perm A) (perm.eqv A) theorem mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∈ l₁ → a ∈ l₂ := assume p, perm.induction_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite this; apply !mem_cons) (suppose a ∈ l₁, or.inr (r₁ this))) (λ x y l ainyxl, or.elim (eq_or_mem_of_mem_cons ainyxl) (suppose a = y, by rewrite this; exact (or.inr !mem_cons)) (suppose a ∈ x::l, or.elim (eq_or_mem_of_mem_cons this) (suppose a = x, or.inl this) (suppose a ∈ l, or.inr (or.inr this)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem not_mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∉ l₁ → a ∉ l₂ := assume p nainl₁ ainl₂, absurd (mem_perm (perm.symm p) ainl₂) nainl₁ theorem perm_app_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (l₁++t₁) ~ (l₂++t₁) := assume p, perm.induction_on p !perm.refl (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, !swap) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (l++t₁) ~ (l++t₂) := list.induction_on l (λ p, p) (λ x xs r p, skip x (r p)) theorem perm_app [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁++t₁) ~ (l₂++t₂) := assume p₁ p₂, trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) theorem perm_app_cons (a : A) {h₁ h₂ t₁ t₂ : list A} : h₁ ~ h₂ → t₁ ~ t₂ → (h₁ ++ (a::t₁)) ~ (h₂ ++ (a::t₂)) := assume p₁ p₂, perm_app p₁ (skip a p₂) theorem perm_cons_app (a : A) : ∀ (l : list A), (a::l) ~ (l ++ [a]) | [] := !perm.refl | (x::xs) := calc a::x::xs ~ x::a::xs : swap x a xs ... ~ x::(xs++[a]) : skip x (perm_cons_app xs) theorem perm_cons_app_simp [simp] (a : A) : ∀ (l : list A), (l ++ [a]) ~ (a::l) := take l, perm.symm !perm_cons_app theorem perm_app_comm [simp] {l₁ l₂ : list A} : (l₁++l₂) ~ (l₂++l₁) := list.induction_on l₁ (by rewrite [append_nil_right, append_nil_left]) (λ a t r, calc a::(t++l₂) ~ a::(l₂++t) : skip a r ... ~ l₂++t++[a] : perm_cons_app ... = l₂++(t++[a]) : append.assoc ... ~ l₂++(a::t) : perm_app_right l₂ (perm.symm (perm_cons_app a t))) theorem length_eq_length_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → length l₁ = length l₂ := assume p, perm.induction_on p rfl (λ x l₁ l₂ p r, by rewrite [*length_cons, r]) (λ x y l, by rewrite *length_cons) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_singleton_of_perm_inv (a : A) {l : list A} : [a] ~ l → l = [a] := have gen : ∀ l₂, perm l₂ l → l₂ = [a] → l = [a], from take l₂, assume p, perm.induction_on p (λ e, e) (λ x l₁ l₂ p r e, begin injection e with e₁ e₂, rewrite [e₁, e₂ at p], have h₁ : l₂ = [], from eq_nil_of_perm_nil p, substvars end) (λ x y l e, by injection e; contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), assume p, gen [a] p rfl theorem eq_singleton_of_perm (a b : A) : [a] ~ [b] → a = b := assume p, begin injection eq_singleton_of_perm_inv a p with e₁, rewrite e₁ end theorem perm_rev : ∀ (l : list A), l ~ (reverse l) | [] := nil | (x::xs) := calc x::xs ~ xs++[x] : perm_cons_app x xs ... ~ reverse xs ++ [x] : perm_app_left [x] (perm_rev xs) ... = reverse (x::xs) : by rewrite [reverse_cons, concat_eq_append] theorem perm_rev_simp [simp] : ∀ (l : list A), (reverse l) ~ l := take l, perm.symm (perm_rev l) theorem perm_middle (a : A) (l₁ l₂ : list A) : (a::l₁)++l₂ ~ l₁++(a::l₂) := calc (a::l₁) ++ l₂ = a::(l₁++l₂) : rfl ... ~ l₁++l₂++[a] : perm_cons_app ... = l₁++(l₂++[a]) : append.assoc ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) theorem perm_middle_simp [simp] (a : A) (l₁ l₂ : list A) : l₁++(a::l₂) ~ (a::l₁)++l₂ := perm.symm !perm_middle theorem perm_cons_app_cons {l l₁ l₂ : list A} (a : A) : l ~ l₁++l₂ → a::l ~ l₁++(a::l₂) := assume p, calc a::l ~ l++[a] : perm_cons_app ... ~ l₁++l₂++[a] : perm_app_left [a] p ... = l₁++(l₂++[a]) : append.assoc ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) open decidable theorem perm_erase [decidable_eq A] {a : A} : ∀ {l : list A}, a ∈ l → l ~ a::(erase a l) | [] h := absurd h !not_mem_nil | (x::t) h := by_cases (assume aeqx : a = x, by rewrite [aeqx, erase_cons_head]) (assume naeqx : a ≠ x, have aint : a ∈ t, from mem_of_ne_of_mem naeqx h, have aux : t ~ a :: erase a t, from perm_erase aint, calc x::t ~ x::a::(erase a t) : skip x aux ... ~ a::x::(erase a t) : swap ... = a::(erase a (x::t)) : by rewrite [!erase_cons_tail naeqx]) theorem erase_perm_erase_of_perm [congr] [decidable_eq A] (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → erase a l₁ ~ erase a l₂ := assume p, perm.induction_on p nil (λ x t₁ t₂ p r, by_cases (assume aeqx : a = x, by rewrite [aeqx, *erase_cons_head]; exact p) (assume naeqx : a ≠ x, by rewrite [*erase_cons_tail _ naeqx]; exact (skip x r))) (λ x y l, by_cases (assume aeqx : a = x, by_cases (assume aeqy : a = y, by rewrite [-aeqx, -aeqy]) (assume naeqy : a ≠ y, by rewrite [-aeqx, erase_cons_tail _ naeqy, *erase_cons_head])) (assume naeqx : a ≠ x, by_cases (assume aeqy : a = y, by rewrite [-aeqy, erase_cons_tail _ naeqx, *erase_cons_head]) (assume naeqy : a ≠ y, by rewrite[erase_cons_tail _ naeqx, *erase_cons_tail _ naeqy, erase_cons_tail _ naeqx]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_induction_on {P : list A → list A → Prop} {l₁ l₂ : list A} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l | [] := h₁ | (x::xs) := h₂ x xs xs !perm.refl (P_refl xs), perm.induction_on p h₁ h₂ (λ x y l, h₃ x y l l !perm.refl !P_refl) h₄ theorem xswap {l₁ l₂ : list A} (x y : A) : l₁ ~ l₂ → x::y::l₁ ~ y::x::l₂ := assume p, calc x::y::l₁ ~ y::x::l₁ : swap ... ~ y::x::l₂ : skip y (skip x p) theorem perm_map [congr] (f : A → B) {l₁ l₂ : list A} : l₁ ~ l₂ → map f l₁ ~ map f l₂ := assume p, perm_induction_on p nil (λ x l₁ l₂ p r, skip (f x) r) (λ x y l₁ l₂ p r, xswap (f y) (f x) r) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) lemma perm_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → l₁~a::l₂ := assume q, qeq.induction_on q (λ h, !perm.refl) (λ b t₁ t₂ q₁ r₁, calc b::t₂ ~ b::a::t₁ : skip b r₁ ... ~ a::b::t₁ : swap) /- permutation is decidable if A has decidable equality -/ section dec open decidable variable [Ha : decidable_eq A] include Ha definition decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list A), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) | 0 l₁ l₂ H₁ H₂ := assert l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, assert l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, by rewrite [l₁n, l₂n]; exact (inl perm.nil) | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, let t₂ : list A := erase x l₂ in have len_t₁ : length t₁ = n, begin injection H₁ with e, exact e end, assert length t₂ = pred (length l₂), from length_erase_of_mem xinl₂, assert length t₂ = n, by rewrite [this, H₂], match decidable_perm_aux n t₁ t₂ len_t₁ this with | inl p := inl (calc x::t₁ ~ x::(erase x l₂) : skip x p ... ~ l₂ : perm_erase xinl₂) | inr np := inr (λ p : x::t₁ ~ l₂, assert erase x (x::t₁) ~ erase x l₂, from erase_perm_erase_of_perm x p, have t₁ ~ erase x l₂, by rewrite [erase_cons_head at this]; exact this, absurd this np) end) (assume nxinl₂ : x ∉ l₂, inr (λ p : x::t₁ ~ l₂, absurd (mem_perm p !mem_cons) nxinl₂)) definition decidable_perm [instance] : ∀ (l₁ l₂ : list A), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, inr (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr {P : Prop} {a b : A} {l₁ l₂ l₃ : list A} : a::l₁ = l₂++(b::l₃) → (l₂ = [] → a = b → l₁ = l₃ → P) → (∀ t, l₂ = a::t → l₁ = t++(b::l₃) → P) → P := match l₂ with | [] := λ e h₁ h₂, by injection e with e₁ e₂; exact h₁ rfl e₁ e₂ | h::t := λ e h₁ h₂, begin injection e with e₁ e₂, rewrite e₁ at h₂, exact h₂ t rfl e₂ end end -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr₂ {P : Prop} {a b c : A} {l₁ l₂ l₃ : list A} : a::b::l₁ = l₂++(c::l₃) → (l₂ = [] → l₃ = b::l₁ → a = c → P) → (l₂ = [a] → b = c → l₁ = l₃ → P) → (∀ t, l₂ = a::b::t → l₁ = t++(c::l₃) → P) → P := match l₂ with | [] := λ e H₁ H₂ H₃, begin injection e with a_eq_c b_l₁_eq_l₃, exact H₁ rfl (eq.symm b_l₁_eq_l₃) a_eq_c end | [h₁] := λ e H₁ H₂ H₃, begin rewrite [append_cons at e, append_nil_left at e], injection e with a_eq_h₁ b_eq_c l₁_eq_l₃, rewrite [a_eq_h₁ at H₂, b_eq_c at H₂, l₁_eq_l₃ at H₂], exact H₂ rfl rfl rfl end | h₁::h₂::t₂ := λ e H₁ H₂ H₃, begin injection e with a_eq_h₁ b_eq_h₂ l₁_eq, rewrite [a_eq_h₁ at H₃, b_eq_h₂ at H₃], exact H₃ t₂ rfl l₁_eq end end /- permutation inversion -/ theorem perm_inv_core {l₁ l₂ : list A} (p' : l₁ ~ l₂) : ∀ {a s₁ s₂}, l₁≈a|s₁ → l₂≈a|s₂ → s₁ ~ s₂ := perm_induction_on p' (λ a s₁ s₂ e₁ e₂, have innil : a ∈ [], from mem_head_of_qeq e₁, absurd innil !not_mem_nil) (λ x t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr C₁₂ (λ (s₁₁_eq : s₁₁ = []) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), assert s₁_p : s₁ ~ t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = t₁ : by rewrite [-t₁_eq, s₁₁_eq, append_nil_left] ... ~ t₂ : p, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ ~ t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [-t₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ t₂ : s₁_p ... = ts₂₁++(a::s₂₂) : t₂_eq ... ~ (a::ts₂₁)++s₂₂ : !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [-x_eq_a, -s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), assert t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, assert s₁_eq : s₁ = x::(ts₁₁++s₁₂), from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::(ts₁₁++ s₁₂) : by rewrite s₁₁_eq, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ = a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ ts₁₁++(a::s₁₂) : !perm_middle ... = t₁ : t₁_eq ... ~ t₂ : p ... = s₂ : by rewrite [t₂_eq, C₂₁, s₂₁_eq, append_nil_left] qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), assert t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, proof calc s₁ = x::(ts₁₁++s₁₂) : s₁_eq ... ~ x::(ts₂₁++s₂₂) : skip x (r t₁_qeq t₂_qeq) ... = s₂ : by rewrite [-append_cons, -s₂₁_eq, C₂₁] qed))) (λ x y t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : y::x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::y::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr₂ C₁₂ (λ (s₁₁_eq : s₁₁ = []) (s₁₂_eq : s₁₂ = x::t₁) (y_eq_a : y = a), assert s₁_p : s₁ ~ x::t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::t₁ : by rewrite [s₁₂_eq, s₁₁_eq, append_nil_left] ... ~ x::t₂ : skip x p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [x_eq_a, -y_eq_a, -s₂₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ x::t₂ : s₁_p ... = x::(ts₂₁++(y::s₂₂)) : by rewrite [t₂_eq, -y_eq_a] ... ~ x::y::(ts₂₁++s₂₂) : skip x !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed)) (λ (s₁₁_eq : s₁₁ = [y]) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), assert s₁_p : s₁ ~ y::t₂, from calc s₁ = y::t₁ : by rewrite [C₁₁, s₁₁_eq, t₁_eq] ... ~ y::t₂ : skip y p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, t₂_eq, y_eq_a, -x_eq_a] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ y::t₂ : s₁_p ... = y::(ts₂₁++(x::s₂₂)) : by rewrite [t₂_eq, -x_eq_a] ... ~ y::x::(ts₂₁++s₂₂) : skip y !perm_middle ... ~ x::y::(ts₂₁++s₂₂) : swap ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = y::x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), assert s₁_eq : s₁ = y::x::(ts₁₁++s₁₂), by rewrite [C₁₁, s₁₁_eq], discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ = y::a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ y::(ts₁₁++(a::s₁₂)) : skip y !perm_middle ... = y::t₁ : by rewrite t₁_eq ... ~ y::t₂ : skip y p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ x::y::(ts₁₁++s₁₂) : swap ... = x::a::(ts₁₁++s₁₂) : by rewrite y_eq_a ... ~ x::(ts₁₁++(a::s₁₂)) : skip x !perm_middle ... = x::t₁ : by rewrite t₁_eq ... ~ x::t₂ : skip x p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), assert t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, assert t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, assert p_aux : ts₁₁++s₁₂ ~ ts₂₁++s₂₂, from r t₁_qeq t₂_qeq, proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ y::x::(ts₂₁++s₂₂) : skip y (skip x p_aux) ... ~ x::y::(ts₂₁++s₂₂) : swap ... = s₂₁ ++ s₂₂ : by rewrite s₂₁_eq ... = s₂ : by rewrite C₂₁ qed))) (λ t₁ t₂ t₃ p₁ p₂ (r₁ : ∀{a s₁ s₂}, t₁ ≈ a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) (r₂ : ∀{a s₁ s₂}, t₂ ≈ a|s₁ → t₃≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, have a ∈ t₁, from mem_head_of_qeq e₁, have a ∈ t₂, from mem_perm p₁ this, obtain (t₂' : list A) (e₂' : t₂≈a|t₂'), from qeq_of_mem this, calc s₁ ~ t₂' : r₁ e₁ e₂' ... ~ s₂ : r₂ e₂' e₂) theorem perm_cons_inv {a : A} {l₁ l₂ : list A} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := assume p, perm_inv_core p (qeq.qhead a l₁) (qeq.qhead a l₂) theorem perm_app_inv {a : A} {l₁ l₂ l₃ l₄ : list A} : l₁++(a::l₂) ~ l₃++(a::l₄) → l₁++l₂ ~ l₃++l₄ := assume p : l₁++(a::l₂) ~ l₃++(a::l₄), have p' : a::(l₁++l₂) ~ a::(l₃++l₄), from calc a::(l₁++l₂) ~ l₁++(a::l₂) : perm_middle ... ~ l₃++(a::l₄) : p ... ~ a::(l₃++l₄) : perm.symm (!perm_middle), perm_cons_inv p' section foldl variables {f : B → A → B} {l₁ l₂ : list A} variable rcomm : right_commutative f include rcomm theorem foldl_eq_of_perm : l₁ ~ l₂ → ∀ b, foldl f b l₁ = foldl f b l₂ := assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldl f b (x::t₁) = foldl f (f b x) t₁ : foldl_cons ... = foldl f (f b x) t₂ : r (f b x) ... = foldl f b (x::t₂) : foldl_cons) (λ x y t₁ t₂ p r b, calc foldl f b (y :: x :: t₁) = foldl f (f (f b y) x) t₁ : by rewrite foldl_cons ... = foldl f (f (f b x) y) t₁ : by rewrite rcomm ... = foldl f (f (f b x) y) t₂ : r (f (f b x) y) ... = foldl f b (x :: y :: t₂) : by rewrite foldl_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) end foldl section foldr variables {f : A → B → B} {l₁ l₂ : list A} variable lcomm : left_commutative f include lcomm theorem foldr_eq_of_perm : l₁ ~ l₂ → ∀ b, foldr f b l₁ = foldr f b l₂ := assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldr f b (x::t₁) = f x (foldr f b t₁) : foldr_cons ... = f x (foldr f b t₂) : by rewrite [r b] ... = foldr f b (x::t₂) : foldr_cons) (λ x y t₁ t₂ p r b, calc foldr f b (y :: x :: t₁) = f y (f x (foldr f b t₁)) : by rewrite foldr_cons ... = f x (f y (foldr f b t₁)) : by rewrite lcomm ... = f x (f y (foldr f b t₂)) : by rewrite [r b] ... = foldr f b (x :: y :: t₂) : by rewrite foldr_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) end foldr theorem perm_erase_dup_of_perm [congr] [H : decidable_eq A] {l₁ l₂ : list A} : l₁ ~ l₂ → erase_dup l₁ ~ erase_dup l₂ := assume p, perm_induction_on p nil (λ x t₁ t₂ p r, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), by rewrite [erase_dup_cons_of_mem xint₁, erase_dup_cons_of_mem xint₂]; exact r) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by rewrite [erase_dup_cons_of_not_mem nxint₂, erase_dup_cons_of_not_mem nxint₁]; exact (skip x r))) (λ y x t₁ t₂ p r, by_cases (λ xinyt₁ : x ∈ y::t₁, by_cases (λ yint₁ : y ∈ t₁, assert yint₂ : y ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁)), assert yinxt₂ : y ∈ x::t₂, from or.inr (yint₂), or.elim (eq_or_mem_of_mem_cons xinyt₁) (λ xeqy : x = y, assert xint₂ : x ∈ t₂, by rewrite [-xeqy at yint₂]; exact yint₂, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end)) (λ nyint₁ : y ∉ t₁, assert nyint₂ : y ∉ t₂, from assume yint₂ : y ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup yint₂))) nyint₁, by_cases (λ xeqy : x = y, assert nxint₂ : x ∉ t₂, by rewrite [-xeqy at nyint₂]; exact nyint₂, assert yinxt₂ : y ∈ x::t₂, by rewrite [xeqy]; exact !mem_cons, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂, xeqy], exact skip y r end) (λ xney : x ≠ y, have x ∈ t₁, from or_resolve_right xinyt₁ xney, assert x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup this)), assert y ∉ x::t₂, from suppose y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons this) (λ h, absurd h (ne.symm xney)) (λ h, absurd h nyint₂), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_not_mem `y ∉ x::t₂`, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_mem `x ∈ t₂`], exact skip y r end))) (λ nxinyt₁ : x ∉ y::t₁, have xney : x ≠ y, from ne_of_not_mem_cons nxinyt₁, have nxint₁ : x ∉ t₁, from not_mem_of_not_mem_cons nxinyt₁, assert nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by_cases (λ yint₁ : y ∈ t₁, assert yinxt₂ : y ∈ x::t₂, from or.inr (mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁))), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_not_mem nxint₂], exact skip x r end) (λ nyint₁ : y ∉ t₁, assert nyinxt₂ : y ∉ x::t₂, from assume yinxt₂ : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons yinxt₂) (λ h, absurd h (ne.symm xney)) (λ h, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup h))) nyint₁), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_not_mem nyinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂], exact xswap x y r end))) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section perm_union variable [H : decidable_eq A] include H theorem perm_union_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (union l₁ t₁) ~ (union l₂ t₁) := assume p, perm.induction_on p (by rewrite [nil_union]) (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint₁]; exact r₁) (λ nxint₁ : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint₁]; exact (skip _ r₁))) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_mem _ yint, *union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_mem _ yint, *union_cons_of_not_mem _ nxint, union_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_not_mem _ nyint, union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint, *union_cons_of_not_mem _ nyint, union_cons_of_not_mem _ nxint]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_union_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (union l t₁) ~ (union l t₂) := list.induction_on l (λ p, by rewrite [*union_nil]; exact p) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [union_cons_of_mem _ xint₁, union_cons_of_mem _ xint₂]; exact (r p)) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [union_cons_of_not_mem _ nxint₁, union_cons_of_not_mem _ nxint₂]; exact (skip _ (r p)))) theorem perm_union [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (union l₁ t₁) ~ (union l₂ t₂) := assume p₁ p₂, trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) end perm_union section perm_insert variable [H : decidable_eq A] include H theorem perm_insert [congr] (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → (insert a l₁) ~ (insert a l₂) := assume p, by_cases (λ ainl₁ : a ∈ l₁, assert ainl₂ : a ∈ l₂, from mem_perm p ainl₁, by rewrite [insert_eq_of_mem ainl₁, insert_eq_of_mem ainl₂]; exact p) (λ nainl₁ : a ∉ l₁, assert nainl₂ : a ∉ l₂, from not_mem_perm p nainl₁, by rewrite [insert_eq_of_not_mem nainl₁, insert_eq_of_not_mem nainl₂]; exact (skip _ p)) end perm_insert section perm_inter variable [H : decidable_eq A] include H theorem perm_inter_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (inter l₁ t₁) ~ (inter l₂ t₁) := assume p, perm.induction_on p !perm.refl (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint₁]; exact (skip x r₁)) (λ nxint₁ : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint₁]; exact r₁)) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_mem _ yint, *inter_cons_of_mem _ xint]; exact !swap) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_mem _ yint, *inter_cons_of_not_mem _ nxint, inter_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_not_mem _ nyint, inter_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint, *inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nxint]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_inter_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (inter l t₁) ~ (inter l t₂) := list.induction_on l (λ p, by rewrite [*inter_nil]) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, assert xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₂]; exact (skip _ (r p))) (λ nxint₁ : x ∉ t₁, assert nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₂]; exact (r p))) theorem perm_inter [congr] {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (inter l₁ t₁) ~ (inter l₂ t₂) := assume p₁ p₂, trans (perm_inter_left t₁ p₁) (perm_inter_right l₂ p₂) end perm_inter /- extensionality -/ section ext open eq.ops theorem perm_ext : ∀ {l₁ l₂ : list A}, nodup l₁ → nodup l₂ → (∀a, a ∈ l₁ ↔ a ∈ l₂) → l₁ ~ l₂ | [] [] d₁ d₂ e := !perm.nil | [] (a₂::t₂) d₁ d₂ e := absurd (iff.mpr (e a₂) !mem_cons) (not_mem_nil a₂) | (a₁::t₁) [] d₁ d₂ e := absurd (iff.mp (e a₁) !mem_cons) (not_mem_nil a₁) | (a₁::t₁) (a₂::t₂) d₁ d₂ e := have a₁ ∈ a₂::t₂, from iff.mp (e a₁) !mem_cons, have ∃ s₁ s₂, a₂::t₂ = s₁++(a₁::s₂), from mem_split this, obtain (s₁ s₂ : list A) (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)), from this, have dt₂' : nodup (a₁::(s₁++s₂)), from nodup_head (by rewrite [t₂_eq at d₂]; exact d₂), have eqv : ∀a, a ∈ t₁ ↔ a ∈ s₁++s₂, from take a, iff.intro (suppose a ∈ t₁, assert a ∈ a₂::t₂, from iff.mp (e a) (mem_cons_of_mem _ this), have a ∈ s₁++(a₁::s₂), by rewrite [t₂_eq at this]; exact this, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, mem_append_left s₂ this) (suppose a ∈ a₁::s₂, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, assert a₁ ∉ t₁, from not_mem_of_nodup_cons d₁, by subst a; contradiction) (suppose a ∈ s₂, mem_append_right s₁ this))) (suppose a ∈ s₁ ++ s₂, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_left _ this), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', assert a₁ ∉ s₁, from not_mem_of_not_mem_append_left this, by subst a; contradiction) (suppose a ∈ t₁, this)) (suppose a ∈ s₂, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_right _ (mem_cons_of_mem _ this)), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', assert a₁ ∉ s₂, from not_mem_of_not_mem_append_right this, by subst a; contradiction) (suppose a ∈ t₁, this))), have ds₁s₂ : nodup (s₁++s₂), from nodup_of_nodup_cons dt₂', have nodup t₁, from nodup_of_nodup_cons d₁, calc a₁::t₁ ~ a₁::(s₁++s₂) : skip a₁ (perm_ext this ds₁s₂ eqv) ... ~ s₁++(a₁::s₂) : !perm_middle ... = a₂::t₂ : by rewrite t₂_eq end ext theorem nodup_of_perm_of_nodup {l₁ l₂ : list A} : l₁ ~ l₂ → nodup l₁ → nodup l₂ := assume h, perm.induction_on h (λ h, h) (λ a l₁ l₂ p ih nd, have nodup l₁, from nodup_of_nodup_cons nd, have nodup l₂, from ih this, have a ∉ l₁, from not_mem_of_nodup_cons nd, have a ∉ l₂, from suppose a ∈ l₂, absurd (mem_perm (perm.symm p) this) `a ∉ l₁`, nodup_cons `a ∉ l₂` `nodup l₂`) (λ x y l₁ nd, have nodup (x::l₁), from nodup_of_nodup_cons nd, have nodup l₁, from nodup_of_nodup_cons this, have x ∉ l₁, from not_mem_of_nodup_cons `nodup (x::l₁)`, have y ∉ x::l₁, from not_mem_of_nodup_cons nd, have x ≠ y, using this, from suppose x = y, begin subst x, exact absurd !mem_cons `y ∉ y::l₁` end, have y ∉ l₁, from not_mem_of_not_mem_cons `y ∉ x::l₁`, have x ∉ y::l₁, from not_mem_cons_of_ne_of_not_mem `x ≠ y` `x ∉ l₁`, have nodup (y::l₁), from nodup_cons `y ∉ l₁` `nodup l₁`, show nodup (x::y::l₁), from nodup_cons `x ∉ y::l₁` `nodup (y::l₁)`) (λ l₁ l₂ l₃ p₁ p₂ ih₁ ih₂ nd, ih₂ (ih₁ nd)) /- product -/ section product theorem perm_product_left {l₁ l₂ : list A} (t₁ : list B) : l₁ ~ l₂ → (product l₁ t₁) ~ (product l₂ t₁) := assume p : l₁ ~ l₂, perm.induction_on p !perm.refl (λ x l₁ l₂ p r, perm_app (perm.refl (map _ t₁)) r) (λ x y l, let m₁ := map (λ b, (x, b)) t₁ in let m₂ := map (λ b, (y, b)) t₁ in let c := product l t₁ in calc m₂ ++ (m₁ ++ c) = (m₂ ++ m₁) ++ c : by rewrite append.assoc ... ~ (m₁ ++ m₂) ++ c : perm_app !perm_app_comm !perm.refl ... = m₁ ++ (m₂ ++ c) : by rewrite append.assoc) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_product_right (l : list A) {t₁ t₂ : list B} : t₁ ~ t₂ → (product l t₁) ~ (product l t₂) := list.induction_on l (λ p, by rewrite [*nil_product]) (λ a t r p, perm_app (perm_map _ p) (r p)) theorem perm_product [congr] {l₁ l₂ : list A} {t₁ t₂ : list B} : l₁ ~ l₂ → t₁ ~ t₂ → (product l₁ t₁) ~ (product l₂ t₂) := assume p₁ p₂, trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) end product /- filter -/ theorem perm_filter [congr] {l₁ l₂ : list A} {p : A → Prop} [decidable_pred p] : l₁ ~ l₂ → (filter p l₁) ~ (filter p l₂) := assume u, perm.induction_on u perm.nil (take x l₁' l₂', assume u' : l₁' ~ l₂', assume u'' : filter p l₁' ~ filter p l₂', decidable.by_cases (suppose p x, by rewrite [*filter_cons_of_pos _ this]; apply perm.skip; apply u'') (suppose ¬ p x, by rewrite [*filter_cons_of_neg _ this]; apply u'')) (take x y l, decidable.by_cases (assume H1 : p x, decidable.by_cases (assume H2 : p y, begin rewrite [filter_cons_of_pos _ H1, *filter_cons_of_pos _ H2, filter_cons_of_pos _ H1], apply perm.swap end) (assume H2 : ¬ p y, by rewrite [filter_cons_of_pos _ H1, *filter_cons_of_neg _ H2, filter_cons_of_pos _ H1])) (assume H1 : ¬ p x, decidable.by_cases (assume H2 : p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_pos _ H2, filter_cons_of_neg _ H1]) (assume H2 : ¬ p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_neg _ H2, filter_cons_of_neg _ H1]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section count variable [decA : decidable_eq A] include decA theorem count_eq_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → ∀ a, count a l₁ = count a l₂ := suppose l₁ ~ l₂, perm.induction_on this (λ a, rfl) (λ x l₁ l₂ p h a, by rewrite [*count_cons, *h a]) (λ x y l a, by_cases (suppose a = x, by_cases (suppose a = y, begin subst x, subst y end) (suppose a ≠ y, begin subst x, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end)) (suppose a ≠ x, by_cases (suppose a = y, begin subst y, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end) (suppose a ≠ y, begin rewrite [count_cons_of_ne `a≠x`, *count_cons_of_ne `a≠y`, count_cons_of_ne `a≠x`] end))) (λ l₁ l₂ l₃ p₁ p₂ h₁ h₂ a, eq.trans (h₁ a) (h₂ a)) end count end perm
2a31f3f1165b3371de8f9b46d04be932bc486f4d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/manifold/partition_of_unity.lean
8d129b488da36c47455a15acbacc5a18a1baa47b
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
27,475
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.manifold.algebra.structures import geometry.manifold.bump_function import topology.metric_space.partition_of_unity import topology.shrinking_lemma /-! # Smooth partition of unity In this file we define two structures, `smooth_bump_covering` and `smooth_partition_of_unity`. Both structures describe coverings of a set by a locally finite family of supports of smooth functions with some additional properties. The former structure is mostly useful as an intermediate step in the construction of a smooth partition of unity but some proofs that traditionally deal with a partition of unity can use a `smooth_bump_covering` as well. Given a real manifold `M` and its subset `s`, a `smooth_bump_covering ι I M s` is a collection of `smooth_bump_function`s `f i` indexed by `i : ι` such that * the center of each `f i` belongs to `s`; * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, there exists `i : ι` such that `f i =ᶠ[𝓝 x] 1`. In the same settings, a `smooth_partition_of_unity ι I M s` is a collection of smooth nonnegative functions `f i : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯`, `i : ι`, such that * the family of sets `support (f i)` is locally finite; * for each `x ∈ s`, the sum `∑ᶠ i, f i x` equals one; * for each `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a similar statement about smooth partitions of unity, see `smooth_partition_of_unity.exists_is_subordinate`. Finally, we use existence of a partition of unity to prove lemma `exists_smooth_forall_mem_convex_of_local` that allows us to construct a globally defined smooth function from local functions. ## TODO * Build a framework for to transfer local definitions to global using partition of unity and use it to define, e.g., the integral of a differential form over a manifold. Lemma `exists_smooth_forall_mem_convex_of_local` is a first step in this direction. ## Tags smooth bump function, partition of unity -/ universes uι uE uH uM uF open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory variables {ι : Type uι} {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {F : Type uF} [normed_add_comm_group F] [normed_space ℝ F] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] /-! ### Covering by supports of smooth bump functions In this section we define `smooth_bump_covering ι I M s` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to construct a smooth partition of unity and can be used instead of a partition of unity in some proofs. We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering ι I M s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/ variables (ι M) /-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if * `(f i).c ∈ s` for all `i`; * the family `λ i, support (f i)` is locally finite; * for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`; in other words, `x` belongs to the interior of `{y | f i y = 1}`; If `M` is a finite dimensional real manifold which is a `σ`-compact Hausdorff topological space, then for every covering `U : M → set M`, `∀ x, U x ∈ 𝓝 x`, there exists a `smooth_bump_covering` subordinate to `U`, see `smooth_bump_covering.exists_is_subordinate`. This covering can be used, e.g., to construct a partition of unity and to prove the weak Whitney embedding theorem. -/ @[nolint has_nonempty_instance] structure smooth_bump_covering (s : set M := univ) := (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (c_mem' : ∀ i, c i ∈ s) (locally_finite' : locally_finite (λ i, support (to_fun i))) (eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1) /-- We say that that a collection of functions form a smooth partition of unity on a set `s` if * all functions are infinitely smooth and nonnegative; * the family `λ i, support (f i)` is locally finite; * for all `x ∈ s` the sum `∑ᶠ i, f i x` equals one; * for all `x`, the sum `∑ᶠ i, f i x` is less than or equal to one. -/ structure smooth_partition_of_unity (s : set M := univ) := (to_fun : ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) (locally_finite' : locally_finite (λ i, support (to_fun i))) (nonneg' : ∀ i x, 0 ≤ to_fun i x) (sum_eq_one' : ∀ x ∈ s, ∑ᶠ i, to_fun i x = 1) (sum_le_one' : ∀ x, ∑ᶠ i, to_fun i x ≤ 1) variables {ι I M} namespace smooth_partition_of_unity variables {s : set M} (f : smooth_partition_of_unity ι I M s) {n : ℕ∞} instance {s : set M} : has_coe_to_fun (smooth_partition_of_unity ι I M s) (λ _, ι → C^∞⟮I, M; 𝓘(ℝ), ℝ⟯) := ⟨smooth_partition_of_unity.to_fun⟩ protected lemma locally_finite : locally_finite (λ i, support (f i)) := f.locally_finite' lemma nonneg (i : ι) (x : M) : 0 ≤ f i x := f.nonneg' i x lemma sum_eq_one {x} (hx : x ∈ s) : ∑ᶠ i, f i x = 1 := f.sum_eq_one' x hx lemma sum_le_one (x : M) : ∑ᶠ i, f i x ≤ 1 := f.sum_le_one' x /-- Reinterpret a smooth partition of unity as a continuous partition of unity. -/ def to_partition_of_unity : partition_of_unity ι M s := { to_fun := λ i, f i, .. f } lemma smooth_sum : smooth I 𝓘(ℝ) (λ x, ∑ᶠ i, f i x) := smooth_finsum (λ i, (f i).smooth) f.locally_finite lemma le_one (i : ι) (x : M) : f i x ≤ 1 := f.to_partition_of_unity.le_one i x lemma sum_nonneg (x : M) : 0 ≤ ∑ᶠ i, f i x := f.to_partition_of_unity.sum_nonneg x lemma cont_mdiff_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), cont_mdiff_at I 𝓘(ℝ, F) n g x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, f i x • g x) := cont_mdiff_of_support $ λ x hx, ((f i).cont_mdiff.cont_mdiff_at.of_le le_top).smul $ hg x $ tsupport_smul_subset_left _ _ hx lemma smooth_smul {g : M → F} {i} (hg : ∀ x ∈ tsupport (f i), smooth_at I 𝓘(ℝ, F) g x) : smooth I 𝓘(ℝ, F) (λ x, f i x • g x) := f.cont_mdiff_smul hg /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma cont_mdiff_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), cont_mdiff_at I 𝓘(ℝ, F) n (g i) x) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := cont_mdiff_finsum (λ i, f.cont_mdiff_smul (hg i)) $ f.locally_finite.subset $ λ i, support_smul_subset_left _ _ /-- If `f` is a smooth partition of unity on a set `s : set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth at every point of the topological support of `f i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma smooth_finsum_smul {g : ι → M → F} (hg : ∀ i (x ∈ tsupport (f i)), smooth_at I 𝓘(ℝ, F) (g i) x) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul hg lemma finsum_smul_mem_convex {g : ι → M → F} {t : set F} {x : M} (hx : x ∈ s) (hg : ∀ i, f i x ≠ 0 → g i x ∈ t) (ht : convex ℝ t) : ∑ᶠ i, f i x • g i x ∈ t := ht.finsum_mem (λ i, f.nonneg _ _) (f.sum_eq_one hx) hg /-- A smooth partition of unity `f i` is subordinate to a family of sets `U i` indexed by the same type if for each `i` the closure of the support of `f i` is a subset of `U i`. -/ def is_subordinate (f : smooth_partition_of_unity ι I M s) (U : ι → set M) := ∀ i, tsupport (f i) ⊆ U i variables {f} {U : ι → set M} @[simp] lemma is_subordinate_to_partition_of_unity : f.to_partition_of_unity.is_subordinate U ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_partition_of_unity ↔ _ is_subordinate.to_partition_of_unity /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is $C^n$ smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is $C^n$ smooth on the whole manifold. -/ lemma is_subordinate.cont_mdiff_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, cont_mdiff_on I 𝓘(ℝ, F) n (g i) (U i)) : cont_mdiff I 𝓘(ℝ, F) n (λ x, ∑ᶠ i, f i x • g i x) := f.cont_mdiff_finsum_smul $ λ i x hx, (hg i).cont_mdiff_at $ (ho i).mem_nhds (hf i hx) /-- If `f` is a smooth partition of unity on a set `s : set M` subordinate to a family of open sets `U : ι → set M` and `g : ι → M → F` is a family of functions such that `g i` is smooth on `U i`, then the sum `λ x, ∑ᶠ i, f i x • g i x` is smooth on the whole manifold. -/ lemma is_subordinate.smooth_finsum_smul {g : ι → M → F} (hf : f.is_subordinate U) (ho : ∀ i, is_open (U i)) (hg : ∀ i, smooth_on I 𝓘(ℝ, F) (g i) (U i)) : smooth I 𝓘(ℝ, F) (λ x, ∑ᶠ i, f i x • g i x) := hf.cont_mdiff_finsum_smul ho hg end smooth_partition_of_unity namespace bump_covering -- Repeat variables to drop [finite_dimensional ℝ E] and [smooth_manifold_with_corners I M] lemma smooth_to_partition_of_unity {E : Type uE} [normed_add_comm_group E] [normed_space ℝ E] {H : Type uH} [topological_space H] {I : model_with_corners ℝ E H} {M : Type uM} [topological_space M] [charted_space H M] {s : set M} (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : smooth I 𝓘(ℝ) (f.to_partition_of_unity i) := (hf i).mul $ smooth_finprod_cond (λ j _, smooth_const.sub (hf j)) $ by { simp only [mul_support_one_sub], exact f.locally_finite } variables {s : set M} /-- A `bump_covering` such that all functions in this covering are smooth generates a smooth partition of unity. In our formalization, not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`; instead, a `smooth_bump_covering` is a covering by supports of `smooth_bump_function`s. So, we define `bump_covering.to_smooth_partition_of_unity`, then reuse it in `smooth_bump_covering.to_smooth_partition_of_unity`. -/ def to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : smooth_partition_of_unity ι I M s := { to_fun := λ i, ⟨f.to_partition_of_unity i, f.smooth_to_partition_of_unity hf i⟩, .. f.to_partition_of_unity } @[simp] lemma to_smooth_partition_of_unity_to_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).to_partition_of_unity = f.to_partition_of_unity := rfl @[simp] lemma coe_to_smooth_partition_of_unity (f : bump_covering ι M s) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) (i : ι) : ⇑(f.to_smooth_partition_of_unity hf i) = f.to_partition_of_unity i := rfl lemma is_subordinate.to_smooth_partition_of_unity {f : bump_covering ι M s} {U : ι → set M} (h : f.is_subordinate U) (hf : ∀ i, smooth I 𝓘(ℝ) (f i)) : (f.to_smooth_partition_of_unity hf).is_subordinate U := h.to_partition_of_unity end bump_covering namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering ι I M s) {I} instance : has_coe_to_fun (smooth_bump_covering ι I M s) (λ x, Π (i : ι), smooth_bump_function I (x.c i)) := ⟨to_fun⟩ @[simp] lemma coe_mk (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (h₁ h₂ h₃) : ⇑(mk c to_fun h₁ h₂ h₃ : smooth_bump_covering ι I M s) = to_fun := rfl /-- We say that `f : smooth_bump_covering ι I M s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `tsupport (f i) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. -/ def is_subordinate {s : set M} (f : smooth_bump_covering ι I M s) (U : M → set M) := ∀ i, tsupport (f i) ⊆ U (f.c i) lemma is_subordinate.support_subset {fs : smooth_bump_covering ι I M s} {U : M → set M} (h : fs.is_subordinate U) (i : ι) : support (fs i) ⊆ U (fs.c i) := subset.trans subset_closure (h i) variable (I) /-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space. Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`. Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/ lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ (ι : Type uM) (f : smooth_bump_covering ι I M s), f.is_subordinate U := begin -- First we deduce some missing instances haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, -- Next we choose a covering by supports of smooth bump functions have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf, /- Then we use the shrinking lemma to get a covering by smaller open -/ rcases exists_subset_Union_closed_subset hs (λ i, (f i).open_support) (λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩, choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i), refine ⟨ι, ⟨c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩, { simpa only [smooth_bump_function.support_update_r] }, { refine (mem_Union.1 $ hsV hx).imp (λ i hi, _), exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt ((f i).support_subset_source $ hVf _ hi) (hr i hi).2 }, { simpa only [coe_mk, smooth_bump_function.support_update_r, tsupport] using hfU i } end variables {I M} protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite' protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite := fs.locally_finite.point_finite x lemma mem_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (chart_at H (fs.c i)).source := (fs i).support_subset_source $ by simp [h] lemma mem_ext_chart_at_source_of_eq_one {i : ι} {x : M} (h : fs i x = 1) : x ∈ (ext_chart_at I (fs.c i)).source := by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h } /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : M) (hx : x ∈ s) : ι := (fs.eventually_eq_one' x hx).some lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 := (fs.eventually_eq_one' x hx).some_spec lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 := (fs.eventually_eq_one x hx).eq_of_nhds lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) := by simp [fs.apply_ind x hx] lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (chart_at H (fs.c (fs.ind x hx))).source := fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx) lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source := fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx) /-- The index type of a `smooth_bump_covering` of a compact manifold is finite. -/ protected def fintype [compact_space M] : fintype ι := fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support variable [t2_space M] /-- Reinterpret a `smooth_bump_covering` as a continuous `bump_covering`. Note that not every `f : bump_covering ι M s` with smooth functions `f i` is a `smooth_bump_covering`. -/ def to_bump_covering : bump_covering ι M s := { to_fun := λ i, ⟨fs i, (fs i).continuous⟩, locally_finite' := fs.locally_finite, nonneg' := λ i x, (fs i).nonneg, le_one' := λ i x, (fs i).le_one, eventually_eq_one' := fs.eventually_eq_one' } @[simp] lemma is_subordinate_to_bump_covering {f : smooth_bump_covering ι I M s} {U : M → set M} : f.to_bump_covering.is_subordinate (λ i, U (f.c i)) ↔ f.is_subordinate U := iff.rfl alias is_subordinate_to_bump_covering ↔ _ is_subordinate.to_bump_covering /-- Every `smooth_bump_covering` defines a smooth partition of unity. -/ def to_smooth_partition_of_unity : smooth_partition_of_unity ι I M s := fs.to_bump_covering.to_smooth_partition_of_unity (λ i, (fs i).smooth) lemma to_smooth_partition_of_unity_apply (i : ι) (x : M) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ᶠ j (hj : well_ordering_rel j i), (1 - fs j x) := rfl lemma to_smooth_partition_of_unity_eq_mul_prod (i : ι) (x : M) (t : finset ι) (ht : ∀ j, well_ordering_rel j i → fs j x ≠ 0 → j ∈ t) : fs.to_smooth_partition_of_unity i x = fs i x * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j x) := fs.to_bump_covering.to_partition_of_unity_eq_mul_prod i x t ht lemma exists_finset_to_smooth_partition_of_unity_eventually_eq (i : ι) (x : M) : ∃ t : finset ι, fs.to_smooth_partition_of_unity i =ᶠ[𝓝 x] fs i * ∏ j in t.filter (λ j, well_ordering_rel j i), (1 - fs j) := fs.to_bump_covering.exists_finset_to_partition_of_unity_eventually_eq i x lemma to_smooth_partition_of_unity_zero_of_zero {i : ι} {x : M} (h : fs i x = 0) : fs.to_smooth_partition_of_unity i x = 0 := fs.to_bump_covering.to_partition_of_unity_zero_of_zero h lemma support_to_smooth_partition_of_unity_subset (i : ι) : support (fs.to_smooth_partition_of_unity i) ⊆ support (fs i) := fs.to_bump_covering.support_to_partition_of_unity_subset i lemma is_subordinate.to_smooth_partition_of_unity {f : smooth_bump_covering ι I M s} {U : M → set M} (h : f.is_subordinate U) : f.to_smooth_partition_of_unity.is_subordinate (λ i, U (f.c i)) := h.to_bump_covering.to_partition_of_unity lemma sum_to_smooth_partition_of_unity_eq (x : M) : ∑ᶠ i, fs.to_smooth_partition_of_unity i x = 1 - ∏ᶠ i, (1 - fs i x) := fs.to_bump_covering.sum_to_partition_of_unity_eq x end smooth_bump_covering variable (I) /-- Given two disjoint closed sets in a Hausdorff σ-compact finite dimensional manifold, there exists an infinitely smooth function that is equal to `0` on one of them and is equal to one on the other. -/ lemma exists_smooth_zero_one_of_closed [t2_space M] [sigma_compact_space M] {s t : set M} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C^∞⟮I, M; 𝓘(ℝ), ℝ⟯, eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin have : ∀ x ∈ t, sᶜ ∈ 𝓝 x, from λ x hx, hs.is_open_compl.mem_nhds (disjoint_right.1 hd hx), rcases smooth_bump_covering.exists_is_subordinate I ht this with ⟨ι, f, hf⟩, set g := f.to_smooth_partition_of_unity, refine ⟨⟨_, g.smooth_sum⟩, λ x hx, _, λ x, g.sum_eq_one, λ x, ⟨g.sum_nonneg x, g.sum_le_one x⟩⟩, suffices : ∀ i, g i x = 0, by simp only [this, cont_mdiff_map.coe_fn_mk, finsum_zero, pi.zero_apply], refine λ i, f.to_smooth_partition_of_unity_zero_of_zero _, exact nmem_support.1 (subset_compl_comm.1 (hf.support_subset i) hx) end namespace smooth_partition_of_unity /-- A `smooth_partition_of_unity` that consists of a single function, uniformly equal to one, defined as an example for `inhabited` instance. -/ def single (i : ι) (s : set M) : smooth_partition_of_unity ι I M s := (bump_covering.single i s).to_smooth_partition_of_unity $ λ j, begin rcases eq_or_ne j i with rfl|h, { simp only [smooth_one, continuous_map.coe_one, bump_covering.coe_single, pi.single_eq_same] }, { simp only [smooth_zero, bump_covering.coe_single, pi.single_eq_of_ne h, continuous_map.coe_zero] } end instance [inhabited ι] (s : set M) : inhabited (smooth_partition_of_unity ι I M s) := ⟨single I default s⟩ variables [t2_space M] [sigma_compact_space M] /-- If `X` is a paracompact normal topological space and `U` is an open covering of a closed set `s`, then there exists a `bump_covering ι X s` that is subordinate to `U`. -/ lemma exists_is_subordinate {s : set M} (hs : is_closed s) (U : ι → set M) (ho : ∀ i, is_open (U i)) (hU : s ⊆ ⋃ i, U i) : ∃ f : smooth_partition_of_unity ι I M s, f.is_subordinate U := begin haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H M, haveI : normal_space M := normal_of_paracompact_t2, rcases bump_covering.exists_is_subordinate_of_prop (smooth I 𝓘(ℝ)) _ hs U ho hU with ⟨f, hf, hfU⟩, { exact ⟨f.to_smooth_partition_of_unity hf, hfU.to_smooth_partition_of_unity hf⟩ }, { intros s t hs ht hd, rcases exists_smooth_zero_one_of_closed I hs ht hd with ⟨f, hf⟩, exact ⟨f, f.smooth, hf⟩ } end end smooth_partition_of_unity variables [sigma_compact_space M] [t2_space M] {t : M → set F} {n : ℕ∞} /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is $C^n$ smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a $C^n$ smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_smooth_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_cont_mdiff_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), cont_mdiff_on I 𝓘(ℝ, F) n g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^n⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := begin choose U hU g hgs hgt using Hloc, obtain ⟨f, hf⟩ := smooth_partition_of_unity.exists_is_subordinate I is_closed_univ (λ x, interior (U x)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩), refine ⟨⟨λ x, ∑ᶠ i, f i x • g i x, hf.cont_mdiff_finsum_smul (λ i, is_open_interior) $ λ i, (hgs i).mono interior_subset⟩, λ x, f.finsum_smul_mem_convex (mem_univ x) (λ i hi, hgt _ _ _) (ht _)⟩, exact interior_subset (hf _ $ subset_closure hi) end /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a neighborhood `U ∈ 𝓝 x` and a function `g : M → F` such that `g` is smooth on `U` and `g y ∈ t y` for all `y ∈ U`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local_const`. -/ lemma exists_smooth_forall_mem_convex_of_local (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ (U ∈ 𝓝 x) (g : M → F), smooth_on I 𝓘(ℝ, F) g U ∧ ∀ y ∈ U, g y ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_cont_mdiff_forall_mem_convex_of_local I ht Hloc /-- Let `M` be a σ-compact Hausdorff finite dimensional topological manifold. Let `t : M → set F` be a family of convex sets. Suppose that for each point `x : M` there exists a vector `c : F` such that for all `y` in a neighborhood of `x` we have `c ∈ t y`. Then there exists a smooth function `g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯` such that `g x ∈ t x` for all `x`. See also `exists_cont_mdiff_forall_mem_convex_of_local` and `exists_smooth_forall_mem_convex_of_local`. -/ lemma exists_smooth_forall_mem_convex_of_local_const (ht : ∀ x, convex ℝ (t x)) (Hloc : ∀ x : M, ∃ c : F, ∀ᶠ y in 𝓝 x, c ∈ t y) : ∃ g : C^∞⟮I, M; 𝓘(ℝ, F), F⟯, ∀ x, g x ∈ t x := exists_smooth_forall_mem_convex_of_local I ht $ λ x, let ⟨c, hc⟩ := Hloc x in ⟨_, hc, λ _, c, smooth_on_const, λ y, id⟩ /-- Let `M` be a smooth σ-compact manifold with extended distance. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `emetric.closed_ball x (δ x) ⊆ U i`. -/ lemma emetric.exists_smooth_forall_closed_ball_subset {M} [emetric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), emetric.closed_ball x (ennreal.of_real (δ x)) ⊆ U i := by simpa only [mem_inter_eq, forall_and_distrib, mem_preimage, mem_Inter, @forall_swap ι M] using exists_smooth_forall_mem_convex_of_local_const I emetric.exists_forall_closed_ball_subset_aux₂ (emetric.exists_forall_closed_ball_subset_aux₁ hK hU hKU hfin) /-- Let `M` be a smooth σ-compact manifold with a metric. Let `K : ι → set M` be a locally finite family of closed sets, let `U : ι → set M` be a family of open sets such that `K i ⊆ U i` for all `i`. Then there exists a positive smooth function `δ : M → ℝ≥0` such that for any `i` and `x ∈ K i`, we have `metric.closed_ball x (δ x) ⊆ U i`. -/ lemma metric.exists_smooth_forall_closed_ball_subset {M} [metric_space M] [charted_space H M] [smooth_manifold_with_corners I M] [sigma_compact_space M] {K : ι → set M} {U : ι → set M} (hK : ∀ i, is_closed (K i)) (hU : ∀ i, is_open (U i)) (hKU : ∀ i, K i ⊆ U i) (hfin : locally_finite K) : ∃ δ : C^∞⟮I, M; 𝓘(ℝ, ℝ), ℝ⟯, (∀ x, 0 < δ x) ∧ ∀ i (x ∈ K i), metric.closed_ball x (δ x) ⊆ U i := begin rcases emetric.exists_smooth_forall_closed_ball_subset I hK hU hKU hfin with ⟨δ, hδ0, hδ⟩, refine ⟨δ, hδ0, λ i x hx, _⟩, rw [← metric.emetric_closed_ball (hδ0 _).le], exact hδ i x hx end
8fb651024842049bc9a7c4c9a71bf4b22f2e7ad1
5cb186111bc6de231aef3b26698e9235da128bb0
/move.lean
6698ccc913b3cfabb744c51b2b37c7bb268f3044
[]
no_license
Kha/syntax
2f96982b920a24d9bdbbb48ad6acce1817e62f26
af05028581955d9fd5af99be9cbb82f5c9226551
refs/heads/master
1,631,456,662,519
1,523,806,396,000
1,523,978,266,000
110,000,924
1
0
null
null
null
null
UTF-8
Lean
false
false
2,928
lean
-- non-meta instance attribute [derive decidable_eq] name universes u v w namespace name -- TODO: make original non-meta by making decidable_eq instance non-meta def replace_prefix' : name → name → name → name | anonymous p p' := anonymous | (mk_string s c) p p' := if c = p then mk_string s p' else mk_string s (replace_prefix' c p p') | (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (replace_prefix' c p p') @[simp] protected def quick_lt : name → name → Prop | anonymous anonymous := false | anonymous _ := true | (mk_numeral v n) (mk_numeral v' n') := v < v' ∨ v = v' ∧ n.quick_lt n' | (mk_numeral _ _) (mk_string _ _) := true | (mk_string s n) (mk_string s' n') := s < s' ∨ s = s' ∧ n.quick_lt n' | _ _ := false instance decidable_rel_quick_lt : decidable_rel name.quick_lt := begin intros n n', induction n generalizing n', case anonymous { by_cases n' = anonymous; simp *; apply_instance }, all_goals { cases n'; { tactic.unfreeze_local_instances, -- use recursive instance simp; apply_instance } } end protected def has_lt_quick : has_lt name := ⟨name.quick_lt⟩ end name namespace option variables {α : Type u} (r : α → α → Prop) @[simp] protected def lt : option α → option α → Prop | none (some x) := true | (some x) (some y) := r x y | _ _ := false instance decidable_rel_lt [decidable_rel r] : decidable_rel (option.lt r) := by intros a b; cases a; cases b; simp; apply_instance protected def has_lt [has_lt α] : has_lt (option α) := ⟨option.lt (<)⟩ end option namespace rbmap variables {α : Type u} {β : Type v} {δ : Type w} {lt : α → α → Prop} open format prod variables [has_to_format α] [has_to_format β] private meta def format_key_data (a : α) (b : β) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : rbmap α β lt) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold (λ a b p, (fst p ++ format_key_data a b (snd p), ff)) m (to_fmt "", tt))) ++ to_fmt "⟩" meta instance : has_to_format (rbmap α β lt) := ⟨to_format⟩ end rbmap namespace list section parameters {α : Type u} {β : Type v} def pmap : Π (xs : list α), (Π (x : α), x ∈ xs → β) → list β | [] f := [] | (a :: l) f := f a (mem_cons_self a l) :: pmap l (λ x h, f x (mem_cons_of_mem a h)) end end list namespace monad def kleisli {m : Type u → Type v} [monad m] {α β γ : Type u} : (α → m β) → (β → m γ) → (α → m γ) := λ a b, (>>= b) ∘ a infixr ` >=> `:55 := kleisli end monad def unreachable {α m} [monad m] [monad_except string m] : m α := throw "unreachable"
76a0e015fa0c30242613309f7fddf69a37c895c2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/localization/integer.lean
512ea6a21df5ef57f904f2559690173d3d2bc84f
[ "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
5,390
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.localization.basic /-! # Integer elements of a localization ## Main definitions * `is_localization.is_integer` is a predicate stating that `x : S` is in the image of `R` ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_ring R] {M : submonoid R} {S : Type*} [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] open function open_locale big_operators namespace is_localization section variables (R) {M S} -- TODO: define a subalgebra of `is_integer`s /-- Given `a : S`, `S` a localization of `R`, `is_integer R a` iff `a` is in the image of the localization map from `R` to `S`. -/ def is_integer (a : S) : Prop := a ∈ (algebra_map R S).range end lemma is_integer_zero : is_integer R (0 : S) := subring.zero_mem _ lemma is_integer_one : is_integer R (1 : S) := subring.one_mem _ lemma is_integer_add {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a + b) := subring.add_mem _ ha hb lemma is_integer_mul {a b : S} (ha : is_integer R a) (hb : is_integer R b) : is_integer R (a * b) := subring.mul_mem _ ha hb lemma is_integer_smul {a : R} {b : S} (hb : is_integer R b) : is_integer R (a • b) := begin rcases hb with ⟨b', hb⟩, use a * b', rw [←hb, (algebra_map R S).map_mul, algebra.smul_def] end variables (M) {S} [is_localization M S] /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the right, matching the argument order in `localization_map.surj`. -/ lemma exists_integer_multiple' (a : S) : ∃ (b : M), is_integer R (a * algebra_map R S b) := let ⟨⟨num, denom⟩, h⟩ := is_localization.surj _ a in ⟨denom, set.mem_range.mpr ⟨num, h.symm⟩⟩ /-- Each element `a : S` has an `M`-multiple which is an integer. This version multiplies `a` on the left, matching the argument order in the `has_smul` instance. -/ lemma exists_integer_multiple (a : S) : ∃ (b : M), is_integer R ((b : R) • a) := by { simp_rw [algebra.smul_def, mul_comm _ a], apply exists_integer_multiple' } /-- We can clear the denominators of a `finset`-indexed family of fractions. -/ lemma exist_integer_multiples {ι : Type*} (s : finset ι) (f : ι → S) : ∃ (b : M), ∀ i ∈ s, is_localization.is_integer R ((b : R) • f i) := begin haveI := classical.prop_decidable, refine ⟨∏ i in s, (sec M (f i)).2, λ i hi, ⟨_, _⟩⟩, { exact (∏ j in s.erase i, (sec M (f j)).2) * (sec M (f i)).1 }, rw [ring_hom.map_mul, sec_spec', ←mul_assoc, ←(algebra_map R S).map_mul, ← algebra.smul_def], congr' 2, refine trans _ ((submonoid.subtype M).map_prod _ _).symm, rw [mul_comm, ←finset.prod_insert (s.not_mem_erase i), finset.insert_erase hi], refl end /-- We can clear the denominators of a finite indexed family of fractions. -/ lemma exist_integer_multiples_of_finite {ι : Type*} [finite ι] (f : ι → S) : ∃ (b : M), ∀ i, is_localization.is_integer R ((b : R) • f i) := begin casesI nonempty_fintype ι, obtain ⟨b, hb⟩ := exist_integer_multiples M finset.univ f, exact ⟨b, λ i, hb i (finset.mem_univ _)⟩ end /-- We can clear the denominators of a finite set of fractions. -/ lemma exist_integer_multiples_of_finset (s : finset S) : ∃ (b : M), ∀ a ∈ s, is_integer R ((b : R) • a) := exist_integer_multiples M s id /-- A choice of a common multiple of the denominators of a `finset`-indexed family of fractions. -/ noncomputable def common_denom {ι : Type*} (s : finset ι) (f : ι → S) : M := (exist_integer_multiples M s f).some /-- The numerator of a fraction after clearing the denominators of a `finset`-indexed family of fractions. -/ noncomputable def integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) : R := ((exist_integer_multiples M s f).some_spec i i.prop).some @[simp] lemma map_integer_multiple {ι : Type*} (s : finset ι) (f : ι → S) (i : s) : algebra_map R S (integer_multiple M s f i) = common_denom M s f • f i := ((exist_integer_multiples M s f).some_spec _ i.prop).some_spec /-- A choice of a common multiple of the denominators of a finite set of fractions. -/ noncomputable def common_denom_of_finset (s : finset S) : M := common_denom M s id /-- The finset of numerators after clearing the denominators of a finite set of fractions. -/ noncomputable def finset_integer_multiple [decidable_eq R] (s : finset S) : finset R := s.attach.image (λ t, integer_multiple M s id t) open_locale pointwise lemma finset_integer_multiple_image [decidable_eq R] (s : finset S) : algebra_map R S '' (finset_integer_multiple M s) = common_denom_of_finset M s • s := begin delta finset_integer_multiple common_denom, rw finset.coe_image, ext, split, { rintro ⟨_, ⟨x, -, rfl⟩, rfl⟩, rw map_integer_multiple, exact set.mem_image_of_mem _ x.prop }, { rintro ⟨x, hx, rfl⟩, exact ⟨_, ⟨⟨x, hx⟩, s.mem_attach _, rfl⟩, map_integer_multiple M s id _⟩ } end end is_localization
f9b79f48da13afc752772d9ce2cd12d8bb4394ea
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/mirror.lean
16b41f1eea6b0e2bf8662d0fb56052952b08ab19
[ "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,655
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.big_operators.nat_antidiagonal import data.polynomial.ring_division /-! # "Mirror" of a univariate polynomial > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `polynomial.mirror`, a variant of `polynomial.reverse`. The difference between `reverse` and `mirror` is that `reverse` will decrease the degree if the polynomial is divisible by `X`. ## Main definitions - `polynomial.mirror` ## Main results - `polynomial.mirror_mul_of_domain`: `mirror` preserves multiplication. - `polynomial.irreducible_of_mirror`: an irreducibility criterion involving `mirror` -/ namespace polynomial open_locale polynomial section semiring variables {R : Type*} [semiring R] (p q : R[X]) /-- mirror of a polynomial: reverses the coefficients while preserving `polynomial.nat_degree` -/ noncomputable def mirror := p.reverse * X ^ p.nat_trailing_degree @[simp] lemma mirror_zero : (0 : R[X]).mirror = 0 := by simp [mirror] lemma mirror_monomial (n : ℕ) (a : R) : (monomial n a).mirror = (monomial n a) := begin classical, by_cases ha : a = 0, { rw [ha, monomial_zero_right, mirror_zero] }, { rw [mirror, reverse, nat_degree_monomial n a, if_neg ha, nat_trailing_degree_monomial ha, ← C_mul_X_pow_eq_monomial, reflect_C_mul_X_pow, rev_at_le (le_refl n), tsub_self, pow_zero, mul_one] }, end lemma mirror_C (a : R) : (C a).mirror = C a := mirror_monomial 0 a lemma mirror_X : X.mirror = (X : R[X]) := mirror_monomial 1 (1 : R) lemma mirror_nat_degree : p.mirror.nat_degree = p.nat_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, nontriviality R, rw [mirror, nat_degree_mul', reverse_nat_degree, nat_degree_X_pow, tsub_add_cancel_of_le p.nat_trailing_degree_le_nat_degree], rwa [leading_coeff_X_pow, mul_one, reverse_leading_coeff, ne, trailing_coeff_eq_zero] end lemma mirror_nat_trailing_degree : p.mirror.nat_trailing_degree = p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, mirror_zero] }, { rw [mirror, nat_trailing_degree_mul_X_pow ((mt reverse_eq_zero.mp) hp), reverse_nat_trailing_degree, zero_add] }, end lemma coeff_mirror (n : ℕ) : p.mirror.coeff n = p.coeff (rev_at (p.nat_degree + p.nat_trailing_degree) n) := begin by_cases h2 : p.nat_degree < n, { rw [coeff_eq_zero_of_nat_degree_lt (by rwa mirror_nat_degree)], by_cases h1 : n ≤ p.nat_degree + p.nat_trailing_degree, { rw [rev_at_le h1, coeff_eq_zero_of_lt_nat_trailing_degree], exact (tsub_lt_iff_left h1).mpr (nat.add_lt_add_right h2 _) }, { rw [←rev_at_fun_eq, rev_at_fun, if_neg h1, coeff_eq_zero_of_nat_degree_lt h2] } }, rw not_lt at h2, rw [rev_at_le (h2.trans (nat.le_add_right _ _))], by_cases h3 : p.nat_trailing_degree ≤ n, { rw [←tsub_add_eq_add_tsub h2, ←tsub_tsub_assoc h2 h3, mirror, coeff_mul_X_pow', if_pos h3, coeff_reverse, rev_at_le (tsub_le_self.trans h2)] }, rw not_le at h3, rw coeff_eq_zero_of_nat_degree_lt (lt_tsub_iff_right.mpr (nat.add_lt_add_left h3 _)), exact coeff_eq_zero_of_lt_nat_trailing_degree (by rwa mirror_nat_trailing_degree), end --TODO: Extract `finset.sum_range_rev_at` lemma. lemma mirror_eval_one : p.mirror.eval 1 = p.eval 1 := begin simp_rw [eval_eq_sum_range, one_pow, mul_one, mirror_nat_degree], refine finset.sum_bij_ne_zero _ _ _ _ _, { exact λ n hn hp, rev_at (p.nat_degree + p.nat_trailing_degree) n }, { intros n hn hp, rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right, ←mirror_nat_trailing_degree], exact nat_trailing_degree_le_of_ne_zero hp }, { exact λ n₁ n₂ hn₁ hp₁ hn₂ hp₂ h, by rw [←@rev_at_invol _ n₁, h, rev_at_invol] }, { intros n hn hp, use rev_at (p.nat_degree + p.nat_trailing_degree) n, refine ⟨_, _, rev_at_invol.symm⟩, { rw finset.mem_range_succ_iff at *, rw rev_at_le (hn.trans (nat.le_add_right _ _)), rw [tsub_le_iff_tsub_le, add_comm, add_tsub_cancel_right], exact nat_trailing_degree_le_of_ne_zero hp }, { change p.mirror.coeff _ ≠ 0, rwa [coeff_mirror, rev_at_invol] } }, { exact λ n hn hp, p.coeff_mirror n }, end lemma mirror_mirror : p.mirror.mirror = p := polynomial.ext (λ n, by rw [coeff_mirror, coeff_mirror, mirror_nat_degree, mirror_nat_trailing_degree, rev_at_invol]) variables {p q} lemma mirror_involutive : function.involutive (mirror : R[X] → R[X]) := mirror_mirror lemma mirror_eq_iff : p.mirror = q ↔ p = q.mirror := mirror_involutive.eq_iff @[simp] lemma mirror_inj : p.mirror = q.mirror ↔ p = q := mirror_involutive.injective.eq_iff @[simp] lemma mirror_eq_zero : p.mirror = 0 ↔ p = 0 := ⟨λ h, by rw [←p.mirror_mirror, h, mirror_zero], λ h, by rw [h, mirror_zero]⟩ variables (p q) @[simp] lemma mirror_trailing_coeff : p.mirror.trailing_coeff = p.leading_coeff := by rw [leading_coeff, trailing_coeff, mirror_nat_trailing_degree, coeff_mirror, rev_at_le (nat.le_add_left _ _), add_tsub_cancel_right] @[simp] lemma mirror_leading_coeff : p.mirror.leading_coeff = p.trailing_coeff := by rw [←p.mirror_mirror, mirror_trailing_coeff, p.mirror_mirror] lemma coeff_mul_mirror : (p * p.mirror).coeff (p.nat_degree + p.nat_trailing_degree) = p.sum (λ n, (^ 2)) := begin rw [coeff_mul, finset.nat.sum_antidiagonal_eq_sum_range_succ_mk], refine (finset.sum_congr rfl (λ n hn, _)).trans (p.sum_eq_of_subset (λ n, (^ 2)) (λ n, zero_pow zero_lt_two) _ (λ n hn, finset.mem_range_succ_iff.mpr ((le_nat_degree_of_mem_supp n hn).trans (nat.le_add_right _ _)))).symm, rw [coeff_mirror, ←rev_at_le (finset.mem_range_succ_iff.mp hn), rev_at_invol, ←sq], end variables [no_zero_divisors R] lemma nat_degree_mul_mirror : (p * p.mirror).nat_degree = 2 * p.nat_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, nat_degree_zero, mul_zero] }, rw [nat_degree_mul hp (mt mirror_eq_zero.mp hp), mirror_nat_degree, two_mul], end lemma nat_trailing_degree_mul_mirror : (p * p.mirror).nat_trailing_degree = 2 * p.nat_trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, nat_trailing_degree_zero, mul_zero] }, rw [nat_trailing_degree_mul hp (mt mirror_eq_zero.mp hp), mirror_nat_trailing_degree, two_mul], end end semiring section ring variables {R : Type*} [ring R] (p q : R[X]) lemma mirror_neg : (-p).mirror = -(p.mirror) := by rw [mirror, mirror, reverse_neg, nat_trailing_degree_neg, neg_mul_eq_neg_mul] variables [no_zero_divisors R] lemma mirror_mul_of_domain : (p * q).mirror = p.mirror * q.mirror := begin by_cases hp : p = 0, { rw [hp, zero_mul, mirror_zero, zero_mul] }, by_cases hq : q = 0, { rw [hq, mul_zero, mirror_zero, mul_zero] }, rw [mirror, mirror, mirror, reverse_mul_of_domain, nat_trailing_degree_mul hp hq, pow_add], rw [mul_assoc, ←mul_assoc q.reverse], conv_lhs { congr, skip, congr, rw [←X_pow_mul] }, repeat { rw [mul_assoc], }, end lemma mirror_smul (a : R) : (a • p).mirror = a • p.mirror := by rw [←C_mul', ←C_mul', mirror_mul_of_domain, mirror_C] end ring section comm_ring variables {R : Type*} [comm_ring R] [no_zero_divisors R] {f : R[X]} lemma irreducible_of_mirror (h1 : ¬ is_unit f) (h2 : ∀ k, f * f.mirror = k * k.mirror → k = f ∨ k = -f ∨ k = f.mirror ∨ k = -f.mirror) (h3 : ∀ g, g ∣ f → g ∣ f.mirror → is_unit g) : irreducible f := begin split, { exact h1 }, { intros g h fgh, let k := g * h.mirror, have key : f * f.mirror = k * k.mirror, { rw [fgh, mirror_mul_of_domain, mirror_mul_of_domain, mirror_mirror, mul_assoc, mul_comm h, mul_comm g.mirror, mul_assoc, ←mul_assoc] }, have g_dvd_f : g ∣ f, { rw fgh, exact dvd_mul_right g h }, have h_dvd_f : h ∣ f, { rw fgh, exact dvd_mul_left h g }, have g_dvd_k : g ∣ k, { exact dvd_mul_right g h.mirror }, have h_dvd_k_rev : h ∣ k.mirror, { rw [mirror_mul_of_domain, mirror_mirror], exact dvd_mul_left h g.mirror }, have hk := h2 k key, rcases hk with hk | hk | hk | hk, { exact or.inr (h3 h h_dvd_f (by rwa ← hk)) }, { exact or.inr (h3 h h_dvd_f (by rwa [← neg_eq_iff_eq_neg.mpr hk, mirror_neg, dvd_neg])) }, { exact or.inl (h3 g g_dvd_f (by rwa ← hk)) }, { exact or.inl (h3 g g_dvd_f (by rwa [← neg_eq_iff_eq_neg.mpr hk, dvd_neg])) } }, end end comm_ring end polynomial
d30007870ce63ad5b2a7ed817478fd4d7780b321
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/fib_brec.lean
ecd88c82bf94278b1096dd2ff54b667d1b4964bd
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,091
lean
import data.nat.basic data.prod open prod namespace nat namespace manual definition brec_on {C : nat → Type} (n : nat) (F : Π (n : nat), @nat.below C n → C n) : C n := have general : C n × @nat.below C n, from nat.rec_on n (pair (F zero poly_unit.star) poly_unit.star) (λ (n₁ : nat) (r₁ : C n₁ × @nat.below C n₁), have b : @nat.below C (succ n₁), from r₁, have c : C (succ n₁), from F (succ n₁) b, pair c b), pr₁ general end manual definition fib (n : nat) := nat.brec_on n (λ (n : nat), nat.cases_on n (λ (b₀ : nat.below zero), succ zero) (λ (n₁ : nat), nat.cases_on n₁ (λ b₁ : nat.below (succ zero), succ zero) (λ (n₂ : nat) (b₂ : nat.below (succ (succ n₂))), pr₁ b₂ + pr₁ (pr₂ b₂)))) theorem fib_0 : fib 0 = 1 := rfl theorem fib_1 : fib 1 = 1 := rfl theorem fib_s_s (n : nat) : fib (succ (succ n)) = fib (succ n) + fib n := rfl example : fib 5 = 8 := rfl example : fib 9 = 55 := rfl end nat
379c32ddbeab98f2f637d9b5bff36da4d9fc8b0a
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/multiset/intervals.lean
db4bb4fee79c38aaf4ef0db2a3f4d99ce1afb4e1
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
3,467
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 data.multiset.nodup import data.list.intervals /-! # Intervals in ℕ as multisets For now this only covers `Ico n m`, the "closed-open" interval containing `[n, ..., m-1]`. -/ namespace multiset open list /-! ### Ico -/ /-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/ def Ico (n m : ℕ) : multiset ℕ := Ico n m namespace Ico theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) := congr_arg coe $ list.Ico.map_add _ _ _ theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) := congr_arg coe $ list.Ico.map_sub _ _ _ h theorem zero_bot (n : ℕ) : Ico 0 n = range n := congr_arg coe $ list.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := list.Ico.length _ _ theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := list.Ico.mem theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 := congr_arg coe $ list.Ico.eq_nil_of_le h @[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 := eq_zero_of_le $ le_refl n @[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n := iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m + Ico m l = Ico n l := congr_arg coe $ list.Ico.append_consecutive hnm hml @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 := congr_arg coe $ list.Ico.bag_inter_consecutive n m l @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := congr_arg coe $ list.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m := by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m := congr_arg coe $ list.Ico.eq_cons h @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := congr_arg coe $ list.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := list.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := congr_arg coe $ list.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := congr_arg coe $ list.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := congr_arg coe $ list.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := congr_arg coe $ list.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := congr_arg coe $ list.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := congr_arg coe $ list.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := congr_arg coe $ list.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := congr_arg coe $ list.Ico.filter_le n m l end Ico end multiset
e406ac002f9bba156f48c75dac156542340f2b7d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/geometry/euclidean/monge_point.lean
6fa7a0dc05769c53add54b4470bab095f02d4950
[ "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
38,586
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import geometry.euclidean.circumcenter /-! # Monge point and orthocenter This file defines the orthocenter of a triangle, via its n-dimensional generalization, the Monge point of a simplex. ## Main definitions * `monge_point` is the Monge point of a simplex, defined in terms of its position on the Euler line and then shown to be the point of concurrence of the Monge planes. * `monge_plane` is a Monge plane of an (n+2)-simplex, which is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). * `altitude` is the line that passes through a vertex of a simplex and is orthogonal to the opposite face. * `orthocenter` is defined, for the case of a triangle, to be the same as its Monge point, then shown to be the point of concurrence of the altitudes. * `orthocentric_system` is a predicate on sets of points that says whether they are four points, one of which is the orthocenter of the other three (in which case various other properties hold, including that each is the orthocenter of the other three). ## References * <https://en.wikipedia.org/wiki/Altitude_(triangle)> * <https://en.wikipedia.org/wiki/Monge_point> * <https://en.wikipedia.org/wiki/Orthocentric_system> * Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point Sphere of an n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf) -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace affine namespace simplex open finset affine_subspace euclidean_geometry points_with_circumcenter_index variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The Monge point of a simplex (in 2 or more dimensions) is a generalization of the orthocenter of a triangle. It is defined to be the intersection of the Monge planes, where a Monge plane is the (n-1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an (n-2)-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). The circumcenter O, centroid G and Monge point M are collinear in that order on the Euler line, with OG : GM = (n-1) : 2. Here, we use that ratio to define the Monge point (so resulting in a point that equals the centroid in 0 or 1 dimensions), and then show in subsequent lemmas that the point so defined lies in the Monge planes and is their unique point of intersection. -/ def monge_point {n : ℕ} (s : simplex ℝ P n) : P := (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter /-- The position of the Monge point in relation to the circumcenter and centroid. -/ lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) : s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) • ((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ s.circumcenter := rfl /-- The Monge point lies in the affine span. -/ lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) : s.monge_point ∈ affine_span ℝ (set.range s.points) := smul_vsub_vadd_mem _ _ (centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1))) s.circumcenter_mem_affine_span s.circumcenter_mem_affine_span /-- Two simplices with the same points have the same Monge point. -/ lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n} (h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point := by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h, circumcenter_eq_of_range_eq h] omit V /-- The weights for the Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹ | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_weights_with_circumcenter` sums to 1. -/ @[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) : ∑ i, monge_point_weights_with_circumcenter n i = 1 := begin simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const, card_fin, nsmul_eq_mul], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1], ring end include V /-- The Monge point of an (n+2)-simplex, in terms of `points_with_circumcenter`. -/ lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) : s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination s.points_with_circumcenter (monge_point_weights_with_circumcenter n) := begin rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, circumcenter_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, ←linear_map.map_smul, weighted_vsub_vadd_affine_combination], congr' with i, rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply], have hn1 : (n + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, cases i; simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter, monge_point_weights_with_circumcenter]; rw [nat.add_sub_assoc (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)], { rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin], have hn3 : (n + 2 + 1 : ℝ) ≠ 0, { exact_mod_cast nat.succ_ne_zero _ }, field_simp [hn1, hn3, mul_comm] }, { field_simp [hn1], ring } end omit V /-- The weights for the Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/ def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) : points_with_circumcenter_index (n + 2) → ℝ | (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0 | circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ)) /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the result of subtracting `centroid_weights_with_circumcenter` from `monge_point_weights_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ = monge_point_weights_with_circumcenter n - centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) := begin ext i, cases i, { rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter], have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1, { simp [card_compl, fintype.card_fin, h] }, rw hu, by_cases hi : i = i₁ ∨ i = i₂; simp [compl_eq_univ_sdiff, hi] }, { simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter, monge_point_vsub_face_centroid_weights_with_circumcenter] } end /-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/ @[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : ∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 := begin rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h, simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter], rw [sum_centroid_weights_with_circumcenter, sub_self], simp [←card_pos, card_compl, h] end include V /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, in terms of `points_with_circumcenter`. -/ lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points = (univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) := by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter, centroid_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub, monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h] /-- The Monge point of an (n+2)-simplex, minus the centroid of an n-dimensional face, is orthogonal to the difference of the two vertices not in that face. -/ lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : ⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points, s.points i₁ -ᵥ s.points i₂⟫ = 0 := begin simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h, point_eq_affine_combination_of_points_with_circumcenter, affine_combination_vsub], have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0, { simp }, rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs, sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter], simp only [monge_point_vsub_face_centroid_weights_with_circumcenter, points_with_circumcenter_point], let fs : finset (fin (n + 3)) := {i₁, i₂}, have hfs : ∀ i : fin (n + 3), i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂), { intros i hi, split ; { intro hj, simpa [←hj] using hi } }, rw ←sum_subset fs.subset_univ _, { simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter, points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter], rw [←sum_subset fs.subset_univ _], { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], repeat { rw ←sum_subset fs.subset_univ _ }, { simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton], simp [h, h.symm, dist_comm (s.points i₁)] }, all_goals { intros i hu hi, simp [hfs i hi] } }, { intros i hu hi, simp [hfs i hi, point_weights_with_circumcenter] } }, { intros i hu hi, simp [hfs i hi] } end /-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine subspace of the subspace spanned by the simplex that passes through the centroid of an n-dimensional face and is orthogonal to the opposite edge (in 2 dimensions, this is the same as an altitude). This definition is only intended to be used when `i₁ ≠ i₂`. -/ def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : affine_subspace ℝ P := mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of a Monge plane. -/ lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points) (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- The Monge plane associated with vertices `i₁` and `i₂` equals that associated with `i₂` and `i₁`. -/ lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) : s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ := begin simp_rw monge_plane_def, congr' 3, { congr' 1, exact insert_singleton_comm _ _ }, { ext, simp_rw submodule.mem_span_singleton, split, all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } } end /-- The Monge point lies in the Monge planes. -/ lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : s.monge_point ∈ s.monge_plane i₁ i₂ := begin rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _), direction_mk', submodule.mem_orthogonal'], refine ⟨_, s.monge_point_mem_affine_span⟩, intros v hv, rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩, rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub h, mul_zero] end -- This doesn't actually need the `i₁ ≠ i₂` hypothesis, but it's -- convenient for the proof and `monge_plane` isn't intended to be -- useful without that hypothesis. /-- The direction of a Monge plane. -/ lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) : (s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [monge_plane_def, direction_inf_of_mem_inf (s.monge_point_mem_monge_plane h), direction_mk', direction_affine_span] /-- The Monge point is the only point in all the Monge planes from any one vertex. -/ lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)} {i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) : p = s.monge_point := begin rw ←@vsub_eq_zero_iff_eq V, have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈ (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points), { intros i₂ hne, rw [←s.direction_monge_plane hne, vsub_right_mem_direction_iff_mem (s.monge_point_mem_monge_plane hne)], exact h i₂ hne }, have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}), (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ, { rw submodule.mem_infi, exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 }, rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi, have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) = (-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})), { rw [set.image_image], ext x, simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton], split, { rintros ⟨i, rfl⟩, use [i, ⟨set.mem_univ _, i.property.symm⟩] }, { rintros ⟨i, ⟨hiu, hi⟩, rfl⟩, use [⟨i, hi.symm⟩, rfl] } }, rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _), set.image_univ] at hi, have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points), { let s₁ : finset (fin (n + 3)) := univ.erase i₁, obtain ⟨i₂, h₂⟩ := card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]), have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm, exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 }, exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint) _ hv hi, end /-- An altitude of a simplex is the line that passes through a vertex and is orthogonal to the opposite face. -/ def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P := mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) /-- The definition of an altitude. -/ lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.altitude i = mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓ affine_span ℝ (set.range s.points) := rfl /-- A vertex lies in the corresponding altitude. -/ lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : s.points i ∈ s.altitude i := (mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩ /-- The direction of an altitude. -/ lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : (s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓ vector_span ℝ (set.range s.points) := by rw [altitude_def, direction_inf_of_mem (self_mem_mk' (s.points i) _) (mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span, direction_affine_span] /-- The vector span of the opposite face lies in the direction orthogonal to an altitude. -/ lemma vector_span_le_altitude_direction_orthogonal {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ≤ (s.altitude i).directionᗮ := begin rw direction_altitude, exact le_trans (vector_span ℝ (s.points '' ↑(finset.univ.erase i))).le_orthogonal_orthogonal (submodule.orthogonal_le inf_le_left) end open finite_dimensional /-- An altitude is finite-dimensional. -/ instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) := begin rw direction_altitude, apply_instance end /-- An altitude is one-dimensional (i.e., a line). -/ @[simp] lemma finrank_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : finrank ℝ ((s.altitude i).direction) = 1 := begin rw direction_altitude, have h := submodule.finrank_add_inf_finrank_orthogonal (vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))), have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp }, rw [finrank_vector_span_of_affine_independent s.independent (fintype.card_fin _), finrank_vector_span_image_finset_of_affine_independent s.independent hc] at h, simpa using h end /-- A line through a vertex is the altitude through that vertex if and only if it is orthogonal to the opposite face. -/ lemma affine_span_insert_singleton_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) (p : P) : affine_span ℝ {p, s.points i} = s.altitude i ↔ (p ≠ s.points i ∧ p ∈ affine_span ℝ (set.range s.points) ∧ p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) := begin rw [eq_iff_direction_eq_of_mem (mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _), ←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p, direction_affine_span, direction_affine_span, direction_affine_span], split, { intro h, split, { intro heq, rw [heq, set.pair_eq_singleton, vector_span_singleton] at h, have hd : finrank ℝ (s.altitude i).direction = 0, { rw [←h, finrank_bot] }, simpa using hd }, { rw [←submodule.mem_inf, inf_comm, ←direction_altitude, ←h], exact vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) } }, { rintro ⟨hne, h⟩, rw [←submodule.mem_inf, inf_comm, ←direction_altitude] at h, rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _), set.insert_diff_of_mem _ (set.mem_singleton _), set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton], refine eq_of_le_of_finrank_eq _ _, { rw submodule.span_le, simpa using h }, { rw [finrank_direction_altitude, finrank_span_set_eq_card], { simp }, { refine linear_independent_singleton _, simpa using hne } } } end end simplex namespace triangle open euclidean_geometry finset simplex affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The orthocenter of a triangle is the intersection of its altitudes. It is defined here as the 2-dimensional case of the Monge point. -/ def orthocenter (t : triangle ℝ P) : P := t.monge_point /-- The orthocenter equals the Monge point. -/ lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl /-- The position of the orthocenter in relation to the circumcenter and centroid. -/ lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) : t.orthocenter = (3 : ℝ) • ((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter := begin rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter], norm_num end /-- The orthocenter lies in the affine span. -/ lemma orthocenter_mem_affine_span (t : triangle ℝ P) : t.orthocenter ∈ affine_span ℝ (set.range t.points) := t.monge_point_mem_affine_span /-- Two triangles with the same points have the same orthocenter. -/ lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P} (h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter := monge_point_eq_of_range_eq h /-- In the case of a triangle, altitudes are the same thing as Monge planes. -/ lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂) (h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ := begin have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!, have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!, rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton, coe_insert, coe_singleton, vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)], simp [h₂₃, submodule.span_insert_eq_span] end /-- The orthocenter lies in the altitudes. -/ lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} : t.orthocenter ∈ t.altitude i₁ := begin obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!, rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃], exact t.monge_point_mem_monge_plane h₂₃ end /-- The orthocenter is the only point lying in any two of the altitudes. -/ lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P} (h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter := begin obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! }, rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁, rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂, rw orthocenter_eq_monge_point, have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i, { intros i hi, have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! }, cases hi₁₂, { exact hi₁₂ ▸ h₂ }, { exact hi₁₂ ▸ h₁ } }, exact eq_monge_point_of_forall_mem_monge_plane ha end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius. -/ lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) = t.circumradius := begin rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg, t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h, t.orthocenter_eq_monge_point, monge_point_eq_affine_combination_of_points_with_circumcenter, dist_affine_combination t.points_with_circumcenter (sum_monge_point_weights_with_circumcenter _) (sum_reflection_circumcenter_weights_with_circumcenter h)], simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter, reflection_circumcenter_weights_with_circumcenter], have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _, obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ : ∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!, simp_rw [←sum_sdiff hu, hi₃], simp [hi₃₁, hi₃₂], norm_num end /-- The distance from the orthocenter to the reflection of the circumcenter in a side equals the circumradius, variant using a `finset`. -/ lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) : dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3)))) t.circumcenter) = t.circumradius := by { convert dist_orthocenter_reflection_circumcenter _ h, simp } /-- The affine span of the orthocenter and a vertex is contained in the altitude. -/ lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) : affine_span ℝ {t.orthocenter, t.points i} ≤ t.altitude i := begin refine span_points_subset_coe_of_subset_coe _, rw [set.insert_subset, set.singleton_subset_iff], exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩ end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then an altitude of `t₂` from a vertex that was not replaced is the corresponding side of `t₁`. -/ lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.altitude j₂ = affine_span ℝ {t₁.points i₁, t₁.points i₂} := begin symmetry, rw [←h₂, t₂.affine_span_insert_singleton_eq_altitude_iff], rw [h₂], use (injective_of_affine_independent t₁.independent).ne hi₁₂, have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points), { refine ext_of_direction_eq _ ⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩, refine eq_of_le_of_finrank_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _, { have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton, h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff], exact ⟨t₁.orthocenter_mem_affine_span, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (set.mem_range_self _)⟩ }, { rw [direction_affine_span, direction_affine_span, finrank_vector_span_of_affine_independent t₁.independent (fintype.card_fin _), finrank_vector_span_of_affine_independent t₂.independent (fintype.card_fin _)] } }, rw he, use mem_affine_span ℝ (set.mem_range_self _), have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! }, rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton, h₁, h₃], have hle : (t₁.altitude i₃).directionᗮ ≤ (affine_span ℝ ({t₁.orthocenter, t₁.points i₃} : set P)).directionᗮ := submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)), refine hle ((t₁.vector_span_le_altitude_direction_orthogonal i₃) _), have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! }, rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton], refine vsub_mem_vector_span ℝ (set.mem_insert _ _) (set.mem_insert_of_mem _ (set.mem_singleton _)) end /-- Suppose we are given a triangle `t₁`, and replace one of its vertices by its orthocenter, yielding triangle `t₂` (with vertices not necessarily listed in the same order). Then the orthocenter of `t₂` is the vertex of `t₁` that was replaced. -/ lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3} (hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃) (hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂) (h₃ : t₂.points j₃ = t₁.points i₃) : t₂.orthocenter = t₁.points i₁ := begin refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm, { rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃, exact mem_affine_span ℝ (set.mem_insert _ _) }, { rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂, exact mem_affine_span ℝ (set.mem_insert _ _) } end end triangle end affine namespace euclidean_geometry open affine affine_subspace finite_dimensional variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- Four points form an orthocentric system if they consist of the vertices of a triangle and its orthocenter. -/ def orthocentric_system (s : set P) : Prop := ∃ t : triangle ℝ P, t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points) /-- This is an auxiliary lemma giving information about the relation of two triangles in an orthocentric system; it abstracts some reasoning, with no geometric content, that is common to some other lemmas. Suppose the orthocentric system is generated by triangle `t`, and we are given three points `p` in the orthocentric system. Then either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂` and `j₃` of `t`, or `p` has the same points as `t`. -/ lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : (∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ (∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧ t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points := begin by_cases h : t.orthocenter ∈ set.range p, { left, rcases h with ⟨i₁, h₁⟩, obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ : ∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃, { clear h₁, dec_trivial! }, have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i, { intros i hi, replace hps := set.mem_of_mem_insert_of_ne (set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm), exact hps }, rcases h i₂ h₁₂ with ⟨j₂, h₂⟩, rcases h i₃ h₁₃ with ⟨j₃, h₃⟩, have hj₂₃ : j₂ ≠ j₃, { intro he, rw [he, h₃] at h₂, exact h₂₃.symm (hpi h₂) }, exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ }, { right, have hs := set.subset_diff_singleton hps h, rw set.insert_diff_self_of_not_mem ho at hs, refine set.eq_of_subset_of_card_le hs _, rw [set.card_range_of_injective hpi, set.card_range_of_injective (injective_of_affine_independent t.independent)] } end /-- For any three points in an orthocentric system generated by triangle `t`, there is a point in the subspace spanned by the triangle from which the distance of all those three points equals the circumradius. -/ lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P} (ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P} (hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) : ∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius := begin rcases exists_of_range_subset_orthocentric_system ho hps hpi with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter, reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _)) t.circumcenter_mem_affine_span], intros p₁ hp₁, rcases hp₁ with ⟨i, rfl⟩, replace h₁₂₃ := h₁₂₃ i, repeat { cases h₁₂₃ }, { rw h₁, exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ }, { rw [←h₂, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))], exact t.dist_circumcenter_eq_circumradius _ }, { rw [←h₃, dist_reflection_eq_of_mem _ (mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert_of_mem _ (set.mem_singleton _))))], exact t.dist_circumcenter_eq_circumradius _ } }, { use [t.circumcenter, t.circumcenter_mem_affine_span], intros p₁ hp₁, rw hs at hp₁, rcases hp₁ with ⟨i, rfl⟩, exact t.dist_circumcenter_eq_circumradius _ } end /-- Any three points in an orthocentric system are affinely independent. -/ lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rcases ho with ⟨t, hto, hst⟩, rw hst at hps, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩, exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi end /-- Any three points in an orthocentric system span the same subspace as the whole orthocentric system. -/ lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_span ℝ (set.range p) = affine_span ℝ s := begin have ha := ho.affine_independent hps hpi, rcases ho with ⟨t, hto, hts⟩, have hs : affine_span ℝ s = affine_span ℝ (set.range t.points), { rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] }, refine ext_of_direction_eq _ ⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩, have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance }, haveI := hfd, refine eq_of_le_of_finrank_eq (direction_le (affine_span_mono ℝ hps)) _, rw [hs, direction_affine_span, direction_affine_span, finrank_vector_span_of_affine_independent ha (fintype.card_fin _), finrank_vector_span_of_affine_independent t.independent (fintype.card_fin _)] end /-- All triangles in an orthocentric system have the same circumradius. -/ lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) : ∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r := begin rcases ho with ⟨t, hto, hts⟩, use t.circumradius, intros t₂ ht₂, have ht₂s := ht₂, rw hts at ht₂, rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂ (injective_of_affine_independent t₂.independent) with ⟨c, hc, h⟩, rw set.forall_range_iff at h, have hs : set.range t.points ⊆ s, { rw hts, exact set.subset_insert _ _ }, rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs (injective_of_affine_independent t.independent), ←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s (injective_of_affine_independent t₂.independent)] at hc, exact (t₂.eq_circumradius_of_dist_eq hc h).symm end /-- Given any triangle in an orthocentric system, the fourth point is its orthocenter. -/ lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s) {t : triangle ℝ P} (ht : set.range t.points ⊆ s) : s = insert t.orthocenter (set.range t.points) := begin rcases ho with ⟨t₀, ht₀o, ht₀s⟩, rw ht₀s at ht, rcases exists_of_range_subset_orthocentric_system ht₀o ht (injective_of_affine_independent t.independent) with ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs, { obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ : ∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃, { clear h₂ h₃, dec_trivial! }, suffices h : t₀.points j₁ = t.orthocenter, { have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x }, have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x }, rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui], simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃], rw set.insert_comm }, exact (triangle.orthocenter_replace_orthocenter_eq_point hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm }, { rw hs, convert ht₀s using 2, exact triangle.orthocenter_eq_of_range_eq hs } end end euclidean_geometry
e43f456acdc5cd2570f9ec7dd78814c353e2f42a
495c02489c2d6a1db94dfdba71dd800d3cc67df2
/group_theory/subgroup.lean
b1ca1c32795e2f6ee596ac11612d0369a7ad181b
[ "Apache-2.0" ]
permissive
leodemoura/leanproved
e0fcbe4f4d72bf0dad9a962ed111b5975cf90712
de56e0af159dd0c0421733289c76aa79c78a0191
refs/heads/master
1,606,822,676,898
1,435,711,541,000
1,435,711,541,000
36,675,856
0
0
null
1,433,178,724,000
1,433,178,724,000
null
UTF-8
Lean
false
false
18,812
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import data algebra.group data open function -- ⁻¹ in eq.ops conflicts with group ⁻¹ -- open eq.ops local notation H1 ▸ H2 := eq.subst H1 H2 open set local attribute set [reducible] section open finset -- overloading problem, use set.subset explicitly for now-example (A : Type) (x : A) (S H : set A) (Pin : x ∈ S) (Psub : S ⊆ H) : x ∈ H := Psub Pin end namespace algebra namespace coset -- semigroup coset definition section variable {A : Type} variable [s : semigroup A] include s definition lmul (a : A) := λ x, a * x definition rmul (a : A) := λ x, x * a definition l a (S : set A) := (lmul a) '[S] definition r a (S : set A) := (rmul a) '[S] lemma lmul_compose : ∀ (a b : A), (lmul a) ∘ (lmul b) = lmul (a*b) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑lmul, mul.assoc]) lemma rmul_compose : ∀ (a b : A), (rmul a) ∘ (rmul b) = rmul (b*a) := take a, take b, funext (assume x, by rewrite [↑function.compose, ↑rmul, mul.assoc]) lemma lcompose a b (S : set A) : l a (l b S) = l (a*b) S := calc (lmul a) '[(lmul b) '[S]] = ((lmul a) ∘ (lmul b)) '[S] : image_compose ... = lmul (a*b) '[S] : lmul_compose lemma rcompose a b (S : set A) : r a (r b S) = r (b*a) S := calc (rmul a) '[(rmul b) '[S]] = ((rmul a) ∘ (rmul b)) '[S] : image_compose ... = rmul (b*a) '[S] : rmul_compose lemma l_sub a (S H : set A) : S ⊆ H → (l a S) ⊆ (l a H) := image_subset (lmul a) definition l_same S (a b : A) := l a S = l b S definition r_same S (a b : A) := r a S = r b S lemma l_same.refl S (a : A) : l_same S a a := rfl lemma l_same.symm S (a b : A) : l_same S a b → l_same S b a := eq.symm lemma l_same.trans S (a b c : A) : l_same S a b → l_same S b c → l_same S a c := eq.trans example (S : set A) : equivalence (l_same S) := mk_equivalence (l_same S) (l_same.refl S) (l_same.symm S) (l_same.trans S) end end coset section variable {A : Type} variable [s : group A] include s definition lmul_by (a : A) := λ x, a * x definition rmul_by (a : A) := λ x, x * a definition glcoset a (H : set A) : set A := λ x, H (a⁻¹ * x) definition grcoset H (a : A) : set A := λ x, H (x * a⁻¹) definition conj_by (g a : A) := g * a * g⁻¹ definition is_conjugate (a b : A) := ∃ x, conj_by x b = a end end algebra namespace group open algebra namespace ops infixr `∘>`:55 := glcoset -- stronger than = (50), weaker than * (70) infixl `<∘`:55 := grcoset infixr `∘c`:55 := conj_by end ops end group namespace algebra open group.ops section variable {A : Type} variable [s : group A] include s -- too precious to make it wider scope. group.ops can now be openned without it. local infixl `~` := is_conjugate lemma conj_compose (f g a : A) : f ∘c g ∘c a = f*g ∘c a := calc f ∘c g ∘c a = f * (g * a * g⁻¹) * f⁻¹ : rfl ... = f * (g * a) * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * g⁻¹ * f⁻¹ : mul.assoc ... = f * g * a * (g⁻¹ * f⁻¹) : mul.assoc ... = f * g * a * (f * g)⁻¹ : mul_inv lemma conj_id (a : A) : 1 ∘c a = a := calc 1 * a * 1⁻¹ = a * 1⁻¹ : one_mul ... = a * 1 : one_inv ... = a : mul_one lemma conj_one (g : A) : g ∘c 1 = 1 := calc g * 1 * g⁻¹ = g * g⁻¹ : mul_one ... = 1 : mul.right_inv lemma conj_inv_cancel (g : A) : ∀ a, g⁻¹ ∘c g ∘c a = a := assume a, calc g⁻¹ ∘c g ∘c a = g⁻¹*g ∘c a : conj_compose ... = 1 ∘c a : mul.left_inv ... = a : conj_id lemma is_conj.refl (a : A) : a ~ a := exists.intro 1 (conj_id a) lemma is_conj.symm (a b : A) : a ~ b → b ~ a := assume Pab, obtain x (Pconj : x ∘c b = a), from Pab, assert Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, from (congr_arg2 conj_by (eq.refl x⁻¹) Pconj), exists.intro x⁻¹ (eq.symm (conj_inv_cancel x b ▸ Pxinv)) lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c := assume Pab, assume Pbc, obtain x (Px : x ∘c b = a), from Pab, obtain y (Py : y ∘c c = b), from Pbc, exists.intro (x*y) (calc x*y ∘c c = x ∘c y ∘c c : conj_compose ... = x ∘c b : Py ... = a : Px) lemma lmul_inj (a : A) : injective (lmul_by a) := take x₁ x₂ Peq, by esimp [lmul_by] at Peq; rewrite [-(inv_mul_cancel_left a x₁), -(inv_mul_cancel_left a x₂), Peq] lemma lmul_inv_on (a : A) (H : set A) : left_inv_on (lmul_by a⁻¹) (lmul_by a) H := take x Px, show a⁻¹*(a*x) = x, by rewrite inv_mul_cancel_left lemma lmul_inj_on (a : A) (H : set A) : inj_on (lmul_by a) H := inj_on_of_left_inv_on (lmul_inv_on a H) lemma glcoset_eq_lcoset a (H : set A) : a ∘> H = coset.l a H := setext begin intro x, rewrite [↑glcoset, ↑coset.l, ↑image, ↑set_of, ↑mem, ↑coset.lmul], apply iff.intro, intro P1, apply (exists.intro (a⁻¹ * x)), apply and.intro, exact P1, exact (mul_inv_cancel_left a x), show (∃ (x_1 : A), H x_1 ∧ a * x_1 = x) → H (a⁻¹ * x), from assume P2, obtain x_1 P3, from P2, have P4 : a * x_1 = x, from and.right P3, have P5 : x_1 = a⁻¹ * x, from eq_inv_mul_of_mul_eq P4, eq.subst P5 (and.left P3) end lemma grcoset_eq_rcoset a (H : set A) : H <∘ a = coset.r a H := begin rewrite [↑grcoset, ↑coset.r, ↑image, ↑coset.rmul, ↑set_of], apply setext, rewrite ↑mem, intro x, apply iff.intro, show H (x * a⁻¹) → (∃ (x_1 : A), H x_1 ∧ x_1 * a = x), from assume PH, exists.intro (x * a⁻¹) (and.intro PH (inv_mul_cancel_right x a)), show (∃ (x_1 : A), H x_1 ∧ x_1 * a = x) → H (x * a⁻¹), from assume Pex, obtain x_1 Pand, from Pex, eq.subst (eq_mul_inv_of_mul_eq (and.right Pand)) (and.left Pand) end lemma glcoset_sub a (S H : set A) : S ⊆ H → (a ∘> S) ⊆ (a ∘> H) := assume Psub, assert P : _, from coset.l_sub a S H Psub, eq.symm (glcoset_eq_lcoset a S) ▸ eq.symm (glcoset_eq_lcoset a H) ▸ P lemma glcoset_compose (a b : A) (H : set A) : a ∘> b ∘> H = a*b ∘> H := begin rewrite [*glcoset_eq_lcoset], exact (coset.lcompose a b H) end lemma grcoset_compose (a b : A) (H : set A) : H <∘ a <∘ b = H <∘ a*b := begin rewrite [*grcoset_eq_rcoset], exact (coset.rcompose b a H) end lemma glcoset_id (H : set A) : 1 ∘> H = H := funext (assume x, calc (1 ∘> H) x = H (1⁻¹*x) : rfl ... = H (1*x) : {one_inv} ... = H x : {one_mul x}) lemma grcoset_id (H : set A) : H <∘ 1 = H := funext (assume x, calc H (x*1⁻¹) = H (x*1) : {one_inv} ... = H x : {mul_one x}) --lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := -- funext (assume x, -- calc glcoset a⁻¹ (glcoset a H) x = H x : {mul_inv_cancel_left a⁻¹ x}) lemma glcoset_inv a (H : set A) : a⁻¹ ∘> a ∘> H = H := calc a⁻¹ ∘> a ∘> H = (a⁻¹*a) ∘> H : glcoset_compose ... = 1 ∘> H : mul.left_inv ... = H : glcoset_id lemma grcoset_inv H (a : A) : (H <∘ a) <∘ a⁻¹ = H := funext (assume x, calc grcoset (grcoset H a) a⁻¹ x = H x : {inv_mul_cancel_right x a⁻¹}) lemma glcoset_cancel a b (H : set A) : (b*a⁻¹) ∘> a ∘> H = b ∘> H := calc (b*a⁻¹) ∘> a ∘> H = b*a⁻¹*a ∘> H : glcoset_compose ... = b ∘> H : {inv_mul_cancel_right b a} lemma grcoset_cancel a b (H : set A) : H <∘ a <∘ a⁻¹*b = H <∘ b := calc H <∘ a <∘ a⁻¹*b = H <∘ a*(a⁻¹*b) : grcoset_compose ... = H <∘ b : {mul_inv_cancel_left a b} -- test how precedence breaks tie: infixr takes hold since its encountered first example a b (H : set A) : a ∘> H <∘ b = a ∘> (H <∘ b) := rfl -- should be true for semigroup as well but irrelevant lemma lcoset_rcoset_assoc a b (H : set A) : a ∘> H <∘ b = (a ∘> H) <∘ b := funext (assume x, begin esimp [glcoset, grcoset], rewrite mul.assoc end) definition mul_closed_on H := ∀ (x y : A), x ∈ H → y ∈ H → x * y ∈ H lemma closed_lcontract a (H : set A) : mul_closed_on H → a ∈ H → a ∘> H ⊆ H := begin rewrite [↑mul_closed_on, ↑glcoset, ↑subset, ↑mem], intro Pclosed, intro PHa, intro x, intro PHainvx, exact (eq.subst (mul_inv_cancel_left a x) (Pclosed a (a⁻¹*x) PHa PHainvx)) end lemma closed_rcontract a (H : set A) : mul_closed_on H → a ∈ H → H <∘ a ⊆ H := assume P1 : mul_closed_on H, assume P2 : H a, begin rewrite ↑subset, intro x, rewrite [↑grcoset, ↑mem], intro P3, exact (eq.subst (inv_mul_cancel_right x a) (P1 (x * a⁻¹) a P3 P2)) end lemma closed_lcontract_set a (H G : set A) : mul_closed_on G → H ⊆ G → a∈G → a∘>H ⊆ G := assume Pclosed, assume PHsubG, assume PainG, assert PaGsubG : a ∘> G ⊆ G, from closed_lcontract a G Pclosed PainG, assert PaHsubaG : a ∘> H ⊆ a ∘> G, from eq.symm (glcoset_eq_lcoset a H) ▸ eq.symm (glcoset_eq_lcoset a G) ▸ (coset.l_sub a H G PHsubG), subset.trans _ _ _ PaHsubaG PaGsubG definition subgroup.has_inv H := ∀ (a : A), a ∈ H → a⁻¹ ∈ H -- two ways to define the same equivalence relatiohship for subgroups definition in_lcoset [reducible] H (a b : A) := a ∈ b ∘> H definition in_rcoset [reducible] H (a b : A) := a ∈ H <∘ b definition same_lcoset [reducible] H (a b : A) := a ∘> H = b ∘> H definition same_rcoset [reducible] H (a b : A) := H <∘ a = H <∘ b definition same_left_right_coset (N : set A) := ∀ x, x ∘> N = N <∘ x structure is_subgroup [class] (H : set A) : Type := (has_one : H 1) (mul_closed : mul_closed_on H) (has_inv : subgroup.has_inv H) structure is_normal_subgroup [class] (N : set A) extends is_subgroup N := (normal : same_left_right_coset N) end section subgroup variable {A : Type} variable [s : group A] include s variable {H : set A} variable [is_subg : is_subgroup H] include is_subg lemma subg_has_one : H (1 : A) := @is_subgroup.has_one A s H is_subg lemma subg_mul_closed : mul_closed_on H := @is_subgroup.mul_closed A s H is_subg lemma subg_has_inv : subgroup.has_inv H := @is_subgroup.has_inv A s H is_subg lemma subgroup_coset_id : ∀ a, a ∈ H → (a ∘> H = H ∧ H <∘ a = H) := take a, assume PHa : H a, assert Pl : a ∘> H ⊆ H, from closed_lcontract a H subg_mul_closed PHa, assert Pr : H <∘ a ⊆ H, from closed_rcontract a H subg_mul_closed PHa, assert PHainv : H a⁻¹, from subg_has_inv a PHa, and.intro (setext (assume x, begin esimp [glcoset, mem], apply iff.intro, apply Pl, intro PHx, exact (subg_mul_closed a⁻¹ x PHainv PHx) end)) (setext (assume x, begin esimp [grcoset, mem], apply iff.intro, apply Pr, intro PHx, exact (subg_mul_closed x a⁻¹ PHx PHainv) end)) lemma subgroup_lcoset_id : ∀ a, a ∈ H → a ∘> H = H := take a, assume PHa : H a, and.left (subgroup_coset_id a PHa) lemma subgroup_rcoset_id : ∀ a, a ∈ H → H <∘ a = H := take a, assume PHa : H a, and.right (subgroup_coset_id a PHa) lemma subg_in_coset_refl (a : A) : a ∈ a ∘> H ∧ a ∈ H <∘ a := assert PH1 : H 1, from subg_has_one, assert PHinvaa : H (a⁻¹*a), from (eq.symm (mul.left_inv a)) ▸ PH1, assert PHainva : H (a*a⁻¹), from (eq.symm (mul.right_inv a)) ▸ PH1, and.intro PHinvaa PHainva lemma subg_in_lcoset_same_lcoset (a b : A) : in_lcoset H a b → same_lcoset H a b := assume Pa_in_b : H (b⁻¹*a), have Pbinva : b⁻¹*a ∘> H = H, from subgroup_lcoset_id (b⁻¹*a) Pa_in_b, have Pb_binva : b ∘> b⁻¹*a ∘> H = b ∘> H, from Pbinva ▸ rfl, have Pbbinva : b*(b⁻¹*a)∘>H = b∘>H, from glcoset_compose b (b⁻¹*a) H ▸ Pb_binva, mul_inv_cancel_left b a ▸ Pbbinva lemma subg_same_lcoset_in_lcoset (a b : A) : same_lcoset H a b → in_lcoset H a b := assume Psame : a∘>H = b∘>H, assert Pa : a ∈ a∘>H, from and.left (subg_in_coset_refl a), by exact (Psame ▸ Pa) lemma subg_lcoset_same (a b : A) : in_lcoset H a b = (a∘>H = b∘>H) := propext(iff.intro (subg_in_lcoset_same_lcoset a b) (subg_same_lcoset_in_lcoset a b)) lemma subg_rcoset_same (a b : A) : in_rcoset H a b = (H<∘a = H<∘b) := propext(iff.intro (assume Pa_in_b : H (a*b⁻¹), have Pabinv : H<∘a*b⁻¹ = H, from subgroup_rcoset_id (a*b⁻¹) Pa_in_b, have Pabinv_b : H <∘ a*b⁻¹ <∘ b = H <∘ b, from Pabinv ▸ rfl, have Pabinvb : H <∘ a*b⁻¹*b = H <∘ b, from grcoset_compose (a*b⁻¹) b H ▸ Pabinv_b, inv_mul_cancel_right a b ▸ Pabinvb) (assume Psame, assert Pa : a ∈ H<∘a, from and.right (subg_in_coset_refl a), by exact (Psame ▸ Pa))) lemma subg_same_lcoset.refl (a : A) : same_lcoset H a a := rfl lemma subg_same_rcoset.refl (a : A) : same_rcoset H a a := rfl lemma subg_same_lcoset.symm (a b : A) : same_lcoset H a b → same_lcoset H b a := eq.symm lemma subg_same_rcoset.symm (a b : A) : same_rcoset H a b → same_rcoset H b a := eq.symm lemma subg_same_lcoset.trans (a b c : A) : same_lcoset H a b → same_lcoset H b c → same_lcoset H a c := eq.trans lemma subg_same_rcoset.trans (a b c : A) : same_rcoset H a b → same_rcoset H b c → same_rcoset H a c := eq.trans variable {S : set A} lemma subg_lcoset_subset_subg (Psub : S ⊆ H) (a : A) : a ∈ H → a ∘> S ⊆ H := assume Pin, have P : a ∘> S ⊆ a ∘> H, from glcoset_sub a S H Psub, subgroup_lcoset_id a Pin ▸ P end subgroup section normal_subg open quot variable {A : Type} variable [s : group A] include s variable (N : set A) variable [is_nsubg : is_normal_subgroup N] include is_nsubg local notation a `~` b := same_lcoset N a b -- note : does not bind as strong as → lemma nsubg_normal : same_left_right_coset N := @is_normal_subgroup.normal A s N is_nsubg lemma nsubg_same_lcoset_product : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ((a1*a2) ~ (b1*b2)) := take a1, take a2, take b1, take b2, assume Psame1 : a1 ∘> N = b1 ∘> N, assume Psame2 : a2 ∘> N = b2 ∘> N, calc a1*a2 ∘> N = a1 ∘> a2 ∘> N : glcoset_compose ... = a1 ∘> b2 ∘> N : by rewrite Psame2 ... = a1 ∘> (N <∘ b2) : by rewrite (nsubg_normal N) ... = (a1 ∘> N) <∘ b2 : by rewrite lcoset_rcoset_assoc ... = (b1 ∘> N) <∘ b2 : by rewrite Psame1 ... = N <∘ b1 <∘ b2 : by rewrite (nsubg_normal N) ... = N <∘ (b1*b2) : by rewrite grcoset_compose ... = (b1*b2) ∘> N : by rewrite (nsubg_normal N) example (a b : A) : (a⁻¹ ~ b⁻¹) = (a⁻¹ ∘> N = b⁻¹ ∘> N) := rfl lemma nsubg_same_lcoset_inv : ∀ a b, (a ~ b) → (a⁻¹ ~ b⁻¹) := take a b, assume Psame : a ∘> N = b ∘> N, calc a⁻¹ ∘> N = a⁻¹*b*b⁻¹ ∘> N : by rewrite mul_inv_cancel_right ... = a⁻¹*b ∘> b⁻¹ ∘> N : by rewrite glcoset_compose ... = a⁻¹*b ∘> (N <∘ b⁻¹) : by rewrite nsubg_normal ... = (a⁻¹*b ∘> N) <∘ b⁻¹ : by rewrite lcoset_rcoset_assoc ... = (a⁻¹ ∘> b ∘> N) <∘ b⁻¹ : by rewrite glcoset_compose ... = (a⁻¹ ∘> a ∘> N) <∘ b⁻¹ : by rewrite Psame ... = N <∘ b⁻¹ : by rewrite glcoset_inv ... = b⁻¹ ∘> N : by rewrite nsubg_normal definition nsubg_setoid [instance] : setoid A := setoid.mk (same_lcoset N) (mk_equivalence (same_lcoset N) (subg_same_lcoset.refl) (subg_same_lcoset.symm) (subg_same_lcoset.trans)) definition coset_of : Type := quot (nsubg_setoid N) definition coset_inv_base (a : A) : coset_of N := ⟦a⁻¹⟧ definition coset_product (a b : A) : coset_of N := ⟦a*b⟧ lemma coset_product_well_defined : ∀ a1 a2 b1 b2, (a1 ~ b1) → (a2 ~ b2) → ⟦a1*a2⟧ = ⟦b1*b2⟧ := take a1 a2 b1 b2, assume P1 P2, quot.sound (nsubg_same_lcoset_product N a1 a2 b1 b2 P1 P2) definition coset_mul (aN bN : coset_of N) : coset_of N := quot.lift_on₂ aN bN (coset_product N) (coset_product_well_defined N) lemma coset_inv_well_defined : ∀ a b, (a ~ b) → ⟦a⁻¹⟧ = ⟦b⁻¹⟧ := take a b, assume P, quot.sound (nsubg_same_lcoset_inv N a b P) definition coset_inv (aN : coset_of N) : coset_of N := quot.lift_on aN (coset_inv_base N) (coset_inv_well_defined N) definition coset_one : coset_of N := ⟦1⟧ local infixl `cx`:70 := coset_mul N example (a b c : A) : ⟦a⟧ cx ⟦b*c⟧ = ⟦a*(b*c)⟧ := rfl lemma coset_product_assoc (a b c : A) : ⟦a⟧ cx ⟦b⟧ cx ⟦c⟧ = ⟦a⟧ cx (⟦b⟧ cx ⟦c⟧) := calc ⟦a*b*c⟧ = ⟦a*(b*c)⟧ : {mul.assoc a b c} ... = ⟦a⟧ cx ⟦b*c⟧ : rfl lemma coset_product_left_id (a : A) : ⟦1⟧ cx ⟦a⟧ = ⟦a⟧ := calc ⟦1*a⟧ = ⟦a⟧ : {one_mul a} lemma coset_product_right_id (a : A) : ⟦a⟧ cx ⟦1⟧ = ⟦a⟧ := calc ⟦a*1⟧ = ⟦a⟧ : {mul_one a} lemma coset_product_left_inv (a : A) : ⟦a⁻¹⟧ cx ⟦a⟧ = ⟦1⟧ := calc ⟦a⁻¹*a⟧ = ⟦1⟧ : {mul.left_inv a} lemma coset_mul.assoc (aN bN cN : coset_of N) : aN cx bN cx cN = aN cx (bN cx cN) := quot.ind (λ a, quot.ind (λ b, quot.ind (λ c, coset_product_assoc N a b c) cN) bN) aN lemma coset_mul.one_mul (aN : coset_of N) : coset_one N cx aN = aN := quot.ind (coset_product_left_id N) aN lemma coset_mul.mul_one (aN : coset_of N) : aN cx (coset_one N) = aN := quot.ind (coset_product_right_id N) aN lemma coset_mul.left_inv (aN : coset_of N) : (coset_inv N aN) cx aN = (coset_one N) := quot.ind (coset_product_left_inv N) aN definition mk_quotient_group : group (coset_of N):= group.mk (coset_mul N) (coset_mul.assoc N) (coset_one N) (coset_mul.one_mul N) (coset_mul.mul_one N) (coset_inv N) (coset_mul.left_inv N) end normal_subg namespace group namespace quotient section open quot variable {A : Type} variable [s : group A] include s variable {N : set A} variable [is_nsubg : is_normal_subgroup N] include is_nsubg definition quotient_group [instance] : group (coset_of N) := mk_quotient_group N example (aN : coset_of N) : aN * aN⁻¹ = 1 := mul.right_inv aN definition natural (a : A) : coset_of N := ⟦a⟧ end end quotient end group end algebra
8bdd618cabd7cb69a5a83c807fafd0048f396524
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/geometry/manifold/manifold.lean
c8f5500bf58ccf74096fd496ae83c3ba82b09f81
[ "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
26,457
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Manifolds A manifold is a topological space M locally modelled on a model space H, i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to H. If the changes of charts satisfy some additional property (for instance if they are smooth), then M inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a manifold: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the manifold structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions * `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos) * `pregroupoid H` : a subset of local homeomorphisms of `H` stable under composition and restriction, but not inverse (ex: smooth maps) * `groupoid_of_pregroupoid`: construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) * `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` * `manifold H M` : manifold structure on `M` modelled on `H`, given by an atlas of local homeomorphisms from `M` to `H` whose sources cover `M`. This is a type class. * `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a manifold modelled on `H`, require that all coordinate changes belong to `G`. This is a type class * `atlas H M` : when `M` is a manifold modelled on `H`, the atlas of this manifold structure, i.e., the set of charts * `structomorph G M M'` : the set of diffeomorphisms between the manifolds `M` and `M'` for the groupoid `G`. We avoid the word diffeomorphisms, keeping it for the smooth category. As a basic example, we give the instance `instance manifold_model_space (H : Type*) [topological_space H] : manifold H H` saying that a topological space is a manifold over itself, with the identity as unique chart. This manifold structure is compatible with any groupoid. ## Implementation notes The atlas in a manifold is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between M and M' do *not* induce a bijection between the atlases of M and M': the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `manifold_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a manifold, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over ℂ^n) will also be seen sometimes as a real manifold modelled over ℝ^(2n). -/ noncomputable theory local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable universes u variables {H : Type u} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms, i.e., `local_homeomorph.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ local infixr ` ≫ₕ `:100 := local_homeomorph.trans open set local_homeomorph section groupoid /- One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on H × E where E is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a manifold over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form s × E The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of diffeomorphisms does not have to be a diffeomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (comp : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (inv : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem : local_homeomorph.refl H ∈ members) (locality : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] @[reducible] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) (by apply_instance) /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, comp := λe e' he he', begin cases he; simp at he he', { simpa [he] }, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, inv := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa [e.to_local_equiv.image_source_eq_target.symm] using E }, end, id_mem := mem_union_left _ (mem_insert _ ∅), locality := λe he, begin cases e.source.eq_empty_or_nonempty with h h, { right, exact h }, { left, rcases h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, interior_eq_of_open open_s], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [interior_eq_of_open open_s, univ_subset_iff] at this, simpa [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, source_eq_of_eq_on_source he'e] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e.to_fun e.source ∧ PG.property e.inv_fun e.target}, comp := λe e' he he', begin split, { apply PG.comp he.1 he'.1, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, inv := λe he, ⟨he.2, he.1⟩, id_mem := ⟨PG.id_mem, PG.id_mem⟩, locality := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1, exact (interior_eq_of_open s_open).symm }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.inv_fun x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.inv_fun ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2, exact (interior_eq_of_open s_open).symm } }, end, eq_on_source := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := eq_on_source_symm ee', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid (PG : pregroupoid H) (e : local_homeomorph H H) : e ∈ PG.groupoid ↔ PG.property e.to_fun e.source ∧ PG.property e.inv_fun e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin assume e he, rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e.to_fun e.source) : PG.property e'.to_fun e'.source := begin rw ← he'.1, exact PG.congr e.open_source (λx hx, (he'.2 x hx).symm) he, end /-- The groupoid of all local homeomorphisms on a topological space H -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid { property := λf s, true, comp := λf g u v hf hg huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } end groupoid /-- A manifold is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space H, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each x a member `chart_at x` of the atlas containing x in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over ℂ^n) will also be seen sometimes as a real manifold over ℝ^(2n). -/ class manifold (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas : set (local_homeomorph M H)) (chart_at : M → local_homeomorph M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) export manifold attribute [simp] mem_chart_source chart_mem_atlas section manifold /-- Any space is a manifold modelled over itself, by just using the identity chart -/ instance manifold_model_space (H : Type*) [topological_space H] : manifold H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial manifold structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp] lemma model_space_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, manifold.atlas] /-- In the model space, chart_at is always the identity -/ @[simp] lemma chart_at_model_space_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x end manifold /-- Sometimes, one may want to construct a manifold structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `manifold_core`. -/ structure manifold_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e').to_fun (e.symm.trans e').source) namespace manifold_core variables [topological_space H] (c : manifold_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e.to_fun ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.inv_fun ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f.to_fun ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e'.to_fun ∘ e.inv_fun ⁻¹' s ∩ (e.target ∩ e.inv_fun ⁻¹' e'.source) = e.target ∩ (e'.to_fun ∘ e.inv_fun ⁻¹' s ∩ e.inv_fun ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } def to_manifold : @manifold H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end manifold_core section has_groupoid variables [topological_space H] [topological_space M] [manifold H M] /-- A manifold has an atlas in a groupoid G if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [manifold H M] (G : structure_groupoid H) : Prop := (compatible : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e').to_fun (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', (mem_groupoid_of_pregroupoid PG _).mpr ⟨h he he', h he' he⟩⟩ /-- The trivial manifold structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw model_space_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any manifold structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ /-- A G-diffeomorphism between two manifolds is a homeomorphism which, when read in the charts, belongs to G. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [manifold H M] [manifold H M'] extends homeomorph M M' := (to_fun_mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [manifold H M'] [manifold H M''] /-- The identity is a diffeomorphism of any manifold, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [manifold H M] [has_groupoid M G] : structomorph G M M := { to_fun_mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { to_fun_mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.inv _ (e.to_fun_mem_groupoid c' c hc' hc), simp at this, rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { to_fun_mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality _ (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁).to_fun x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁).to_fun ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, ⟨this, _⟩⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.comp _ _ (e.to_fun_mem_groupoid c g hc hg₁) (e'.to_fun_mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source_trans, trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source_restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source F₁ F₂ A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
7af9e3ddf9a4a4bc87bae3d2b3127dce002eadf5
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/1331.lean
31fdcb5e79a853e07f0734894917e455a97d1d9a
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
369
lean
def is_space : char → Prop | #" " := true | #"\x09" := true -- \t | #"\n" := true | #"\x0d" := true -- \r | _ := false instance is_space.decidable_pred : decidable_pred is_space := begin delta is_space, apply_instance end def f (a : nat) : nat := a + 2 open tactic lemma flemma : f 0 = 2 := begin delta f, guard_target 0 + 2 = 2, reflexivity end
ad60b1111aa1dd81bc05da33c1d8eb91f5d162d9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/simpCnstr1.lean
e55b1074b75c30f7a18f097b7100a7c9799fdf06
[ "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,439
lean
import Lean open Lean in open Lean.Meta in def test (declName : Name) : MetaM Unit := do let info ← getConstInfo declName forallTelescope info.type fun _ e => do let some (e', p) ← Linear.simp? e none | throwError "failed to simplify{indentExpr e}" check p unless (← isDefEq (← inferType p) (← mkEq e e')) do throwError "invalid proof" IO.println s!"{← Meta.ppExpr e} ==> {← Meta.ppExpr e'}" axiom ex1 (a b : Nat) : a + b + 1 + a < b + 4 + a axiom ex2 (a b : Nat) : a + b + 1 + a = b + 4 + a + b axiom ex3 (a b : Nat) : 5 = b + 4 + a + b axiom ex4 (a b : Nat) : 4 = 1 + a axiom ex5 (a b : Nat) : 4 + ((a + a) + b) + (a + a) + (b + b) ≤ 3 + (4*a + b) + b + 8 + 1 axiom ex6 (a b : Nat) : 4 = 8 + a axiom ex7 (a b : Nat) : a + a ≤ 8 + a + a + b axiom ex8 (a b c d : Nat) : b + a + c + d ≤ a + b + a + b axiom ex9 (a b : Nat) : a + b + 1 + a > b + 4 + a axiom ex10 (a b : Nat) : a + b + 1 + a ≥ b + 4 + a axiom ex11 (a b : Nat) : ¬ (a + b + 1 + a < b + 4 + a) axiom ex12 (a b : Nat) : ¬ (a + b + 1 + a > b + 4 + a) axiom ex13 (a b : Nat) : ¬ (a + b + 1 + a ≤ b + 4 + a) axiom ex14 (a b c d : Nat) : ¬ (a + d + b + 1 + a + d ≥ b + 4 + a + c) #eval test ``ex1 #eval test ``ex2 #eval test ``ex3 #eval test ``ex4 #eval test ``ex5 #eval test ``ex6 #eval test ``ex7 #eval test ``ex8 #eval test ``ex9 #eval test ``ex10 #eval test ``ex11 #eval test ``ex12 #eval test ``ex13 #eval test ``ex14
95e7bda4f1d3fdd3c98f4bcd362fd7fe7a339ca9
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world2/level4.lean
9b6b9beface84373e3bf6df987748fcc793dc582
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
1,075
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level3 -- hide namespace mynat -- hide /- # World 2 -- Addition world ## Level 4 (boss level) : `add_comm` You are equipped with: * `add_zero (a : mynat) : a + 0 = a` * `add_succ (a b : mynat) : a + succ(b) = succ (a + b)` * `zero_add (a : mynat) : 0 + a = a` * `add_assoc (a b c : mynat) : (a + b) + c = a + (b + c)` * `succ_add (a b : mynat) : succ a + b = succ (a + b)` [boss battle music] -/ /- Lemma On the set of natural numbers, addition is commutative. In other words, for all natural numbers $a$ and $b$, we have $$ a + b = b + a. $$ -/ lemma add_comm (a b : mynat) : a + b = b + a := begin [less_leaky] induction b with d hd, { -- ⊢ a + 0 = 0 + a, rw zero_add, rw add_zero, refl }, { rw add_succ, rw hd, rw succ_add, refl } end /- If you got this far -- nice! You're nearly ready to go onto multiplication world. There are just a couple more useful lemmas which you should prove first. Press on to level 5. -/ end mynat -- hide
93285172aa45a1c22e97d38b84c777fa13cdd460
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Server/Snapshots.lean
488fec2aea11462bcb9945fb88edeaf2ab2f1114
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,656
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Init.System.IO import Lean.Elab.Import import Lean.Elab.Command /-! One can think of this module as being a partial reimplementation of Lean.Elab.Frontend which also stores a snapshot of the world after each command. Importantly, we allow (re)starting compilation from any snapshot/position in the file for interactive editing purposes. -/ namespace Lean namespace Server namespace Snapshots open Elab /-- The data associated with a snapshot is different depending on whether it was produced from the header or from a command. -/ inductive SnapshotData where | headerData : Command.State → SnapshotData | cmdData : Command.State → SnapshotData -- NOTE(WN): these carry the same dat but we leave open the future -- possibility of more snapshot variants. For example, within tactic blocks. deriving Inhabited /-- What Lean knows about the world after the header and each command. -/ structure Snapshot where /- Where the command which produced this snapshot begins. Note that neighbouring snapshots are *not* necessarily attached beginning-to-end, since inputs outside the grammar advance the parser but do not produce snapshots. -/ beginPos : String.Pos stx : Syntax mpState : Parser.ModuleParserState data : SnapshotData deriving Inhabited namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def toCmdState : Snapshot → Command.State | { data := SnapshotData.headerData cmdState, .. } => cmdState | { data := SnapshotData.cmdData cmdState, .. } => cmdState def env (s : Snapshot) : Environment := s.toCmdState.env def msgLog (s : Snapshot) : MessageLog := s.toCmdState.messages end Snapshot def reparseHeader (contents : String) (header : Snapshot) (opts : Options := {}) : IO Snapshot := do let inputCtx := Parser.mkInputContext contents "<input>" let (_, newHeaderParserState, _) ← Parser.parseHeader inputCtx pure { header with mpState := newHeaderParserState } private def ioErrorFromEmpty (ex : Empty) : IO.Error := nomatch ex /-- Parses the next command occurring after the given snapshot without elaborating it. -/ def parseNextCmd (contents : String) (snap : Snapshot) : IO Syntax := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.toCmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, _, _) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog cmdStx /-- Parse remaining file without elaboration. NOTE that doing so can lead to parse errors or even wrong syntax objects, so it should only be done for reporting preliminary results! -/ partial def parseAhead (contents : String) (snap : Snapshot) : IO (Array Syntax) := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.toCmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } go inputCtx pmctx snap.mpState #[] where go inputCtx pmctx cmdParserState stxs := do let (cmdStx, cmdParserState, _) := Parser.parseCommand inputCtx pmctx cmdParserState snap.msgLog if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then stxs.push cmdStx else go inputCtx pmctx cmdParserState (stxs.push cmdStx) /-- Compiles the next command occurring after the given snapshot. If there is no next command (file ended), returns messages produced through the file. -/ -- NOTE: This code is really very similar to Elab.Frontend. But generalizing it -- over "store snapshots"/"don't store snapshots" would likely result in confusing -- isServer? conditionals and not be worth it due to how short it is. def compileNextCmd (contents : String) (snap : Snapshot) : IO (Sum Snapshot MessageLog) := do let inputCtx := Parser.mkInputContext contents "<input>" let cmdState := snap.toCmdState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let (cmdStx, cmdParserState, msgLog) := Parser.parseCommand inputCtx pmctx snap.mpState snap.msgLog let cmdPos := cmdStx.getPos?.get! if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then Sum.inr msgLog else let cmdStateRef ← IO.mkRef { snap.toCmdState with messages := msgLog } let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos fileName := inputCtx.fileName fileMap := inputCtx.fileMap } EIO.toIO ioErrorFromEmpty $ Elab.Command.catchExceptions (Elab.Command.elabCommand cmdStx) cmdCtx cmdStateRef let postCmdState ← cmdStateRef.get let postCmdSnap : Snapshot := { beginPos := cmdPos stx := cmdStx mpState := cmdParserState data := SnapshotData.cmdData postCmdState } Sum.inl postCmdSnap /-- Compiles all commands after the given snapshot. Returns them as a list, together with the final message log. -/ partial def compileCmdsAfter (contents : String) (snap : Snapshot) : IO (List Snapshot × MessageLog) := do let cmdOut ← compileNextCmd contents snap match cmdOut with | Sum.inl snap => let (snaps, msgLog) ← compileCmdsAfter contents snap (snap :: snaps, msgLog) | Sum.inr msgLog => ([], msgLog) end Snapshots end Server end Lean
674efd1d9f7295e1e41ab1526d468e8bc979a079
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/type_library/bool.lean
8e7ffae47e6274cd77efdf6143d63555b5c3b0fc
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
938
lean
#check bnot namespace hidden /- The bool data type is a simple, two-valued (true/false) type. A set of operations is defined on values of this type comprising Boolean algebra. EXERCISE: Complete this file as instructed below. -/ inductive bool : Type | tt | ff /- Note: The identifiers ff and tt without qualification will refer to Lean's built-in definitions of these terms. Use bool.ff and bool.tt throughout this file, to be sure you're picking up *our* definition of bool, not Lean's. -/ def bnot : bool → bool | bool.tt := bool.ff -- 0 | bool.ff := bool.tt -- 1 def band : bool → bool → bool | bool.tt .tt := bool.tt | _ _ := bool.ff /- EXERCISE: Implement the following binary boolean operators. Use the following names for the functions with the give descriptions. bor -- or / disjunction bxor -- exclusive or bimp -- implies biff -- iff / equivalent bnand -- not and bnor -- not or -/ end hidden
560f3ca63e239f7b461bf48cef625b262ffd1947
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/Meta/Basic.lean
3d0d54ce1aa4a2ffd029dd2bf0d353a53724b5b8
[ "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
45,125
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.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck structure Config := (foApprox : Bool := false) (ctxApprox : Bool := false) (quasiPatternApprox : Bool := false) /- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ (constApprox : Bool := false) /- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ (isDefEqStuckEx : Bool := false) (transparency : TransparencyMode := TransparencyMode.default) /- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ (zetaNonDep : Bool := true) /- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ (trackZeta : Bool := false) structure ParamInfo := (implicit : Bool := false) (instImplicit : Bool := false) (hasFwdDeps : Bool := false) (backDeps : Array Nat := #[]) instance : Inhabited ParamInfo := ⟨{}⟩ def ParamInfo.isExplicit (p : ParamInfo) : Bool := !p.implicit && p.instImplicit structure FunInfo := (paramInfo : Array ParamInfo := #[]) (resultDeps : Array Nat := #[]) structure InfoCacheKey := (transparency : TransparencyMode) (expr : Expr) (nargs? : Option Nat) namespace InfoCacheKey instance : Inhabited InfoCacheKey := ⟨⟨arbitrary, arbitrary, arbitrary⟩⟩ instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩ instance : BEq InfoCacheKey := ⟨fun ⟨t₁, e₁, n₁⟩ ⟨t₂, e₂, n₂⟩ => t₁ == t₂ && n₁ == n₂ && e₁ == e₂⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) structure Cache := (inferType : PersistentExprStructMap Expr := {}) (funInfo : PersistentHashMap InfoCacheKey FunInfo := {}) (synthInstance : SynthInstanceCache := {}) (whnfDefault : PersistentExprStructMap Expr := {}) -- cache for closed terms and `TransparencyMode.default` (whnfAll : PersistentExprStructMap Expr := {}) -- cache for closed terms and `TransparencyMode.all` structure PostponedEntry := (lhs : Level) (rhs : Level) structure State := (mctx : MetavarContext := {}) (cache : Cache := {}) /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ (zetaFVarIds : NameSet := {}) (postponed : PersistentArray PostponedEntry := {}) instance : Inhabited State := ⟨{}⟩ structure Context := (config : Config := {}) (lctx : LocalContext := {}) (localInstances : LocalInstances := #[]) abbrev MetaM := ReaderT Context $ StateRefT State CoreM instance : Inhabited (MetaM α) := { default := fun _ _ => arbitrary } instance : MonadLCtx MetaM := { getLCtx := do pure (← read).lctx } instance : MonadMCtx MetaM := { getMCtx := do pure (← get).mctx, modifyMCtx := fun f => modify fun s => { s with mctx := f s.mctx } } instance : AddMessageContext MetaM := { addMessageContext := addMessageContextFull } @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck {α} : MetaM α := throw $ Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f $ runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase $ k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase $ k b c section Methods variables {m : Type → Type} [MonadLiftT MetaM m] variables {n : Type → Type} [MonadControlT MetaM n] [Monad n] def getLocalInstances : m LocalInstances := liftMetaM do pure (← read).localInstances def getConfig : m Config := liftMetaM do pure (← read).config def setMCtx (mctx : MetavarContext) : m Unit := liftMetaM $ modify fun s => { s with mctx := mctx } def resetZetaFVarIds : m Unit := liftMetaM $ modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : m NameSet := liftMetaM do pure (← get).zetaFVarIds def getPostponed : m (PersistentArray PostponedEntry) := liftMetaM do pure (← get).postponed def setPostponed (postponed : PersistentArray PostponedEntry) : m Unit := liftMetaM $ modify fun s => { s with postponed := postponed } @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : m Unit := liftMetaM $ modify fun s => { s with postponed := f s.postponed } builtin_initialize whnfRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "whnf implementation was not set" builtin_initialize inferTypeRef : IO.Ref (Expr → MetaM Expr) ← IO.mkRef fun _ => throwError "inferType implementation was not set" builtin_initialize isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) ← IO.mkRef fun _ _ => throwError "isDefEq implementation was not set" builtin_initialize synthPendingRef : IO.Ref (MVarId → MetaM Bool) ← IO.mkRef fun _ => pure false def whnf (e : Expr) : m Expr := liftMetaM $ withIncRecDepth do (← whnfRef.get) e def whnfForall [Monad m] (e : Expr) : m Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e def inferType (e : Expr) : m Expr := liftMetaM $ withIncRecDepth do (← inferTypeRef.get) e protected def isExprDefEqAux (t s : Expr) : MetaM Bool := withIncRecDepth do (← isExprDefEqAuxRef.get) t s protected def synthPending (mvarId : MVarId) : MetaM Bool := withIncRecDepth do (← synthPendingRef.get) mvarId -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth {α} (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; pure $ mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : m Expr := liftMetaM do let mvarId ← mkFreshId mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : m Level := liftMetaM do let mvarId ← mkFreshId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; pure $ mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAt lctx localInsts type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : m Expr := liftMetaM $ mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : m Expr := liftMetaM do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : m Expr := liftMetaM do let lctx ← getLCtx let localInsts ← getLocalInstances mkFreshExprMVarAtCore mvarId lctx localInsts type kind userName numScopeArgs def mkFreshExprMVarWithIdImpl (mvarId : MVarId) (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : m Expr := liftMetaM $ mkFreshExprMVarWithIdImpl mvarId type? kind userName def shouldReduceAll : MetaM Bool := liftMetaM do return (← read).config.transparency == TransparencyMode.all def shouldReduceReducibleOnly : m Bool := liftMetaM do return (← read).config.transparency == TransparencyMode.reducible def getTransparency : m TransparencyMode := liftMetaM do return (← read).config.transparency def getMVarDecl (mvarId : MVarId) : m MetavarDecl := liftMetaM do let mctx ← getMCtx match mctx.findDecl? mvarId with | some d => pure d | none => throwError! "unknown metavariable '{mkMVar mvarId}'" def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : m Unit := liftMetaM do modifyMCtx fun mctx => mctx.setMVarKind mvarId kind /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mvarId : MVarId) (type : Expr) : m Unit := liftMetaM do modifyMCtx fun mctx => mctx.setMVarType mvarId type def isReadOnlyExprMVar (mvarId : MVarId) : m Bool := liftMetaM do let mvarDecl ← getMVarDecl mvarId let mctx ← getMCtx pure $ mvarDecl.depth != mctx.depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : m Bool := liftMetaM do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => pure true | _ => do let mctx ← getMCtx pure $ mvarDecl.depth != mctx.depth def isReadOnlyLevelMVar (mvarId : MVarId) : m Bool := liftMetaM do let mctx ← getMCtx match mctx.findLevelDepth? mvarId with | some depth => pure $ depth != mctx.depth | _ => throwError! "unknown universe metavariable '{mkLevelMVar mvarId}'" def renameMVar (mvarId : MVarId) (newUserName : Name) : m Unit := liftMetaM do modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName def isExprMVarAssigned (mvarId : MVarId) : m Bool := liftMetaM do let mctx ← getMCtx pure $ mctx.isExprAssigned mvarId def getExprMVarAssignment? (mvarId : MVarId) : m (Option Expr) := liftMetaM do let mctx ← getMCtx pure (mctx.getExprAssignment? mvarId) def assignExprMVar (mvarId : MVarId) (val : Expr) : m Unit := liftMetaM do modifyMCtx fun mctx => mctx.assignExpr mvarId val def isDelayedAssigned (mvarId : MVarId) : m Bool := liftMetaM do return (← getMCtx).isDelayedAssigned mvarId def getDelayedAssignment? (mvarId : MVarId) : m (Option DelayedMetavarAssignment) := liftMetaM do return (← getMCtx).getDelayedAssignment? mvarId def hasAssignableMVar (e : Expr) : m Bool := liftMetaM do return (← getMCtx).hasAssignableMVar e def throwUnknownFVar {α} (fvarId : FVarId) : MetaM α := throwError! "unknown free variable '{mkFVar fvarId}'" def findLocalDecl? (fvarId : FVarId) : m (Option LocalDecl) := liftMetaM do return (← getLCtx).find? fvarId def getLocalDecl (fvarId : FVarId) : m LocalDecl := liftMetaM do match (← getLCtx).find? fvarId with | some d => pure d | none => throwUnknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : m LocalDecl := liftMetaM do getLocalDecl fvar.fvarId! def getLocalDeclFromUserName (userName : Name) : m LocalDecl := liftMetaM do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError! "unknown local declaration '{userName}'" def instantiateLevelMVarsImp (u : Level) : MetaM Level := MetavarContext.instantiateLevelMVars u def instantiateLevelMVars (u : Level) : m Level := liftMetaM do instantiateLevelMVarsImp u def instantiateMVarsImp (e : Expr) : MetaM Expr := (MetavarContext.instantiateExprMVars e).run def instantiateMVars (e : Expr) : m Expr := liftMetaM do instantiateMVarsImp e def instantiateLocalDeclMVars (localDecl : LocalDecl) : m LocalDecl := liftMetaM do match localDecl with | LocalDecl.cdecl idx id n type bi => let type ← instantiateMVars type pure $ LocalDecl.cdecl idx id n type bi | LocalDecl.ldecl idx id n type val nonDep => let type ← instantiateMVars type let val ← instantiateMVars val pure $ LocalDecl.ldecl idx id n type val nonDep @[inline] private def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := do match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with | EStateM.Result.ok e newS => do setNGen newS.ngen; setMCtx newS.mctx; pure e | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do setMCtx newS.mctx; setNGen newS.ngen; throwError "failed to create binder due to failure when reverting variable dependencies" def mkForallFVarsImp (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e def mkForallFVars (xs : Array Expr) (e : Expr) : m Expr := liftMetaM do mkForallFVarsImp xs e def mkLambdaFVarsImp (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e def mkLambdaFVars (xs : Array Expr) (e : Expr) : m Expr := liftMetaM do mkLambdaFVarsImp xs e def mkLetFVars (xs : Array Expr) (e : Expr) : m Expr := mkLambdaFVars xs e def mkArrow (d b : Expr) : m Expr := liftMetaM do let n ← mkFreshUserName `x return Lean.mkForall n BinderInfo.default d b def mkForallUsedOnlyImp (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) := do if xs.isEmpty then pure (e, 0) else liftMkBindingM <| MetavarContext.mkForallUsedOnly xs e def mkForallUsedOnly (xs : Array Expr) (e : Expr) : m (Expr × Nat) := liftMetaM do mkForallUsedOnlyImp xs e def elimMVarDepsImp (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : m Expr := liftMetaM do elimMVarDepsImp xs e preserveOrder @[inline] def withConfig {α} (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta {α} (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withTransparency {α} (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) @[inline] def withReducible {α} (x : n α) : n α := withTransparency TransparencyMode.reducible x @[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x def getConst? (constName : Name) : MetaM (Option ConstantInfo) := do let env ← getEnv match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => if (← shouldReduceAll) then pure (some info) else pure none | some (info@(ConstantInfo.defnInfo _)) => if (← shouldReduceReducibleOnly) then if (← isReducible constName) then pure (some info) else pure none else pure (some info) | some info => pure (some info) | none => throwUnknownConstant constName def getConstNoEx? (constName : Name) : MetaM (Option ConstantInfo) := do let env ← getEnv match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => if (← shouldReduceAll) then pure (some info) else pure none | some (info@(ConstantInfo.defnInfo _)) => if (← shouldReduceReducibleOnly) then if (← isReducible constName) then pure (some info) else pure none else pure (some info) | some info => pure (some info) | none => pure none /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl {α} (x : MetaM α) : MetaM α := do let s ← get let savedCache := s.cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache {α} : n α → n α := mapMetaM savingCacheImpl private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do let env ← getEnv if isClass env constName then pure (LOption.some constName) else match (← getConst? constName) with | some _ => pure LOption.undef | none => pure LOption.none private partial def isClassQuick? : Expr → MetaM (LOption Name) | Expr.bvar .. => pure LOption.none | Expr.lit .. => pure LOption.none | Expr.fvar .. => pure LOption.none | Expr.sort .. => pure LOption.none | Expr.lam .. => pure LOption.none | Expr.letE .. => pure LOption.undef | Expr.proj .. => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick? b | Expr.mdata _ e _ => isClassQuick? e | Expr.const n _ _ => isClassQuickConst? n | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n .. => isClassQuickConst? n | Expr.lam .. => pure LOption.undef | _ => pure LOption.none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let s ← get let savedSythInstance := s.cache.synthInstance modify fun s => { s with cache := { s.cache with synthInstance := {} } } pure savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modify fun s => { s with cache := { s.cache with synthInstance := cache } } @[inline] private def resettingSynthInstanceCacheImpl {α} (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache {α} : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | BinderInfo.auxDecl => k | _ => resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance {α} (className : Name) (fvar : Expr) : n α → n α := mapMetaM $ withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp {α} (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k | LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux {α} (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.forallE n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => withReducible $ -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun xs type => do match type.getAppFn with | Expr.const c _ _ => do let env ← getEnv pure $ if isClass env c then some c else none | _ => pure none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end private def withNewLocalInstancesImpAux {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM $ withNewLocalInstancesImp fvars j partial def withNewLocalInstances {α} (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM $ withNewLocalInstancesImpAux fvars j def isClass? (type : Expr) : m (Option Name) := liftMetaM do try isClassImp? type catch _ => pure none @[inline] private def forallTelescopeImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k /-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/ private partial def lambdaTelescopeAux {α} (k : Array Expr → Expr → MetaM α) : Bool → LocalContext → Array Expr → Nat → Expr → MetaM α | consumeLet, lctx, fvars, j, Expr.lam n d b c => do let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId lambdaTelescopeAux k consumeLet lctx (fvars.push fvar) j b | true, lctx, fvars, j, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId lambdaTelescopeAux k true lctx (fvars.push fvar) j b | _, lctx, fvars, j, e => let e := e.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e private partial def lambdaTelescopeImp {α} (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e process consumeLet (← getLCtx) #[] 0 e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type true k) k /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaTelescope {α} (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type false k) k def getParamNamesImp (declName : Name) : MetaM (Array Name) := do let cinfo ← getConstInfo declName forallTelescopeReducing cinfo.type fun xs _ => do xs.mapM fun x => do let localDecl ← getLocalDecl x.fvarId! pure localDecl.userName /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : m (Array Name) := liftMetaM $ getParamNamesImp declName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do match type with | Expr.forallE n d b c => let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let d := d.instantiateRevRange j mvars.size mvars let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else pure (mvars, bis, type) else pure (mvars, bis, type) process #[] #[] 0 e /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : m (Array Expr × Array BinderInfo × Expr) := liftMetaM $ forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : m (Array Expr × Array BinderInfo × Expr) := liftMetaM $ forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ private partial def lambdaMetaTelescopeImp (e : Expr) (maxMVars? : Option Nat) : MetaM (Array Expr × Array BinderInfo × Expr) := let rec process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars pure (mvars, bis, type) let cont : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do match type with | Expr.lam n d b c => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => finalize () match maxMVars? with | none => cont () | some maxMVars => if mvars.size < maxMVars then cont () else finalize () process #[] #[] 0 e /-- Similar to `forallMetaTelescope` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : m (Array Expr × Array BinderInfo × Expr) := liftMetaM $ lambdaMetaTelescopeImp e maxMVars? private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar $ k fvar private def withLocalDeclImp {α} (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLocalDecl {α} (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD {α} (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k private def withLetDeclImp {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLetDecl {α} (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k private def withExistingLocalDeclsImp {α} (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let numLocalInstances := ctx.localInstances.size let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do let newLocalInsts ← decls.foldlM (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do { match (← isClass? decl.type) with | none => pure newlocalInsts | some c => pure $ newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _)) ctx.localInstances; if newLocalInsts.size == numLocalInstances then k else resettingSynthInstanceCache $ withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k def withExistingLocalDecls {α} (decls : List LocalDecl) : n α → n α := mapMetaM $ withExistingLocalDeclsImp decls private def withNewMCtxDepthImp {α} (x : MetaM α) : MetaM α := do let s ← get let savedMCtx := s.mctx modifyMCtx fun mctx => mctx.incDepth try x finally setMCtx savedMCtx /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ def withNewMCtxDepth {α} : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM $ withLocalContextImp lctx localInsts private def withMVarContextImp {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← getMVarDecl mvarId withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) : n α → n α := mapMetaM $ withMVarContextImp mvarId private def withMCtxImp {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' def withMCtx {α} (mctx : MetavarContext) : n α → n α := mapMetaM $ withMCtxImp mctx @[inline] private def approxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq {α} : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp {α} (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq {α} : n α → n α := mapMetaM fullApproxDefEqImp def normalizeLevel (u : Level) : m Level := liftMetaM do let u ← instantiateLevelMVars u; pure u.normalize def assignLevelMVar (mvarId : MVarId) (u : Level) : m Unit := liftMetaM do modifyMCtx fun mctx => mctx.assignLevel mvarId u def whnfD [MonadLiftT MetaM n] (e : Expr) : n Expr := withTransparency TransparencyMode.default $ whnf e def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): m Unit := liftMetaM do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | Except.ok env => setEnv env | Except.error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else pure e /- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : m Expr := liftMetaM $ instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ let e ← whnf e match e with | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else pure e /- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : m Expr := liftMetaM $ instantiateLambdaAux ps 0 e /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn (e : Expr) (fvarId : FVarId) : m Bool := liftMetaM do let mctx ← getMCtx pure $ mctx.exprDependsOn e fvarId def ppExprImp (e : Expr) : MetaM Format := do let env ← getEnv let mctx ← getMCtx let lctx ← getLCtx let opts ← getOptions let ctxCore ← readThe Core.Context Lean.ppExpr { env := env, mctx := mctx, lctx := lctx, opts := opts, currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e def ppExpr (e : Expr) : m Format := liftMetaM $ ppExprImp e @[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch _ => setEnv env; setMCtx mctx; y instance {α} : OrElse (MetaM α) := ⟨Meta.orelse⟩ @[inline] private def orelseMergeErrorsImp {α} (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw $ Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors {α m} [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp {α} (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw $ Exception.error ref $ f msg | ex => throw ex @[inline] def mapError {α m} [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- `commitWhenSome? x` executes `x` and keep modifications when it returns `some a`. -/ @[specialize] def commitWhenSome? {α} (x? : MetaM (Option α)) : MetaM (Option α) := do let env ← getEnv let mctx ← getMCtx try match (← x?) with | some a => pure (some a) | none => setEnv env setMCtx mctx pure none catch ex => setEnv env setMCtx mctx throw ex end Methods end Meta export Meta (MetaM) end Lean
7c9b1364e629d64799d5c8d2ea1aab0d90583410
23c79f5a2b724d0a6865a697f74bc337c40a1c17
/verified-counting/src/list_lemma.lean
dc60003d1167b2d9458ed97195e6f5e43f984b29
[]
no_license
mukeshtiwari/Puzzles
145e679e637d1c36363c90863cba7c0fda0190b1
4a760e7dc6c65cab0fde86d0296d863c62fdda29
refs/heads/master
1,608,024,738,873
1,607,504,305,000
1,607,504,305,000
5,691,003
0
0
null
null
null
null
UTF-8
Lean
false
false
691
lean
import tactic.find tactic.omega data.vector tactic.basic lemma zip_with_len_l {α β γ : Type*} {l₁ : list α} {l₂ : list β} {f : α → β → γ} (h : list.length l₁ = list.length l₂) : list.length (list.zip_with f l₁ l₂) = list.length l₁ := begin induction l₁ with x xs ih generalizing l₂, {simp [list.zip_with]}, { cases l₂ with y ys, {injection h}, {simp only [list.zip_with, list.length], finish} } end lemma map_with_len_l {α β : Type*} {l₁ : list α} {f : α → β} : list.length (list.map f l₁) = list.length l₁ := begin induction l₁ with x xs ih, {simp [list.map]}, {simp [list.map]}, end
af8e44c2de52e8703e79f87106dec2097bef66b1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/hom/lattice.lean
033a64c543d1556d2c70beb05078c4cd5c0b1c36
[ "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
42,781
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.lattice import order.hom.bounded import order.symm_diff /-! # Lattice homomorphisms This file defines (bounded) lattice homomorphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `sup_hom`: Maps which preserve `⊔`. * `inf_hom`: Maps which preserve `⊓`. * `sup_bot_hom`: Finitary supremum homomorphisms. Maps which preserve `⊔` and `⊥`. * `inf_top_hom`: Finitary infimum homomorphisms. Maps which preserve `⊓` and `⊤`. * `lattice_hom`: Lattice homomorphisms. Maps which preserve `⊔` and `⊓`. * `bounded_lattice_hom`: Bounded lattice homomorphisms. Maps which preserve `⊤`, `⊥`, `⊔` and `⊓`. ## Typeclasses * `sup_hom_class` * `inf_hom_class` * `sup_bot_hom_class` * `inf_top_hom_class` * `lattice_hom_class` * `bounded_lattice_hom_class` ## TODO Do we need more intersections between `bot_hom`, `top_hom` and lattice homomorphisms? -/ open function order_dual variables {F ι α β γ δ : Type*} /-- The type of `⊔`-preserving functions from `α` to `β`. -/ structure sup_hom (α β : Type*) [has_sup α] [has_sup β] := (to_fun : α → β) (map_sup' (a b : α) : to_fun (a ⊔ b) = to_fun a ⊔ to_fun b) /-- The type of `⊓`-preserving functions from `α` to `β`. -/ structure inf_hom (α β : Type*) [has_inf α] [has_inf β] := (to_fun : α → β) (map_inf' (a b : α) : to_fun (a ⊓ b) = to_fun a ⊓ to_fun b) /-- The type of finitary supremum-preserving homomorphisms from `α` to `β`. -/ structure sup_bot_hom (α β : Type*) [has_sup α] [has_sup β] [has_bot α] [has_bot β] extends sup_hom α β := (map_bot' : to_fun ⊥ = ⊥) /-- The type of finitary infimum-preserving homomorphisms from `α` to `β`. -/ structure inf_top_hom (α β : Type*) [has_inf α] [has_inf β] [has_top α] [has_top β] extends inf_hom α β := (map_top' : to_fun ⊤ = ⊤) /-- The type of lattice homomorphisms from `α` to `β`. -/ structure lattice_hom (α β : Type*) [lattice α] [lattice β] extends sup_hom α β := (map_inf' (a b : α) : to_fun (a ⊓ b) = to_fun a ⊓ to_fun b) /-- The type of bounded lattice homomorphisms from `α` to `β`. -/ structure bounded_lattice_hom (α β : Type*) [lattice α] [lattice β] [bounded_order α] [bounded_order β] extends lattice_hom α β := (map_top' : to_fun ⊤ = ⊤) (map_bot' : to_fun ⊥ = ⊥) section set_option old_structure_cmd true /-- `sup_hom_class F α β` states that `F` is a type of `⊔`-preserving morphisms. You should extend this class when you extend `sup_hom`. -/ class sup_hom_class (F : Type*) (α β : out_param $ Type*) [has_sup α] [has_sup β] extends fun_like F α (λ _, β) := (map_sup (f : F) (a b : α) : f (a ⊔ b) = f a ⊔ f b) /-- `inf_hom_class F α β` states that `F` is a type of `⊓`-preserving morphisms. You should extend this class when you extend `inf_hom`. -/ class inf_hom_class (F : Type*) (α β : out_param $ Type*) [has_inf α] [has_inf β] extends fun_like F α (λ _, β) := (map_inf (f : F) (a b : α) : f (a ⊓ b) = f a ⊓ f b) /-- `sup_bot_hom_class F α β` states that `F` is a type of finitary supremum-preserving morphisms. You should extend this class when you extend `sup_bot_hom`. -/ class sup_bot_hom_class (F : Type*) (α β : out_param $ Type*) [has_sup α] [has_sup β] [has_bot α] [has_bot β] extends sup_hom_class F α β := (map_bot (f : F) : f ⊥ = ⊥) /-- `inf_top_hom_class F α β` states that `F` is a type of finitary infimum-preserving morphisms. You should extend this class when you extend `sup_bot_hom`. -/ class inf_top_hom_class (F : Type*) (α β : out_param $ Type*) [has_inf α] [has_inf β] [has_top α] [has_top β] extends inf_hom_class F α β := (map_top (f : F) : f ⊤ = ⊤) /-- `lattice_hom_class F α β` states that `F` is a type of lattice morphisms. You should extend this class when you extend `lattice_hom`. -/ class lattice_hom_class (F : Type*) (α β : out_param $ Type*) [lattice α] [lattice β] extends sup_hom_class F α β := (map_inf (f : F) (a b : α) : f (a ⊓ b) = f a ⊓ f b) /-- `bounded_lattice_hom_class F α β` states that `F` is a type of bounded lattice morphisms. You should extend this class when you extend `bounded_lattice_hom`. -/ class bounded_lattice_hom_class (F : Type*) (α β : out_param $ Type*) [lattice α] [lattice β] [bounded_order α] [bounded_order β] extends lattice_hom_class F α β := (map_top (f : F) : f ⊤ = ⊤) (map_bot (f : F) : f ⊥ = ⊥) end export sup_hom_class (map_sup) export inf_hom_class (map_inf) attribute [simp] map_top map_bot map_sup map_inf @[priority 100] -- See note [lower instance priority] instance sup_hom_class.to_order_hom_class [semilattice_sup α] [semilattice_sup β] [sup_hom_class F α β] : order_hom_class F α β := { map_rel := λ f a b h, by rw [←sup_eq_right, ←map_sup, sup_eq_right.2 h], ..‹sup_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance inf_hom_class.to_order_hom_class [semilattice_inf α] [semilattice_inf β] [inf_hom_class F α β] : order_hom_class F α β := { map_rel := λ f a b h, by rw [←inf_eq_left, ←map_inf, inf_eq_left.2 h] ..‹inf_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance sup_bot_hom_class.to_bot_hom_class [has_sup α] [has_sup β] [has_bot α] [has_bot β] [sup_bot_hom_class F α β] : bot_hom_class F α β := { .. ‹sup_bot_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance inf_top_hom_class.to_top_hom_class [has_inf α] [has_inf β] [has_top α] [has_top β] [inf_top_hom_class F α β] : top_hom_class F α β := { .. ‹inf_top_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance lattice_hom_class.to_inf_hom_class [lattice α] [lattice β] [lattice_hom_class F α β] : inf_hom_class F α β := { .. ‹lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_sup_bot_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : sup_bot_hom_class F α β := { .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_inf_top_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : inf_top_hom_class F α β := { .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_lattice_hom_class.to_bounded_order_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : bounded_order_hom_class F α β := { .. show order_hom_class F α β, from infer_instance, .. ‹bounded_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_sup_hom_class [semilattice_sup α] [semilattice_sup β] [order_iso_class F α β] : sup_hom_class F α β := { map_sup := λ f a b, eq_of_forall_ge_iff $ λ c, by simp only [←le_map_inv_iff, sup_le_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_inf_hom_class [semilattice_inf α] [semilattice_inf β] [order_iso_class F α β] : inf_hom_class F α β := { map_inf := λ f a b, eq_of_forall_le_iff $ λ c, by simp only [←map_inv_le_iff, le_inf_iff], .. show order_hom_class F α β, from infer_instance } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_sup_bot_hom_class [semilattice_sup α] [order_bot α] [semilattice_sup β] [order_bot β] [order_iso_class F α β] : sup_bot_hom_class F α β := { ..order_iso_class.to_sup_hom_class, ..order_iso_class.to_bot_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_inf_top_hom_class [semilattice_inf α] [order_top α] [semilattice_inf β] [order_top β] [order_iso_class F α β] : inf_top_hom_class F α β := { ..order_iso_class.to_inf_hom_class, ..order_iso_class.to_top_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_lattice_hom_class [lattice α] [lattice β] [order_iso_class F α β] : lattice_hom_class F α β := { ..order_iso_class.to_sup_hom_class, ..order_iso_class.to_inf_hom_class } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_bounded_lattice_hom_class [lattice α] [lattice β] [bounded_order α] [bounded_order β] [order_iso_class F α β] : bounded_lattice_hom_class F α β := { ..order_iso_class.to_lattice_hom_class, ..order_iso_class.to_bounded_order_hom_class } @[simp] lemma map_finset_sup [semilattice_sup α] [order_bot α] [semilattice_sup β] [order_bot β] [sup_bot_hom_class F α β] (f : F) (s : finset ι) (g : ι → α) : f (s.sup g) = s.sup (f ∘ g) := finset.cons_induction_on s (map_bot f) $ λ i s _ h, by rw [finset.sup_cons, finset.sup_cons, map_sup, h] @[simp] lemma map_finset_inf [semilattice_inf α] [order_top α] [semilattice_inf β] [order_top β] [inf_top_hom_class F α β] (f : F) (s : finset ι) (g : ι → α) : f (s.inf g) = s.inf (f ∘ g) := finset.cons_induction_on s (map_top f) $ λ i s _ h, by rw [finset.inf_cons, finset.inf_cons, map_inf, h] section bounded_lattice variables [lattice α] [bounded_order α] [lattice β] [bounded_order β] [bounded_lattice_hom_class F α β] (f : F) {a b : α} include β lemma disjoint.map (h : disjoint a b) : disjoint (f a) (f b) := by rw [disjoint_iff, ←map_inf, h.eq_bot, map_bot] lemma codisjoint.map (h : codisjoint a b) : codisjoint (f a) (f b) := by rw [codisjoint_iff, ←map_sup, h.eq_top, map_top] lemma is_compl.map (h : is_compl a b) : is_compl (f a) (f b) := ⟨h.1.map _, h.2.map _⟩ end bounded_lattice section boolean_algebra variables [boolean_algebra α] [boolean_algebra β] [bounded_lattice_hom_class F α β] (f : F) include β /-- Special case of `map_compl` for boolean algebras. -/ lemma map_compl' (a : α) : f aᶜ = (f a)ᶜ := (is_compl_compl.map _).compl_eq.symm /-- Special case of `map_sdiff` for boolean algebras. -/ lemma map_sdiff' (a b : α) : f (a \ b) = f a \ f b := by rw [sdiff_eq, sdiff_eq, map_inf, map_compl'] /-- Special case of `map_symm_diff` for boolean algebras. -/ lemma map_symm_diff' (a b : α) : f (a ∆ b) = f a ∆ f b := by rw [symm_diff, symm_diff, map_sup, map_sdiff', map_sdiff'] end boolean_algebra instance [has_sup α] [has_sup β] [sup_hom_class F α β] : has_coe_t F (sup_hom α β) := ⟨λ f, ⟨f, map_sup f⟩⟩ instance [has_inf α] [has_inf β] [inf_hom_class F α β] : has_coe_t F (inf_hom α β) := ⟨λ f, ⟨f, map_inf f⟩⟩ instance [has_sup α] [has_sup β] [has_bot α] [has_bot β] [sup_bot_hom_class F α β] : has_coe_t F (sup_bot_hom α β) := ⟨λ f, ⟨f, map_bot f⟩⟩ instance [has_inf α] [has_inf β] [has_top α] [has_top β] [inf_top_hom_class F α β] : has_coe_t F (inf_top_hom α β) := ⟨λ f, ⟨f, map_top f⟩⟩ instance [lattice α] [lattice β] [lattice_hom_class F α β] : has_coe_t F (lattice_hom α β) := ⟨λ f, { to_fun := f, map_sup' := map_sup f, map_inf' := map_inf f }⟩ instance [lattice α] [lattice β] [bounded_order α] [bounded_order β] [bounded_lattice_hom_class F α β] : has_coe_t F (bounded_lattice_hom α β) := ⟨λ f, { to_fun := f, map_top' := map_top f, map_bot' := map_bot f, ..(f : lattice_hom α β) }⟩ /-! ### Supremum homomorphisms -/ namespace sup_hom variables [has_sup α] section has_sup variables [has_sup β] [has_sup γ] [has_sup δ] instance : sup_hom_class (sup_hom α β) α β := { coe := sup_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_sup := sup_hom.map_sup' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (sup_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : sup_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : sup_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `sup_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : sup_hom α β) (f' : α → β) (h : f' = f) : sup_hom α β := { to_fun := f', map_sup' := h.symm ▸ f.map_sup' } @[simp] lemma coe_copy (f : sup_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : sup_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `sup_hom`. -/ protected def id : sup_hom α α := ⟨id, λ a b, rfl⟩ instance : inhabited (sup_hom α α) := ⟨sup_hom.id α⟩ @[simp] lemma coe_id : ⇑(sup_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : sup_hom.id α a = a := rfl /-- Composition of `sup_hom`s as a `sup_hom`. -/ def comp (f : sup_hom β γ) (g : sup_hom α β) : sup_hom α γ := { to_fun := f ∘ g, map_sup' := λ a b, by rw [comp_apply, map_sup, map_sup] } @[simp] lemma coe_comp (f : sup_hom β γ) (g : sup_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : sup_hom β γ) (g : sup_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : sup_hom γ δ) (g : sup_hom β γ) (h : sup_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : sup_hom α β) : f.comp (sup_hom.id α) = f := sup_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : sup_hom α β) : (sup_hom.id β).comp f = f := sup_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : sup_hom β γ} {f : sup_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, sup_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : sup_hom β γ} {f₁ f₂ : sup_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, sup_hom.ext $ λ a, hg $ by rw [←sup_hom.comp_apply, h, sup_hom.comp_apply], congr_arg _⟩ end has_sup variables (α) [semilattice_sup β] /-- The constant function as a `sup_hom`. -/ def const (b : β) : sup_hom α β := ⟨λ _, b, λ _ _, sup_idem.symm⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl variables {α} instance : has_sup (sup_hom α β) := ⟨λ f g, ⟨f ⊔ g, λ a b, by { rw [pi.sup_apply, map_sup, map_sup], exact sup_sup_sup_comm _ _ _ _ }⟩⟩ instance : semilattice_sup (sup_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ f g, rfl instance [has_bot β] : has_bot (sup_hom α β) := ⟨sup_hom.const α ⊥⟩ instance [has_top β] : has_top (sup_hom α β) := ⟨sup_hom.const α ⊤⟩ instance [order_bot β] : order_bot (sup_hom α β) := order_bot.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [order_top β] : order_top (sup_hom α β) := order_top.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [bounded_order β] : bounded_order (sup_hom α β) := bounded_order.lift (coe_fn : _ → α → β) (λ _ _, id) rfl rfl @[simp] lemma coe_sup (f g : sup_hom α β) : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma coe_bot [has_bot β] : ⇑(⊥ : sup_hom α β) = ⊥ := rfl @[simp] lemma coe_top [has_top β] : ⇑(⊤ : sup_hom α β) = ⊤ := rfl @[simp] lemma sup_apply (f g : sup_hom α β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma bot_apply [has_bot β] (a : α) : (⊥ : sup_hom α β) a = ⊥ := rfl @[simp] lemma top_apply [has_top β] (a : α) : (⊤ : sup_hom α β) a = ⊤ := rfl end sup_hom /-! ### Infimum homomorphisms -/ namespace inf_hom variables [has_inf α] section has_inf variables [has_inf β] [has_inf γ] [has_inf δ] instance : inf_hom_class (inf_hom α β) α β := { coe := inf_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_inf := inf_hom.map_inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (inf_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : inf_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : inf_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of an `inf_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : inf_hom α β) (f' : α → β) (h : f' = f) : inf_hom α β := { to_fun := f', map_inf' := h.symm ▸ f.map_inf' } @[simp] lemma coe_copy (f : inf_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : inf_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as an `inf_hom`. -/ protected def id : inf_hom α α := ⟨id, λ a b, rfl⟩ instance : inhabited (inf_hom α α) := ⟨inf_hom.id α⟩ @[simp] lemma coe_id : ⇑(inf_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : inf_hom.id α a = a := rfl /-- Composition of `inf_hom`s as an `inf_hom`. -/ def comp (f : inf_hom β γ) (g : inf_hom α β) : inf_hom α γ := { to_fun := f ∘ g, map_inf' := λ a b, by rw [comp_apply, map_inf, map_inf] } @[simp] lemma coe_comp (f : inf_hom β γ) (g : inf_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : inf_hom β γ) (g : inf_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : inf_hom γ δ) (g : inf_hom β γ) (h : inf_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : inf_hom α β) : f.comp (inf_hom.id α) = f := inf_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : inf_hom α β) : (inf_hom.id β).comp f = f := inf_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : inf_hom β γ} {f : inf_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, inf_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : inf_hom β γ} {f₁ f₂ : inf_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, inf_hom.ext $ λ a, hg $ by rw [←inf_hom.comp_apply, h, inf_hom.comp_apply], congr_arg _⟩ end has_inf variables (α) [semilattice_inf β] /-- The constant function as an `inf_hom`. -/ def const (b : β) : inf_hom α β := ⟨λ _, b, λ _ _, inf_idem.symm⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl variables {α} instance : has_inf (inf_hom α β) := ⟨λ f g, ⟨f ⊓ g, λ a b, by { rw [pi.inf_apply, map_inf, map_inf], exact inf_inf_inf_comm _ _ _ _ }⟩⟩ instance : semilattice_inf (inf_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ f g, rfl instance [has_bot β] : has_bot (inf_hom α β) := ⟨inf_hom.const α ⊥⟩ instance [has_top β] : has_top (inf_hom α β) := ⟨inf_hom.const α ⊤⟩ instance [order_bot β] : order_bot (inf_hom α β) := order_bot.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [order_top β] : order_top (inf_hom α β) := order_top.lift (coe_fn : _ → α → β) (λ _ _, id) rfl instance [bounded_order β] : bounded_order (inf_hom α β) := bounded_order.lift (coe_fn : _ → α → β) (λ _ _, id) rfl rfl @[simp] lemma coe_inf (f g : inf_hom α β) : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma coe_bot [has_bot β] : ⇑(⊥ : inf_hom α β) = ⊥ := rfl @[simp] lemma coe_top [has_top β] : ⇑(⊤ : inf_hom α β) = ⊤ := rfl @[simp] lemma inf_apply (f g : inf_hom α β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma bot_apply [has_bot β] (a : α) : (⊥ : inf_hom α β) a = ⊥ := rfl @[simp] lemma top_apply [has_top β] (a : α) : (⊤ : inf_hom α β) a = ⊤ := rfl end inf_hom /-! ### Finitary supremum homomorphisms -/ namespace sup_bot_hom variables [has_sup α] [has_bot α] section has_sup variables [has_sup β] [has_bot β] [has_sup γ] [has_bot γ] [has_sup δ] [has_bot δ] /-- Reinterpret a `sup_bot_hom` as a `bot_hom`. -/ def to_bot_hom (f : sup_bot_hom α β) : bot_hom α β := { ..f } instance : sup_bot_hom_class (sup_bot_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_sup := λ f, f.map_sup', map_bot := λ f, f.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (sup_bot_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : sup_bot_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : sup_bot_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `sup_bot_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : sup_bot_hom α β) (f' : α → β) (h : f' = f) : sup_bot_hom α β := { to_sup_hom := f.to_sup_hom.copy f' h, ..f.to_bot_hom.copy f' h } @[simp] lemma coe_copy (f : sup_bot_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : sup_bot_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `sup_bot_hom`. -/ @[simps] protected def id : sup_bot_hom α α := ⟨sup_hom.id α, rfl⟩ instance : inhabited (sup_bot_hom α α) := ⟨sup_bot_hom.id α⟩ @[simp] lemma coe_id : ⇑(sup_bot_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : sup_bot_hom.id α a = a := rfl /-- Composition of `sup_bot_hom`s as a `sup_bot_hom`. -/ def comp (f : sup_bot_hom β γ) (g : sup_bot_hom α β) : sup_bot_hom α γ := { ..f.to_sup_hom.comp g.to_sup_hom, ..f.to_bot_hom.comp g.to_bot_hom } @[simp] lemma coe_comp (f : sup_bot_hom β γ) (g : sup_bot_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : sup_bot_hom β γ) (g : sup_bot_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : sup_bot_hom γ δ) (g : sup_bot_hom β γ) (h : sup_bot_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : sup_bot_hom α β) : f.comp (sup_bot_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : sup_bot_hom α β) : (sup_bot_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : sup_bot_hom β γ} {f : sup_bot_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : sup_bot_hom β γ} {f₁ f₂ : sup_bot_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, sup_bot_hom.ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_sup variables [semilattice_sup β] [order_bot β] instance : has_sup (sup_bot_hom α β) := ⟨λ f g, { to_sup_hom := f.to_sup_hom ⊔ g.to_sup_hom, ..f.to_bot_hom ⊔ g.to_bot_hom }⟩ instance : semilattice_sup (sup_bot_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ f g, rfl instance : order_bot (sup_bot_hom α β) := { bot := ⟨⊥, rfl⟩, bot_le := λ f, bot_le } @[simp] lemma coe_sup (f g : sup_bot_hom α β) : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma coe_bot : ⇑(⊥ : sup_bot_hom α β) = ⊥ := rfl @[simp] lemma sup_apply (f g : sup_bot_hom α β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma bot_apply (a : α) : (⊥ : sup_bot_hom α β) a = ⊥ := rfl end sup_bot_hom /-! ### Finitary infimum homomorphisms -/ namespace inf_top_hom variables [has_inf α] [has_top α] section has_inf variables [has_inf β] [has_top β] [has_inf γ] [has_top γ] [has_inf δ] [has_top δ] /-- Reinterpret an `inf_top_hom` as a `top_hom`. -/ def to_top_hom (f : inf_top_hom α β) : top_hom α β := { ..f } instance : inf_top_hom_class (inf_top_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_inf := λ f, f.map_inf', map_top := λ f, f.map_top' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (inf_top_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : inf_top_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : inf_top_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of an `inf_top_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : inf_top_hom α β) (f' : α → β) (h : f' = f) : inf_top_hom α β := { to_inf_hom := f.to_inf_hom.copy f' h, ..f.to_top_hom.copy f' h } @[simp] lemma coe_copy (f : inf_top_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : inf_top_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as an `inf_top_hom`. -/ @[simps] protected def id : inf_top_hom α α := ⟨inf_hom.id α, rfl⟩ instance : inhabited (inf_top_hom α α) := ⟨inf_top_hom.id α⟩ @[simp] lemma coe_id : ⇑(inf_top_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : inf_top_hom.id α a = a := rfl /-- Composition of `inf_top_hom`s as an `inf_top_hom`. -/ def comp (f : inf_top_hom β γ) (g : inf_top_hom α β) : inf_top_hom α γ := { ..f.to_inf_hom.comp g.to_inf_hom, ..f.to_top_hom.comp g.to_top_hom } @[simp] lemma coe_comp (f : inf_top_hom β γ) (g : inf_top_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : inf_top_hom β γ) (g : inf_top_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : inf_top_hom γ δ) (g : inf_top_hom β γ) (h : inf_top_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : inf_top_hom α β) : f.comp (inf_top_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : inf_top_hom α β) : (inf_top_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : inf_top_hom β γ} {f : inf_top_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : inf_top_hom β γ} {f₁ f₂ : inf_top_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, inf_top_hom.ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_inf variables [semilattice_inf β] [order_top β] instance : has_inf (inf_top_hom α β) := ⟨λ f g, { to_inf_hom := f.to_inf_hom ⊓ g.to_inf_hom, ..f.to_top_hom ⊓ g.to_top_hom }⟩ instance : semilattice_inf (inf_top_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ f g, rfl instance : order_top (inf_top_hom α β) := { top := ⟨⊤, rfl⟩, le_top := λ f, le_top } @[simp] lemma coe_inf (f g : inf_top_hom α β) : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma coe_top : ⇑(⊤ : inf_top_hom α β) = ⊤ := rfl @[simp] lemma inf_apply (f g : inf_top_hom α β) (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma top_apply (a : α) : (⊤ : inf_top_hom α β) a = ⊤ := rfl end inf_top_hom /-! ### Lattice homomorphisms -/ namespace lattice_hom variables [lattice α] [lattice β] [lattice γ] [lattice δ] /-- Reinterpret a `lattice_hom` as an `inf_hom`. -/ def to_inf_hom (f : lattice_hom α β) : inf_hom α β := { ..f } instance : lattice_hom_class (lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_sup := λ f, f.map_sup', map_inf := λ f, f.map_inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (lattice_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : lattice_hom α β) (f' : α → β) (h : f' = f) : lattice_hom α β := { .. f.to_sup_hom.copy f' h, .. f.to_inf_hom.copy f' h } @[simp] lemma coe_copy (f : lattice_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : lattice_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `lattice_hom`. -/ protected def id : lattice_hom α α := { to_fun := id, map_sup' := λ _ _, rfl, map_inf' := λ _ _, rfl } instance : inhabited (lattice_hom α α) := ⟨lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : lattice_hom.id α a = a := rfl /-- Composition of `lattice_hom`s as a `lattice_hom`. -/ def comp (f : lattice_hom β γ) (g : lattice_hom α β) : lattice_hom α γ := { ..f.to_sup_hom.comp g.to_sup_hom, ..f.to_inf_hom.comp g.to_inf_hom } @[simp] lemma coe_comp (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : lattice_hom β γ) (g : lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_sup_hom (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : sup_hom α γ) = (f : sup_hom β γ).comp g := rfl @[simp] lemma coe_comp_inf_hom (f : lattice_hom β γ) (g : lattice_hom α β) : (f.comp g : inf_hom α γ) = (f : inf_hom β γ).comp g := rfl @[simp] lemma comp_assoc (f : lattice_hom γ δ) (g : lattice_hom β γ) (h : lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : lattice_hom α β) : f.comp (lattice_hom.id α) = f := lattice_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : lattice_hom α β) : (lattice_hom.id β).comp f = f := lattice_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : lattice_hom β γ} {f : lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, lattice_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : lattice_hom β γ} {f₁ f₂ : lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, lattice_hom.ext $ λ a, hg $ by rw [←lattice_hom.comp_apply, h, lattice_hom.comp_apply], congr_arg _⟩ end lattice_hom namespace order_hom_class variables (α β) [linear_order α] [lattice β] [order_hom_class F α β] /-- An order homomorphism from a linear order is a lattice homomorphism. -/ @[reducible] def to_lattice_hom_class : lattice_hom_class F α β := { map_sup := λ f a b, begin obtain h | h := le_total a b, { rw [sup_eq_right.2 h, sup_eq_right.2 (order_hom_class.mono f h : f a ≤ f b)] }, { rw [sup_eq_left.2 h, sup_eq_left.2 (order_hom_class.mono f h : f b ≤ f a)] } end, map_inf := λ f a b, begin obtain h | h := le_total a b, { rw [inf_eq_left.2 h, inf_eq_left.2 (order_hom_class.mono f h : f a ≤ f b)] }, { rw [inf_eq_right.2 h, inf_eq_right.2 (order_hom_class.mono f h : f b ≤ f a)] } end, .. ‹order_hom_class F α β› } /-- Reinterpret an order homomorphism to a linear order as a `lattice_hom`. -/ def to_lattice_hom (f : F) : lattice_hom α β := by { haveI : lattice_hom_class F α β := order_hom_class.to_lattice_hom_class α β, exact f } @[simp] lemma coe_to_lattice_hom (f : F) : ⇑(to_lattice_hom α β f) = f := rfl @[simp] lemma to_lattice_hom_apply (f : F) (a : α) : to_lattice_hom α β f a = f a := rfl end order_hom_class /-! ### Bounded lattice homomorphisms -/ namespace bounded_lattice_hom variables [lattice α] [lattice β] [lattice γ] [lattice δ] [bounded_order α] [bounded_order β] [bounded_order γ] [bounded_order δ] /-- Reinterpret a `bounded_lattice_hom` as a `sup_bot_hom`. -/ def to_sup_bot_hom (f : bounded_lattice_hom α β) : sup_bot_hom α β := { ..f } /-- Reinterpret a `bounded_lattice_hom` as an `inf_top_hom`. -/ def to_inf_top_hom (f : bounded_lattice_hom α β) : inf_top_hom α β := { ..f } /-- Reinterpret a `bounded_lattice_hom` as a `bounded_order_hom`. -/ def to_bounded_order_hom (f : bounded_lattice_hom α β) : bounded_order_hom α β := { ..f, ..(f.to_lattice_hom : α →o β) } instance : bounded_lattice_hom_class (bounded_lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := f; obtain ⟨⟨⟨_, _⟩, _⟩, _⟩ := g; congr', map_sup := λ f, f.map_sup', map_inf := λ f, f.map_inf', map_top := λ f, f.map_top', map_bot := λ f, f.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (bounded_lattice_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : bounded_lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : bounded_lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `bounded_lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : bounded_lattice_hom α β) (f' : α → β) (h : f' = f) : bounded_lattice_hom α β := { .. f.to_lattice_hom.copy f' h, .. f.to_bounded_order_hom.copy f' h } @[simp] lemma coe_copy (f : bounded_lattice_hom α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : bounded_lattice_hom α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables (α) /-- `id` as a `bounded_lattice_hom`. -/ protected def id : bounded_lattice_hom α α := { ..lattice_hom.id α, ..bounded_order_hom.id α } instance : inhabited (bounded_lattice_hom α α) := ⟨bounded_lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(bounded_lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : bounded_lattice_hom.id α a = a := rfl /-- Composition of `bounded_lattice_hom`s as a `bounded_lattice_hom`. -/ def comp (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : bounded_lattice_hom α γ := { ..f.to_lattice_hom.comp g.to_lattice_hom, ..f.to_bounded_order_hom.comp g.to_bounded_order_hom } @[simp] lemma coe_comp (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_lattice_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : lattice_hom α γ) = (f : lattice_hom β γ).comp g := rfl @[simp] lemma coe_comp_sup_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : sup_hom α γ) = (f : sup_hom β γ).comp g := rfl @[simp] lemma coe_comp_inf_hom (f : bounded_lattice_hom β γ) (g : bounded_lattice_hom α β) : (f.comp g : inf_hom α γ) = (f : inf_hom β γ).comp g := rfl @[simp] lemma comp_assoc (f : bounded_lattice_hom γ δ) (g : bounded_lattice_hom β γ) (h : bounded_lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : bounded_lattice_hom α β) : f.comp (bounded_lattice_hom.id α) = f := bounded_lattice_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : bounded_lattice_hom α β) : (bounded_lattice_hom.id β).comp f = f := bounded_lattice_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : bounded_lattice_hom β γ} {f : bounded_lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, bounded_lattice_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : bounded_lattice_hom β γ} {f₁ f₂ : bounded_lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end bounded_lattice_hom /-! ### Dual homs -/ namespace sup_hom variables [has_sup α] [has_sup β] [has_sup γ] /-- Reinterpret a supremum homomorphism as an infimum homomorphism between the dual lattices. -/ @[simps] protected def dual : sup_hom α β ≃ inf_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_sup'⟩, inv_fun := λ f, ⟨f, f.map_inf'⟩, left_inv := λ f, sup_hom.ext $ λ _, rfl, right_inv := λ f, inf_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (sup_hom.id α).dual = inf_hom.id _ := rfl @[simp] lemma dual_comp (g : sup_hom β γ) (f : sup_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : sup_hom.dual.symm (inf_hom.id _) = sup_hom.id α := rfl @[simp] lemma symm_dual_comp (g : inf_hom βᵒᵈ γᵒᵈ) (f : inf_hom αᵒᵈ βᵒᵈ) : sup_hom.dual.symm (g.comp f) = (sup_hom.dual.symm g).comp (sup_hom.dual.symm f) := rfl end sup_hom namespace inf_hom variables [has_inf α] [has_inf β] [has_inf γ] /-- Reinterpret an infimum homomorphism as a supremum homomorphism between the dual lattices. -/ @[simps] protected def dual : inf_hom α β ≃ sup_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_inf'⟩, inv_fun := λ f, ⟨f, f.map_sup'⟩, left_inv := λ f, inf_hom.ext $ λ _, rfl, right_inv := λ f, sup_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (inf_hom.id α).dual = sup_hom.id _ := rfl @[simp] lemma dual_comp (g : inf_hom β γ) (f : inf_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : inf_hom.dual.symm (sup_hom.id _) = inf_hom.id α := rfl @[simp] lemma symm_dual_comp (g : sup_hom βᵒᵈ γᵒᵈ) (f : sup_hom αᵒᵈ βᵒᵈ) : inf_hom.dual.symm (g.comp f) = (inf_hom.dual.symm g).comp (inf_hom.dual.symm f) := rfl end inf_hom namespace sup_bot_hom variables [has_sup α] [has_bot α] [has_sup β] [has_bot β] [has_sup γ] [has_bot γ] /-- Reinterpret a finitary supremum homomorphism as a finitary infimum homomorphism between the dual lattices. -/ def dual : sup_bot_hom α β ≃ inf_top_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_sup_hom.dual, f.map_bot'⟩, inv_fun := λ f, ⟨sup_hom.dual.symm f.to_inf_hom, f.map_top'⟩, left_inv := λ f, sup_bot_hom.ext $ λ _, rfl, right_inv := λ f, inf_top_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (sup_bot_hom.id α).dual = inf_top_hom.id _ := rfl @[simp] lemma dual_comp (g : sup_bot_hom β γ) (f : sup_bot_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : sup_bot_hom.dual.symm (inf_top_hom.id _) = sup_bot_hom.id α := rfl @[simp] lemma symm_dual_comp (g : inf_top_hom βᵒᵈ γᵒᵈ) (f : inf_top_hom αᵒᵈ βᵒᵈ) : sup_bot_hom.dual.symm (g.comp f) = (sup_bot_hom.dual.symm g).comp (sup_bot_hom.dual.symm f) := rfl end sup_bot_hom namespace inf_top_hom variables [has_inf α] [has_top α] [has_inf β] [has_top β] [has_inf γ] [has_top γ] /-- Reinterpret a finitary infimum homomorphism as a finitary supremum homomorphism between the dual lattices. -/ @[simps] protected def dual : inf_top_hom α β ≃ sup_bot_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_inf_hom.dual, f.map_top'⟩, inv_fun := λ f, ⟨inf_hom.dual.symm f.to_sup_hom, f.map_bot'⟩, left_inv := λ f, inf_top_hom.ext $ λ _, rfl, right_inv := λ f, sup_bot_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (inf_top_hom.id α).dual = sup_bot_hom.id _ := rfl @[simp] lemma dual_comp (g : inf_top_hom β γ) (f : inf_top_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : inf_top_hom.dual.symm (sup_bot_hom.id _) = inf_top_hom.id α := rfl @[simp] lemma symm_dual_comp (g : sup_bot_hom βᵒᵈ γᵒᵈ) (f : sup_bot_hom αᵒᵈ βᵒᵈ) : inf_top_hom.dual.symm (g.comp f) = (inf_top_hom.dual.symm g).comp (inf_top_hom.dual.symm f) := rfl end inf_top_hom namespace lattice_hom variables [lattice α] [lattice β] [lattice γ] /-- Reinterpret a lattice homomorphism as a lattice homomorphism between the dual lattices. -/ @[simps] protected def dual : lattice_hom α β ≃ lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_inf_hom.dual, f.map_sup'⟩, inv_fun := λ f, ⟨f.to_inf_hom.dual, f.map_sup'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (lattice_hom.id α).dual = lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : lattice_hom β γ) (f : lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : lattice_hom.dual.symm (lattice_hom.id _) = lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : lattice_hom βᵒᵈ γᵒᵈ) (f : lattice_hom αᵒᵈ βᵒᵈ) : lattice_hom.dual.symm (g.comp f) = (lattice_hom.dual.symm g).comp (lattice_hom.dual.symm f) := rfl end lattice_hom namespace bounded_lattice_hom variables [lattice α] [bounded_order α] [lattice β] [bounded_order β] [lattice γ] [bounded_order γ] /-- Reinterpret a bounded lattice homomorphism as a bounded lattice homomorphism between the dual bounded lattices. -/ @[simps] protected def dual : bounded_lattice_hom α β ≃ bounded_lattice_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_lattice_hom.dual, f.map_bot', f.map_top'⟩, inv_fun := λ f, ⟨lattice_hom.dual.symm f.to_lattice_hom, f.map_bot', f.map_top'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (bounded_lattice_hom.id α).dual = bounded_lattice_hom.id _ := rfl @[simp] lemma dual_comp (g : bounded_lattice_hom β γ) (f : bounded_lattice_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : bounded_lattice_hom.dual.symm (bounded_lattice_hom.id _) = bounded_lattice_hom.id α := rfl @[simp] lemma symm_dual_comp (g : bounded_lattice_hom βᵒᵈ γᵒᵈ) (f : bounded_lattice_hom αᵒᵈ βᵒᵈ) : bounded_lattice_hom.dual.symm (g.comp f) = (bounded_lattice_hom.dual.symm g).comp (bounded_lattice_hom.dual.symm f) := rfl end bounded_lattice_hom
73042d04a45a68f821f599d92c152bd829ae7801
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/freudenthal.hlean
07329ef14e11449e90d95c11aedfa43c1775ccdd
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,702
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The Freudenthal Suspension Theorem -/ import homotopy.wedge homotopy.circle open eq is_conn is_trunc pointed susp nat pi equiv is_equiv trunc fiber trunc_index namespace freudenthal section parameters {A : Type*} {n : ℕ} [is_conn n A] /- This proof is ported from Agda This is the 95% version of the Freudenthal Suspension Theorem, which means that we don't prove that loop_psusp_unit : A →* Ω(psusp A) is 2n-connected (if A is n-connected), but instead we only prove that it induces an equivalence on the first 2n homotopy groups. -/ private definition up (a : A) : north = north :> susp A := loop_psusp_unit A a definition code_merid : A → ptrunc (n + n) A → ptrunc (n + n) A := begin have is_conn n (ptrunc (n + n) A), from !is_conn_trunc, refine @wedge_extension.ext _ _ n n _ _ (λ x y, ttrunc (n + n) A) _ _ _ _, { intros, apply is_trunc_trunc}, -- this subgoal might become unnecessary if -- type class inference catches it { exact tr}, { exact id}, { reflexivity} end definition code_merid_β_left (a : A) : code_merid a pt = tr a := by apply wedge_extension.β_left definition code_merid_β_right (b : ptrunc (n + n) A) : code_merid pt b = b := by apply wedge_extension.β_right definition code_merid_coh : code_merid_β_left pt = code_merid_β_right pt := begin symmetry, apply eq_of_inv_con_eq_idp, apply wedge_extension.coh end definition is_equiv_code_merid (a : A) : is_equiv (code_merid a) := begin have Πa, is_trunc n.-2.+1 (is_equiv (code_merid a)), from λa, is_trunc_of_le _ !minus_one_le_succ, refine is_conn.elim (n.-1) _ _ a, { esimp, exact homotopy_closed id (homotopy.symm (code_merid_β_right))} end definition code_merid_equiv [constructor] (a : A) : trunc (n + n) A ≃ trunc (n + n) A := equiv.mk _ (is_equiv_code_merid a) definition code_merid_inv_pt (x : trunc (n + n) A) : (code_merid_equiv pt)⁻¹ x = x := begin refine ap010 @(is_equiv.inv _) _ x ⬝ _, { exact homotopy_closed id (homotopy.symm code_merid_β_right)}, { apply is_conn.elim_β}, { reflexivity} end definition code [unfold 4] : susp A → Type := susp.elim_type (trunc (n + n) A) (trunc (n + n) A) code_merid_equiv definition is_trunc_code (x : susp A) : is_trunc (n + n) (code x) := begin induction x with a: esimp, { exact _}, { exact _}, { apply is_prop.elimo} end local attribute is_trunc_code [instance] definition decode_north [unfold 4] : code north → trunc (n + n) (north = north :> susp A) := trunc_functor (n + n) up definition decode_north_pt : decode_north (tr pt) = tr idp := ap tr !con.right_inv definition decode_south [unfold 4] : code south → trunc (n + n) (north = south :> susp A) := trunc_functor (n + n) merid definition encode' {x : susp A} (p : north = x) : code x := transport code p (tr pt) definition encode [unfold 5] {x : susp A} (p : trunc (n + n) (north = x)) : code x := begin induction p with p, exact transport code p (tr pt) end theorem encode_decode_north (c : code north) : encode (decode_north c) = c := begin have H : Πc, is_trunc (n + n) (encode (decode_north c) = c), from _, esimp at *, induction c with a, rewrite [↑[encode, decode_north, up, code], con_tr, elim_type_merid, ▸*, code_merid_β_left, elim_type_merid_inv, ▸*, code_merid_inv_pt] end definition decode_coh_f (a : A) : tr (up pt) =[merid a] decode_south (code_merid a (tr pt)) := begin refine _ ⬝op ap decode_south (code_merid_β_left a)⁻¹, apply trunc_pathover, apply eq_pathover_constant_left_id_right, apply square_of_eq, exact whisker_right (merid a) !con.right_inv end definition decode_coh_g (a' : A) : tr (up a') =[merid pt] decode_south (code_merid pt (tr a')) := begin refine _ ⬝op ap decode_south (code_merid_β_right (tr a'))⁻¹, apply trunc_pathover, apply eq_pathover_constant_left_id_right, apply square_of_eq, refine !inv_con_cancel_right ⬝ !idp_con⁻¹ end definition decode_coh_lem {A : Type} {a a' : A} (p : a = a') : whisker_right p (con.right_inv p) = inv_con_cancel_right p p ⬝ (idp_con p)⁻¹ := by induction p; reflexivity theorem decode_coh (a : A) : decode_north =[merid a] decode_south := begin apply arrow_pathover_left, intro c, esimp at *, induction c with a', rewrite [↑code, elim_type_merid], refine @wedge_extension.ext _ _ n n _ _ (λ a a', tr (up a') =[merid a] decode_south (to_fun (code_merid_equiv a) (tr a'))) _ _ _ _ a a', { intros, apply is_trunc_pathover, apply is_trunc_succ, apply is_trunc_trunc}, { exact decode_coh_f}, { exact decode_coh_g}, { clear a a', unfold [decode_coh_f, decode_coh_g], refine ap011 concato_eq _ _, { refine ap (λp, trunc_pathover (eq_pathover_constant_left_id_right (square_of_eq p))) _, apply decode_coh_lem}, { apply ap (λp, ap decode_south p⁻¹), apply code_merid_coh}} end definition decode [unfold 4] {x : susp A} (c : code x) : trunc (n + n) (north = x) := begin induction x with a, { exact decode_north c}, { exact decode_south c}, { exact decode_coh a} end theorem decode_encode {x : susp A} (p : trunc (n + n) (north = x)) : decode (encode p) = p := begin induction p with p, induction p, esimp, apply decode_north_pt end parameters (A n) definition equiv' : trunc (n + n) A ≃ trunc (n + n) (Ω (psusp A)) := equiv.MK decode_north encode decode_encode encode_decode_north definition pequiv' : ptrunc (n + n) A ≃* ptrunc (n + n) (Ω (psusp A)) := pequiv_of_equiv equiv' decode_north_pt -- We don't prove this: -- theorem freudenthal_suspension : is_conn_fun (n+n) (loop_psusp_unit A) := sorry end end freudenthal open algebra group definition freudenthal_pequiv (A : Type*) {n k : ℕ} [is_conn n A] (H : k ≤ 2 * n) : ptrunc k A ≃* ptrunc k (Ω (psusp A)) := have H' : k ≤[ℕ₋₂] n + n, by rewrite [mul.comm at H, -algebra.zero_add n at {1}]; exact of_nat_le_of_nat H, ptrunc_pequiv_ptrunc_of_le H' (freudenthal.pequiv' A n) definition freudenthal_equiv {A : Type*} {n k : ℕ} [is_conn n A] (H : k ≤ 2 * n) : trunc k A ≃ trunc k (Ω (psusp A)) := freudenthal_pequiv A H definition freudenthal_homotopy_group_pequiv (A : Type*) {n k : ℕ} [is_conn n A] (H : k ≤ 2 * n) : π[k + 1] (psusp A) ≃* π[k] A := calc π[k + 1] (psusp A) ≃* π[k] (Ω (psusp A)) : homotopy_group_succ_in (psusp A) k ... ≃* Ω[k] (ptrunc k (Ω (psusp A))) : homotopy_group_pequiv_loop_ptrunc k (Ω (psusp A)) ... ≃* Ω[k] (ptrunc k A) : loopn_pequiv_loopn k (freudenthal_pequiv A H) ... ≃* π[k] A : (homotopy_group_pequiv_loop_ptrunc k A)⁻¹ᵉ* definition freudenthal_homotopy_group_isomorphism (A : Type*) {n k : ℕ} [is_conn n A] (H : k + 1 ≤ 2 * n) : πg[k+2] (psusp A) ≃g πg[k + 1] A := begin fapply isomorphism_of_equiv, { exact equiv_of_pequiv (freudenthal_homotopy_group_pequiv A H)}, { intro g h, refine _ ⬝ !homotopy_group_pequiv_loop_ptrunc_inv_con, apply ap !homotopy_group_pequiv_loop_ptrunc⁻¹ᵉ*, refine ap (loopn_pequiv_loopn _ _) _ ⬝ !loopn_pequiv_loopn_con, refine ap !homotopy_group_pequiv_loop_ptrunc _ ⬝ !homotopy_group_pequiv_loop_ptrunc_con, apply homotopy_group_succ_in_con} end definition to_pmap_freudenthal_pequiv {A : Type*} (n k : ℕ) [is_conn n A] (H : k ≤ 2 * n) : freudenthal_pequiv A H ~* ptrunc_functor k (loop_psusp_unit A) := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity }, { refine !idp_con ⬝ _, refine _ ⬝ ap02 _ !idp_con⁻¹, refine _ ⬝ !ap_compose, apply ap_compose } end definition ptrunc_elim_freudenthal_pequiv {A B : Type*} (n k : ℕ) [is_conn n A] (H : k ≤ 2 * n) (f : A →* Ω B) [is_trunc (k.+1) (B)] : ptrunc.elim k (Ω→ (psusp.elim f)) ∘* freudenthal_pequiv A H ~* ptrunc.elim k f := begin refine pwhisker_left _ !to_pmap_freudenthal_pequiv ⬝* _, refine !ptrunc_elim_ptrunc_functor ⬝* _, exact ptrunc_elim_phomotopy k !ap1_psusp_elim, end namespace susp definition iterate_psusp_stability_pequiv (A : Type*) {k n : ℕ} [is_conn 0 A] (H : k ≤ 2 * n) : π[k + 1] (iterate_psusp (n + 1) A) ≃* π[k] (iterate_psusp n A) := have is_conn n (iterate_psusp n A), by rewrite [-zero_add n]; exact _, freudenthal_homotopy_group_pequiv (iterate_psusp n A) H definition iterate_psusp_stability_isomorphism (A : Type*) {k n : ℕ} [is_conn 0 A] (H : k + 1 ≤ 2 * n) : πg[k+2] (iterate_psusp (n + 1) A) ≃g πg[k+1] (iterate_psusp n A) := have is_conn n (iterate_psusp n A), by rewrite [-zero_add n]; exact _, freudenthal_homotopy_group_isomorphism (iterate_psusp n A) H definition stability_helper1 {k n : ℕ} (H : k + 2 ≤ 2 * n) : k ≤ 2 * pred n := begin rewrite [mul_pred_right], change pred (pred (k + 2)) ≤ pred (pred (2 * n)), apply pred_le_pred, apply pred_le_pred, exact H end definition stability_helper2 (A : Type) {k n : ℕ} (H : k + 2 ≤ 2 * n) : is_conn (pred n) (iterate_susp (n + 1) A) := have Π(n : ℕ), n = -2 + (succ n + 1), begin intro n, induction n with n IH, reflexivity, exact ap succ IH end, begin cases n with n, { exfalso, exact not_succ_le_zero _ H}, { esimp, rewrite [this n], apply is_conn_iterate_susp} end definition iterate_susp_stability_pequiv (A : Type) {k n : ℕ} (H : k + 2 ≤ 2 * n) : π[k + 1] (pointed.MK (iterate_susp (n + 2) A) !north) ≃* π[k ] (pointed.MK (iterate_susp (n + 1) A) !north) := have is_conn (pred n) (carrier (pointed.MK (iterate_susp (n + 1) A) !north)), from stability_helper2 A H, freudenthal_homotopy_group_pequiv (pointed.MK (iterate_susp (n + 1) A) !north) (stability_helper1 H) definition iterate_susp_stability_isomorphism (A : Type) {k n : ℕ} (H : k + 3 ≤ 2 * n) : πg[k+1 +1] (pointed.MK (iterate_susp (n + 2) A) !north) ≃g πg[k+1] (pointed.MK (iterate_susp (n + 1) A) !north) := have is_conn (pred n) (carrier (pointed.MK (iterate_susp (n + 1) A) !north)), from @stability_helper2 A (k+1) n H, freudenthal_homotopy_group_isomorphism (pointed.MK (iterate_susp (n + 1) A) !north) (stability_helper1 H) definition iterated_freudenthal_pequiv (A : Type*) {n k m : ℕ} [HA : is_conn n A] (H : k ≤ 2 * n) : ptrunc k A ≃* ptrunc k (Ω[m] (iterate_psusp m A)) := begin revert A n k HA H, induction m with m IH: intro A n k HA H, { reflexivity}, { have H2 : succ k ≤ 2 * succ n, from calc succ k ≤ succ (2 * n) : succ_le_succ H ... ≤ 2 * succ n : self_le_succ, exact calc ptrunc k A ≃* ptrunc k (Ω (psusp A)) : freudenthal_pequiv A H ... ≃* Ω (ptrunc (succ k) (psusp A)) : loop_ptrunc_pequiv ... ≃* Ω (ptrunc (succ k) (Ω[m] (iterate_psusp m (psusp A)))) : loop_pequiv_loop (IH (psusp A) (succ n) (succ k) _ H2) ... ≃* ptrunc k (Ω[succ m] (iterate_psusp m (psusp A))) : loop_ptrunc_pequiv ... ≃* ptrunc k (Ω[succ m] (iterate_psusp (succ m) A)) : ptrunc_pequiv_ptrunc _ (loopn_pequiv_loopn _ !iterate_psusp_succ_in)} end end susp
4efe3846b12e44e616681d48e257869bf353ea29
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/order/complete_lattice.lean
4eff73521275392c184060bedc422524ea588474
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
41,166
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 -/ import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions We use `Sup`/`Inf`/`supr`/`infi` for the corresponding functions in the statement. Sometimes we also use `bsupr`/`binfi` for "bounded` supremum or infimum, i.e. one of `⨆ i ∈ s, f i`, `⨆ i (hi : p i), f i`, or more generally `⨆ i (hi : p i), f i hi`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set variables {α β β₂ : Type*} {ι ι₂ : Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ class complete_lattice (α : Type*) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities, so it should be used with `.. complete_lattice_of_Inf α _`. -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities, so it should be used with `.. complete_lattice_of_Sup α _`. -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, decidable_linear_order α end prio section variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := is_lub_le_iff (is_lub_Sup s) @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := le_is_glb_iff (is_glb_Inf s) theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs -- TODO: it is weird that we have to add union_def theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := by finish /- le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t)) -/ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := is_lub_empty.Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := is_glb_univ.Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := iff.intro (assume h a ha, top_unique $ h ▸ Inf_le ha) (assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha) @[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) := iff.intro (assume h a ha, bot_unique $ h ▸ le_Sup ha) (assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha) end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := is_glb_lt_iff (is_glb_Inf s) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := lt_is_lub_iff (is_lub_Sup s) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) @[nolint ge_or_gt] -- see Note [nolint_ge] lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) := iff.intro (assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb) (assume h, bot_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha)) lemma lt_supr_iff {f : ι → α} : a < supr f ↔ (∃i, a < f i) := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ (∃i, f i < a) := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- supr & infi -/ section variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _ lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _ lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem le_bsupr {p : ι → Prop} {f : Π i (h : p i), α} (i : ι) (hi : p i) : f i hi ≤ ⨆ i hi, f i hi := le_supr_of_le i $ le_supr (f i) hi theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i theorem bsupr_le {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ a) : (⨆ i (hi : p i), f i hi) ≤ a := supr_le $ λ i, supr_le $ h i theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem bsupr_le_bsupr {p : ι → Prop} {f g : Π i (hi : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨆ i hi, f i hi) ≤ ⨆ i hi, g i hi := bsupr_le $ λ i hi, le_trans (h i hi) (le_bsupr i hi) theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := (is_lub_le_iff is_lub_supr).trans forall_range_iff theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) := ⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr2 [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : (⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) := calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) : supr_le_supr $ λ i, hf.le_map_supr ... ≤ f (⨆ i (h : ι' i), s i h) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆a∈s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr2 _ lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_le_supr2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_le_supr2 $ λ x, (hs x).imp $ λ i hi, hf hi) lemma supr_congr {f : β → α} {g : β₂ → α} (h : β → β₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { unfold supr, congr' 1, convert h1.range_comp g, ext, rw ←h2 } -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {α : Type*} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin unfold supr, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ end theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ /- I wanted to see if this would help for infi_comm; it doesn't. @[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂) : (: ⨅ i j, s i j :) ≤ (: s i j :) := begin transitivity, apply (infi_le (λ i, ⨅ j, s i j) i), apply infi_le end -/ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem binfi_le {p : ι → Prop} {f : Π i (hi : p i), α} (i : ι) (hi : p i) : (⨅ i hi, f i hi) ≤ f i hi := infi_le_of_le i $ infi_le (f i) hi theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i theorem le_binfi {p : ι → Prop} {f : Π i (h : p i), α} (h : ∀ i hi, a ≤ f i hi) : a ≤ ⨅ i hi, f i hi := le_infi $ λ i, le_infi $ h i theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem binfi_le_binfi {p : ι → Prop} {f g : Π i (h : p i), α} (h : ∀ i hi, f i hi ≤ g i hi) : (⨅ i hi, f i hi) ≤ ⨅ i hi, g i hi := le_binfi $ λ i hi, le_trans (binfi_le i hi) (h i hi) theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := le_antisymm (le_infi $ assume b, le_infi $ assume h, Inf_le h) (le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h) lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) : f (infi s) ≤ (⨅ i, f (s i)) := le_infi $ λ i, hf $ infi_le _ _ lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f) {ι' : ι → Sort*} (s : Π i, ι' i → α) : f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) := calc f (⨅ i (h : ι' i), s i h) ≤ (⨅ i, f (⨅ h, s i h)) : hf.map_infi_le ... ≤ (⨅ i h, f (s i h)) : infi_le_infi $ λ i, hf.map_infi_le lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a∈s, f a := by rw [Inf_eq_infi]; exact hf.map_infi2_le _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_le_infi2 $ λ x, ⟨_, le_refl _⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_le_infi2 $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma infi_congr {f : β → α} {g : β₂ → α} (h : β → β₂) (h1 : function.surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := by { unfold infi, congr' 1, convert h1.range_comp g, ext, rw ←h2 } @[congr] theorem infi_congr_Prop {α : Type*} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := begin unfold infi, apply congr_arg, ext, simp, split, exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩, exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩ end -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a := by rw [supr, range_const, Sup_singleton] @[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ := bot_unique $ supr_le $ assume i, le_refl _ @[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := iff.intro (assume eq i, top_unique $ eq ▸ infi_le _ _) (assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i) @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) := iff.intro (assume eq i, bot_unique $ eq ▸ le_supr _ _) (assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i) @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆h:p, a h) = (if h : p then a h else ⊥) := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆h:p, a) = (if p then a else ⊥) := by rw [supr_eq_dif, dif_eq_if] lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅h:p, a h) = (if h : p then a h else ⊤) := by by_cases p; simp [h] lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅h:p, a) = (if p then a else ⊤) := by rw [infi_eq_dif, dif_eq_if] -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := le_antisymm (supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i) (supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j) @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) attribute [ematch] le_refl theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := le_antisymm (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right)) lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf i]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} {i : ι} (hi : p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left) (infi_le_of_le i $ infi_le_of_le hi $ inf_le_right)) theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ assume i, sup_le (le_sup_left_of_le $ le_supr _ _) (le_sup_right_of_le $ le_supr _ _)) (sup_le (supr_le $ assume i, le_supr_of_le i le_sup_left) (supr_le $ assume i, le_supr_of_le i le_sup_right)) /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := le_antisymm (supr_le $ assume s, match s with | or.inl i := le_sup_left_of_le $ le_supr _ i | or.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩)) lemma Sup_range {α : Type*} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl lemma Inf_range {α : Type*} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := le_antisymm (le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _)) (le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i) theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi ... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm] ... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm] ... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr ... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm] ... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm] ... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left] /- supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or ... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := by simpa [classical.em] using @supr_union _ _ _ f {i | p i} {i | ¬ p i} lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := by convert supr_split _ _; simp theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := by rw [(union_eq_self_of_subset_left h).symm, supr_union]; exact le_sup_left theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := by simp theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := le_antisymm (le_infi $ assume b, le_infi $ assume hbt, infi_le_of_le (f b) $ infi_le (λ_, g (f b)) (mem_image_of_mem f hbt)) (le_infi $ assume c, le_infi $ assume ⟨b, hbt, eq⟩, eq ▸ infi_le_of_le b $ infi_le (λ_, g (f b)) hbt) lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := le_antisymm (supr_le $ assume c, supr_le $ assume ⟨b, hbt, eq⟩, eq ▸ le_supr_of_le b $ le_supr (λ_, g (f b)) hbt) (supr_le $ assume b, supr_le $ assume hbt, le_supr_of_le (f b) $ le_supr (λ_, g (f b)) (mem_image_of_mem f hbt)) /- supr and infi under Type -/ theorem infi_of_empty' (h : ι → false) {s : ι → α} : infi s = ⊤ := top_unique (le_infi $ assume i, (h i).elim) theorem supr_of_empty' (h : ι → false) {s : ι → α} : supr s = ⊥ := bot_unique (supr_le $ assume i, (h i).elim) theorem infi_of_empty (h : ¬nonempty ι) {s : ι → α} : infi s = ⊤ := infi_of_empty' (λ i, h ⟨i⟩) theorem supr_of_empty (h : ¬nonempty ι) {s : ι → α} : supr s = ⊥ := supr_of_empty' (λ i, h ⟨i⟩) @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := infi_of_empty nonempty_empty @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := supr_of_empty nonempty_empty @[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := le_antisymm (le_inf (infi_le _ _) (infi_le _ _)) (le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end) theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma Sup_eq_supr' {s : set α} : Sup s = ⨆ x : s, (x : α) := by rw [Sup_eq_supr, supr_subtype']; refl lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := le_antisymm (supr_le $ assume s, match s with | sum.inl i := le_sup_left_of_le $ le_supr _ i | sum.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩)) end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] @[nolint ge_or_gt] -- see Note [nolint_ge] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /- Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, .. bounded_distrib_lattice_Prop } lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) := le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i) lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Πa, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Πa, β a) a) := rfl lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆f:s, (f : Πa, β a) a) := rfl lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) := @infi_apply α (λ i, order_dual (β i)) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, supr_le $ λ f, le_supr_of_le f $ m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_infi $ λ f, infi_le_of_le f $ m_s f f.2 h end complete_lattice namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice (order_dual α) := { le_Sup := @complete_lattice.Inf_le α _, Sup_le := @complete_lattice.le_Inf α _, Inf_le := @complete_lattice.le_Sup α _, le_Inf := @complete_lattice.Sup_le α _, .. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α } instance [complete_linear_order α] : complete_linear_order (order_dual α) := { .. order_dual.complete_lattice α, .. order_dual.decidable_linear_order α } end order_dual namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := assume s p h, ⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := assume s p h, ⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩, .. prod.bounded_lattice α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod
1a0c496bd0830fd8e99fcbbb05b1a86fb7c6c447
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/group/integration.lean
1143a97806c65af239036f52e3c6d9b739739a4f
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
8,406
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.integral.bochner import measure_theory.group.measure import measure_theory.group.action /-! # Integration on Groups We develop properties of integrals with a group as domain. This file contains properties about integrability, Lebesgue integration and Bochner integration. -/ namespace measure_theory open measure topological_space open_locale ennreal variables {𝕜 M α G E F : Type*} [measurable_space G] variables [normed_group E] [normed_space ℝ E] [complete_space E] [normed_group F] variables {μ : measure G} {f : G → E} {g : G} section measurable_inv variables [group G] [has_measurable_inv G] @[to_additive] lemma integrable.comp_inv [is_inv_invariant μ] {f : G → F} (hf : integrable f μ) : integrable (λ t, f t⁻¹) μ := (hf.mono_measure (map_inv_eq_self μ).le).comp_measurable measurable_inv @[to_additive] lemma integral_inv_eq_self (f : G → E) (μ : measure G) [is_inv_invariant μ] : ∫ x, f (x⁻¹) ∂μ = ∫ x, f x ∂μ := begin have h : measurable_embedding (λ x : G, x⁻¹) := (measurable_equiv.inv G).measurable_embedding, rw [← h.integral_map, map_inv_eq_self] end end measurable_inv section measurable_mul variables [group G] [has_measurable_mul G] /-- Translating a function by left-multiplication does not change its `measure_theory.lintegral` with respect to a left-invariant measure. -/ @[to_additive "Translating a function by left-addition does not change its `measure_theory.lintegral` with respect to a left-invariant measure."] lemma lintegral_mul_left_eq_self [is_mul_left_invariant μ] (f : G → ℝ≥0∞) (g : G) : ∫⁻ x, f (g * x) ∂μ = ∫⁻ x, f x ∂μ := begin convert (lintegral_map_equiv f $ measurable_equiv.mul_left g).symm, simp [map_mul_left_eq_self μ g] end /-- Translating a function by right-multiplication does not change its `measure_theory.lintegral` with respect to a right-invariant measure. -/ @[to_additive "Translating a function by right-addition does not change its `measure_theory.lintegral` with respect to a right-invariant measure."] lemma lintegral_mul_right_eq_self [is_mul_right_invariant μ] (f : G → ℝ≥0∞) (g : G) : ∫⁻ x, f (x * g) ∂μ = ∫⁻ x, f x ∂μ := begin convert (lintegral_map_equiv f $ measurable_equiv.mul_right g).symm, simp [map_mul_right_eq_self μ g] end @[simp, to_additive] lemma lintegral_div_right_eq_self [is_mul_right_invariant μ] (f : G → ℝ≥0∞) (g : G) : ∫⁻ x, f (x / g) ∂μ = ∫⁻ x, f x ∂μ := by simp_rw [div_eq_mul_inv, lintegral_mul_right_eq_self f g⁻¹] /-- Translating a function by left-multiplication does not change its integral with respect to a left-invariant measure. -/ @[simp, to_additive "Translating a function by left-addition does not change its integral with respect to a left-invariant measure."] lemma integral_mul_left_eq_self [is_mul_left_invariant μ] (f : G → E) (g : G) : ∫ x, f (g * x) ∂μ = ∫ x, f x ∂μ := begin have h_mul : measurable_embedding (λ x, g * x) := (measurable_equiv.mul_left g).measurable_embedding, rw [← h_mul.integral_map, map_mul_left_eq_self] end /-- Translating a function by right-multiplication does not change its integral with respect to a right-invariant measure. -/ @[simp, to_additive "Translating a function by right-addition does not change its integral with respect to a right-invariant measure."] lemma integral_mul_right_eq_self [is_mul_right_invariant μ] (f : G → E) (g : G) : ∫ x, f (x * g) ∂μ = ∫ x, f x ∂μ := begin have h_mul : measurable_embedding (λ x, x * g) := (measurable_equiv.mul_right g).measurable_embedding, rw [← h_mul.integral_map, map_mul_right_eq_self] end @[simp, to_additive] lemma integral_div_right_eq_self [is_mul_right_invariant μ] (f : G → E) (g : G) : ∫ x, f (x / g) ∂μ = ∫ x, f x ∂μ := by simp_rw [div_eq_mul_inv, integral_mul_right_eq_self f g⁻¹] /-- If some left-translate of a function negates it, then the integral of the function with respect to a left-invariant measure is 0. -/ @[to_additive "If some left-translate of a function negates it, then the integral of the function with respect to a left-invariant measure is 0."] lemma integral_eq_zero_of_mul_left_eq_neg [is_mul_left_invariant μ] (hf' : ∀ x, f (g * x) = - f x) : ∫ x, f x ∂μ = 0 := by simp_rw [← self_eq_neg ℝ E, ← integral_neg, ← hf', integral_mul_left_eq_self] /-- If some right-translate of a function negates it, then the integral of the function with respect to a right-invariant measure is 0. -/ @[to_additive "If some right-translate of a function negates it, then the integral of the function with respect to a right-invariant measure is 0."] lemma integral_eq_zero_of_mul_right_eq_neg [is_mul_right_invariant μ] (hf' : ∀ x, f (x * g) = - f x) : ∫ x, f x ∂μ = 0 := by simp_rw [← self_eq_neg ℝ E, ← integral_neg, ← hf', integral_mul_right_eq_self] @[to_additive] lemma integrable.comp_mul_left {f : G → F} [is_mul_left_invariant μ] (hf : integrable f μ) (g : G) : integrable (λ t, f (g * t)) μ := (hf.mono_measure (map_mul_left_eq_self μ g).le).comp_measurable $ measurable_const_mul g @[to_additive] lemma integrable.comp_mul_right {f : G → F} [is_mul_right_invariant μ] (hf : integrable f μ) (g : G) : integrable (λ t, f (t * g)) μ := (hf.mono_measure (map_mul_right_eq_self μ g).le).comp_measurable $ measurable_mul_const g @[to_additive] lemma integrable.comp_div_right {f : G → F} [is_mul_right_invariant μ] (hf : integrable f μ) (g : G) : integrable (λ t, f (t / g)) μ := by { simp_rw [div_eq_mul_inv], exact hf.comp_mul_right g⁻¹ } variables [has_measurable_inv G] @[to_additive] lemma integrable.comp_div_left {f : G → F} [is_inv_invariant μ] [is_mul_left_invariant μ] (hf : integrable f μ) (g : G) : integrable (λ t, f (g / t)) μ := begin rw [← map_mul_right_inv_eq_self μ g⁻¹, integrable_map_measure, function.comp], { simp_rw [div_inv_eq_mul, mul_inv_cancel_left], exact hf }, { refine ae_strongly_measurable.comp_measurable _ (measurable_id.const_div g), simp_rw [map_map (measurable_id'.const_div g) (measurable_id'.const_mul g⁻¹).inv, function.comp, div_inv_eq_mul, mul_inv_cancel_left, map_id'], exact hf.ae_strongly_measurable }, { exact (measurable_id'.const_mul g⁻¹).inv.ae_measurable } end @[simp, to_additive] lemma integrable_comp_div_left (f : G → F) [is_inv_invariant μ] [is_mul_left_invariant μ] (g : G) : integrable (λ t, f (g / t)) μ ↔ integrable f μ := begin refine ⟨λ h, _, λ h, h.comp_div_left g⟩, convert h.comp_inv.comp_mul_left g⁻¹, simp_rw [div_inv_eq_mul, mul_inv_cancel_left] end @[simp, to_additive] lemma integral_div_left_eq_self (f : G → E) (μ : measure G) [is_inv_invariant μ] [is_mul_left_invariant μ] (x' : G) : ∫ x, f (x' / x) ∂μ = ∫ x, f x ∂μ := by simp_rw [div_eq_mul_inv, integral_inv_eq_self (λ x, f (x' * x)) μ, integral_mul_left_eq_self f x'] end measurable_mul section smul variables [group G] [measurable_space α] [mul_action G α] [has_measurable_smul G α] @[simp, to_additive] lemma integral_smul_eq_self {μ : measure α} [smul_invariant_measure G α μ] (f : α → E) {g : G} : ∫ x, f (g • x) ∂μ = ∫ x, f x ∂μ := begin have h : measurable_embedding (λ x : α, g • x) := (measurable_equiv.smul g).measurable_embedding, rw [← h.integral_map, map_smul] end end smul section topological_group variables [topological_space G] [group G] [topological_group G] [borel_space G] [is_mul_left_invariant μ] /-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function `f` is 0 iff `f` is 0. -/ @[to_additive "For nonzero regular left invariant measures, the integral of a continuous nonnegative function `f` is 0 iff `f` is 0."] lemma lintegral_eq_zero_of_is_mul_left_invariant [regular μ] (hμ : μ ≠ 0) {f : G → ℝ≥0∞} (hf : continuous f) : ∫⁻ x, f x ∂μ = 0 ↔ f = 0 := begin haveI := is_open_pos_measure_of_mul_left_invariant_of_regular hμ, rw [lintegral_eq_zero_iff hf.measurable, hf.ae_eq_iff_eq μ continuous_zero] end end topological_group end measure_theory
08283b6675de6683280bd3f7d9eefeae51bebba7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/InfoTree.lean
0e84967de2c2800a82aaa8869cf177759a9c9b8f
[ "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
15,245
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.Position import Lean.Expr import Lean.Message import Lean.Data.Json import Lean.Meta.Basic import Lean.Meta.PPGoal namespace Lean.Elab open Std (PersistentArray PersistentArray.empty PersistentHashMap) /- Context after executing `liftTermElabM`. Note that the term information collected during elaboration may contain metavariables, and their assignments are stored at `mctx`. -/ structure ContextInfo where env : Environment fileMap : FileMap mctx : MetavarContext := {} options : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] deriving Inhabited /-- An elaboration step -/ structure ElabInfo where elaborator : Name stx : Syntax deriving Inhabited structure TermInfo extends ElabInfo where lctx : LocalContext -- The local context when the term was elaborated. expectedType? : Option Expr expr : Expr isBinder : Bool := false deriving Inhabited structure CommandInfo extends ElabInfo where deriving Inhabited inductive CompletionInfo where | dot (termInfo : TermInfo) (field? : Option Syntax) (expectedType? : Option Expr) | id (stx : Syntax) (id : Name) (danglingDot : Bool) (lctx : LocalContext) (expectedType? : Option Expr) | namespaceId (stx : Syntax) | option (stx : Syntax) | endSection (stx : Syntax) (scopeNames : List String) | tactic (stx : Syntax) (goals : List MVarId) -- TODO `import` def CompletionInfo.stx : CompletionInfo → Syntax | dot i .. => i.stx | id stx .. => stx | namespaceId stx => stx | option stx => stx | endSection stx .. => stx | tactic stx .. => stx structure FieldInfo where /-- Name of the projection. -/ projName : Name /-- Name of the field as written. -/ fieldName : Name lctx : LocalContext val : Expr stx : Syntax deriving Inhabited /- We store the list of goals before and after the execution of a tactic. We also store the metavariable context at each time since, we want to unassigned metavariables at tactic execution time to be displayed as `?m...`. -/ structure TacticInfo extends ElabInfo where mctxBefore : MetavarContext goalsBefore : List MVarId mctxAfter : MetavarContext goalsAfter : List MVarId deriving Inhabited structure MacroExpansionInfo where lctx : LocalContext -- The local context when the macro was expanded. stx : Syntax output : Syntax deriving Inhabited inductive Info where | ofTacticInfo (i : TacticInfo) | ofTermInfo (i : TermInfo) | ofCommandInfo (i : CommandInfo) | ofMacroExpansionInfo (i : MacroExpansionInfo) | ofFieldInfo (i : FieldInfo) | ofCompletionInfo (i : CompletionInfo) deriving Inhabited inductive InfoTree where | context (i : ContextInfo) (t : InfoTree) -- The context object is created by `liftTermElabM` at `Command.lean` | node (i : Info) (children : PersistentArray InfoTree) -- The children contains information for nested term elaboration and tactic evaluation | ofJson (j : Json) -- For user data | hole (mvarId : MVarId) -- The elaborator creates holes (aka metavariables) for tactics and postponed terms deriving Inhabited partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option Info := match t with | context _ t => findInfo? p t | node i ts => if p i then some i else ts.findSome? (findInfo? p) | _ => none structure InfoState where enabled : Bool := false assignment : PersistentHashMap MVarId InfoTree := {} -- map from holeId to InfoTree trees : PersistentArray InfoTree := {} deriving Inhabited class MonadInfoTree (m : Type → Type) where getInfoState : m InfoState modifyInfoState : (InfoState → InfoState) → m Unit export MonadInfoTree (getInfoState modifyInfoState) instance [MonadLift m n] [MonadInfoTree m] : MonadInfoTree n where getInfoState := liftM (getInfoState : m _) modifyInfoState f := liftM (modifyInfoState f : m _) partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree := match tree with | node i c => node i <| c.map (substitute · assignment) | context i t => context i (substitute t assignment) | ofJson j => ofJson j | hole id => match assignment.find? id with | none => hole id | some tree => substitute tree assignment def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do let x := x.run { lctx := lctx } { mctx := info.mctx } let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } { env := info.env } return a def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext := { env := info.env, mctx := info.mctx, lctx := lctx, opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do ppTerm (info.toPPContext lctx) stx private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := let pos := stx.getPos?.getD 0 let endPos := stx.getTailPos?.getD pos f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}" where fmtPos pos info := let pos := format <| ctx.fileMap.toPosition pos match info with | SourceInfo.original .. => pos | _ => f!"{pos}†" private def formatElabInfo (ctx : ContextInfo) (info : ElabInfo) : Format := if info.elaborator.isAnonymous then formatStxRange ctx info.stx else f!"{formatStxRange ctx info.stx} @ {info.elaborator}" def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α := ctx.runMetaM info.lctx x def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do info.runMetaM ctx do try return f!"{← Meta.ppExpr info.expr} : {← Meta.ppExpr (← Meta.inferType info.expr)} @ {formatElabInfo ctx info.toElabInfo}" catch _ => return f!"{← Meta.ppExpr info.expr} : <failed-to-infer-type> @ {formatElabInfo ctx info.toElabInfo}" def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format := match info with | CompletionInfo.dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}" | CompletionInfo.id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}" | _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}" def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do return f!"command @ {formatElabInfo ctx info.toElabInfo}" def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do ctx.runMetaM info.lctx do return f!"{info.fieldName} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}" def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format := if goals.isEmpty then return "no goals" else ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM (Meta.ppGoal .))) def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do let ctxB := { ctx with mctx := info.mctxBefore } let ctxA := { ctx with mctx := info.mctxAfter } let goalsBefore ← ctxB.ppGoals info.goalsBefore let goalsAfter ← ctxA.ppGoals info.goalsAfter return f!"Tactic @ {formatElabInfo ctx info.toElabInfo}\n{info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}" def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do let stx ← ctx.ppSyntax info.lctx info.stx let output ← ctx.ppSyntax info.lctx info.output return f!"Macro expansion\n{stx}\n===>\n{output}" def Info.format (ctx : ContextInfo) : Info → IO Format | ofTacticInfo i => i.format ctx | ofTermInfo i => i.format ctx | ofCommandInfo i => i.format ctx | ofMacroExpansionInfo i => i.format ctx | ofFieldInfo i => i.format ctx | ofCompletionInfo i => i.format ctx def Info.toElabInfo? : Info → Option ElabInfo | ofTacticInfo i => some i.toElabInfo | ofTermInfo i => some i.toElabInfo | ofCommandInfo i => some i.toElabInfo | ofMacroExpansionInfo i => none | ofFieldInfo i => none | ofCompletionInfo i => none /-- Helper function for propagating the tactic metavariable context to its children nodes. We need this function because we preserve `TacticInfo` nodes during backtracking *and* their children. Moreover, we backtrack the metavariable context to undo metavariable assignments. `TacticInfo` nodes save the metavariable context before/after the tactic application, and can be pretty printed without any extra information. This is not the case for `TermInfo` nodes. Without this function, the formatting method would often fail when processing `TermInfo` nodes that are children of `TacticInfo` nodes that have been preserved during backtracking. Saving the metavariable context at `TermInfo` nodes is also not a good option because at `TermInfo` creation time, the metavariable context often miss information, e.g., a TC problem has not been resolved, a postponed subterm has not been elaborated, etc. See `Term.SavedState.restore`. -/ def Info.updateContext? : Option ContextInfo → Info → Option ContextInfo | some ctx, ofTacticInfo i => some { ctx with mctx := i.mctxAfter } | ctx?, _ => ctx? partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do match tree with | ofJson j => return toString j | hole id => return toString id.name | context i t => format t i | node i cs => match ctx? with | none => return "<context-not-available>" | some ctx => let fmt ← i.format ctx if cs.size == 0 then return fmt else let ctx? := i.updateContext? ctx? return f!"{fmt}{Std.Format.nestD <| Std.Format.prefixJoin (Std.format "\n") (← cs.toList.mapM fun c => format c ctx?)}" section variable [Monad m] [MonadInfoTree m] @[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit := modifyInfoState fun s => { s with trees := f s.trees } def getResetInfoTrees : m (PersistentArray InfoTree) := do let trees := (← getInfoState).trees modifyInfoTrees fun _ => {} return trees def pushInfoTree (t : InfoTree) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => ts.push t def pushInfoLeaf (t : Info) : m Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) t def addCompletionInfo (info : CompletionInfo) : m Unit := do pushInfoLeaf <| Info.ofCompletionInfo info def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m Name := do let n ← resolveGlobalConstNoOverload id if (← getInfoState).enabled then -- we do not store a specific elaborator since identifiers are special-cased by the server anyway pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := id, expectedType? } return n def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) (expectedType? : Option Expr := none) : m (List Name) := do let ns ← resolveGlobalConst id if (← getInfoState).enabled then for n in ns do pushInfoLeaf <| Info.ofTermInfo { elaborator := Name.anonymous, lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := id, expectedType? } return ns def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => do match a? with | none => modifyInfoTrees fun _ => treesSaved | some a => let info ← mkInfo a modifyInfoTrees fun trees => match info with | Sum.inl info => treesSaved.push <| InfoTree.node info trees | Sum.inr mvaId => treesSaved.push <| InfoTree.hole mvaId else x def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let tree ← mkInfoTree st.trees modifyInfoTrees fun _ => treesSaved.push tree else x @[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees) def withSaveInfoContext [MonadFinally m] [MonadEnv m] [MonadOptions m] [MonadMCtx m] [MonadResolveName m] [MonadFileMap m] (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let trees ← st.trees.mapM fun tree => do let tree := tree.substitute st.assignment InfoTree.context { env := (← getEnv), fileMap := (← getFileMap), mctx := (← getMCtx), currNamespace := (← getCurrNamespace), openDecls := (← getOpenDecls), options := (← getOptions) } tree modifyInfoTrees fun _ => treesSaved ++ trees else x def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) := return (← getInfoState).assignment[mvarId] def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do assert! (← getInfoHoleIdAssignment? mvarId).isNone modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree } end def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (stx output : Syntax) (x : m α) : m α := let mkInfo : m Info := do return Info.ofMacroExpansionInfo { lctx := (← getLCtx) stx, output } withInfoContext x mkInfo @[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => modifyInfoState fun s => if s.trees.size > 0 then { s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] } else { s with trees := treesSaved } else x def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit := modifyInfoState fun s => { s with enabled := flag } def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) := return (← getInfoState).trees end Lean.Elab
1a83f71d7723c21f75b0c8932fb5c83734a95b53
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/functor/currying.lean
26a95ef824fa72f0f065bac21f81b0ef9732ab3f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,017
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.products.bifunctor /-! # Curry and uncurry, as functors. We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`, and verify that they provide an equivalence of categories `currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`. -/ namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variables {B : Type u₁} [category.{v₁} B] {C : Type u₂} [category.{v₂} C] {D : Type u₃} [category.{v₃} D] {E : Type u₄} [category.{v₄} E] /-- The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`. -/ @[simps] def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) := { obj := λ F, { obj := λ X, (F.obj X.1).obj X.2, map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2, map_comp' := λ X Y Z f g, begin simp only [prod_comp_fst, prod_comp_snd, functor.map_comp, nat_trans.comp_app, category.assoc], slice_lhs 2 3 { rw ← nat_trans.naturality }, rw category.assoc, end }, map := λ F G T, { app := λ X, (T.app X.1).app X.2, naturality' := λ X Y f, begin simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc, functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app], slice_lhs 2 3 { rw nat_trans.naturality }, slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app] }, rw category.assoc, end } }. /-- The object level part of the currying functor. (See `curry` for the functorial version.) -/ def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) := { obj := λ X, { obj := λ Y, F.obj (X, Y), map := λ Y Y' g, F.map (𝟙 X, g) }, map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } } /-- The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`. -/ @[simps obj_obj_obj obj_obj_map obj_map_app map_app_app] def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) := { obj := λ F, curry_obj F, map := λ F G T, { app := λ X, { app := λ Y, T.app (X, Y), naturality' := λ Y Y' g, begin dsimp [curry_obj], rw nat_trans.naturality, end }, naturality' := λ X X' f, begin ext, dsimp [curry_obj], rw nat_trans.naturality, end } }. /-- The equivalence of functor categories given by currying/uncurrying. -/ @[simps] -- create projection simp lemmas even though this isn't a `{ .. }`. def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) := equivalence.mk uncurry curry (nat_iso.of_components (λ F, nat_iso.of_components (λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy)) (nat_iso.of_components (λ F, nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (by tidy)) /-- `F.flip` is isomorphic to uncurrying `F`, swapping the variables, and currying. -/ @[simps] def flip_iso_curry_swap_uncurry (F : C ⥤ D ⥤ E) : F.flip ≅ curry.obj (prod.swap _ _ ⋙ uncurry.obj F) := nat_iso.of_components (λ d, nat_iso.of_components (λ c, iso.refl _) (by tidy)) (by tidy) /-- The uncurrying of `F.flip` is isomorphic to swapping the factors followed by the uncurrying of `F`. -/ @[simps] def uncurry_obj_flip (F : C ⥤ D ⥤ E) : uncurry.obj F.flip ≅ prod.swap _ _ ⋙ uncurry.obj F := nat_iso.of_components (λ p, iso.refl _) (by tidy) variables (B C D E) /-- A version of `category_theory.whiskering_right` for bifunctors, obtained by uncurrying, applying `whiskering_right` and currying back -/ @[simps] def whiskering_right₂ : (C ⥤ D ⥤ E) ⥤ ((B ⥤ C) ⥤ (B ⥤ D) ⥤ (B ⥤ E)) := uncurry ⋙ (whiskering_right _ _ _) ⋙ ((whiskering_left _ _ _).obj (prod_functor_to_functor_prod _ _ _)) ⋙ curry end category_theory
e405bc3677ee5cd8c4dfed20126a65511ecc33b3
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/sheaves/presheaf.lean
f8401c44654dbec2df3db4ff4185ae1dadadc997
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,930
lean
/- Presheaf (of types). https://stacks.math.columbia.edu/tag/006D Author: Ramon Fernandez Mir -/ import topology.basic import topology.opens universes u v -- Definition of a presheaf. open topological_space lattice structure presheaf (α : Type u) [topological_space α] := (F : opens α → Type v) (res : ∀ (U V) (HVU : V ⊆ U), F U → F V) (Hid : ∀ (U), res U U (set.subset.refl U) = id) (Hcomp : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U), res U W (set.subset.trans HWV HVU) = res V W HWV ∘ res U V HVU) namespace presheaf variables {α : Type u} [topological_space α] instance : has_coe_to_fun (presheaf α) := { F := λ _, opens α → Type v, coe := presheaf.F } -- Simplification lemmas for Hid and Hcomp. @[simp] lemma Hcomp' (F : presheaf α) : ∀ (U V W) (HWV : W ⊆ V) (HVU : V ⊆ U) (s : F U), (F.res U W (set.subset.trans HWV HVU)) s = (F.res V W HWV) ((F.res U V HVU) s) := λ U V W HWV HVU s, by rw F.Hcomp U V W HWV HVU @[simp] lemma Hid' (F : presheaf α) : ∀ (U) (s : F U), (F.res U U (set.subset.refl U)) s = s := λ U s, by rw F.Hid U; simp -- Morphism of presheaves. structure morphism (F G : presheaf α) := (map : ∀ (U), F U → G U) (commutes : ∀ (U V) (HVU : V ⊆ U), (G.res U V HVU) ∘ (map U) = (map V) ∘ (F.res U V HVU)) infix `⟶`:80 := morphism section morphism def comp {F G H : presheaf α} (fg : F ⟶ G) (gh : G ⟶ H) : F ⟶ H := { map := λ U, gh.map U ∘ fg.map U, commutes := λ U V HVU, begin rw [←function.comp.assoc, gh.commutes U V HVU], symmetry, rw [function.comp.assoc, ←fg.commutes U V HVU] end } infix `⊚`:80 := comp def id (F : presheaf α) : F ⟶ F := { map := λ U, id, commutes := λ U V HVU, by simp, } structure iso (F G : presheaf α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor ⊚ inv = id F) (inv_mor_id : inv ⊚ mor = id G) end morphism end presheaf
e2fe4ba0b5a9bacb5104b7361c1b765d7b5a5dd8
4727251e0cd73359b15b664c3170e5d754078599
/src/data/qpf/multivariate/constructions/sigma.lean
98bc5f1c1ace79ced8d4206bbfd119099d8edb79
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,034
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.pfunctor.multivariate.basic import data.qpf.multivariate.basic /-! # Dependent product and sum of QPFs are QPFs -/ universes u namespace mvqpf open_locale mvfunctor variables {n : ℕ} {A : Type u} variables (F : A → typevec.{u} n → Type u) /-- Dependent sum of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def sigma (v : typevec.{u} n) : Type.{u} := Σ α : A, F α v /-- Dependent product of of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def pi (v : typevec.{u} n) : Type.{u} := Π α : A, F α v instance sigma.inhabited {α} [inhabited A] [inhabited (F default α)] : inhabited (sigma F α) := ⟨ ⟨default, default⟩ ⟩ instance pi.inhabited {α} [Π a, inhabited (F a α)] : inhabited (pi F α) := ⟨ λ a, default ⟩ variables [Π α, mvfunctor $ F α] namespace sigma instance : mvfunctor (sigma F) := { map := λ α β f ⟨a,x⟩, ⟨a,f <$$> x⟩ } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent sum -/ protected def P : mvpfunctor n := ⟨ Σ a, (P (F a)).A, λ x, (P (F x.1)).B x.2 ⟩ /-- abstraction function for dependent sums -/ protected def abs ⦃α⦄ : (sigma.P F).obj α → sigma F α | ⟨a,f⟩ := ⟨ a.1, mvqpf.abs ⟨a.2, f⟩ ⟩ /-- representation function for dependent sums -/ protected def repr ⦃α⦄ : sigma F α → (sigma.P F).obj α | ⟨a,f⟩ := let x := mvqpf.repr f in ⟨ ⟨a,x.1⟩, x.2 ⟩ instance : mvqpf (sigma F) := { P := sigma.P F, abs := sigma.abs F, repr := sigma.repr F, abs_repr := by rintros α ⟨x,f⟩; simp [sigma.repr,sigma.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp [sigma.abs,mvpfunctor.map_eq]; simp [(<$$>),mvfunctor._match_1,← abs_map,← mvpfunctor.map_eq] } end sigma namespace pi instance : mvfunctor (pi F) := { map := λ α β f x a, f <$$> x a } variables [Π α, mvqpf $ F α] /-- polynomial functor representation of a dependent product -/ protected def P : mvpfunctor n := ⟨ Π a, (P (F a)).A, λ x i, Σ a : A, (P (F a)).B (x a) i ⟩ /-- abstraction function for dependent products -/ protected def abs ⦃α⦄ : (pi.P F).obj α → pi F α | ⟨a,f⟩ := λ x, mvqpf.abs ⟨a x, λ i y, f i ⟨_,y⟩⟩ /-- representation function for dependent products -/ protected def repr ⦃α⦄ : pi F α → (pi.P F).obj α | f := ⟨ λ a, (mvqpf.repr (f a)).1, λ i a, (@mvqpf.repr _ _ _ (_inst_2 _) _ (f _)).2 _ a.2 ⟩ instance : mvqpf (pi F) := { P := pi.P F, abs := pi.abs F, repr := pi.repr F, abs_repr := by rintros α f; ext; simp [pi.repr,pi.abs,abs_repr], abs_map := by rintros α β f ⟨x,g⟩; simp only [pi.abs, mvpfunctor.map_eq]; ext; simp only [(<$$>)]; simp only [←abs_map, mvpfunctor.map_eq]; refl } end pi end mvqpf
9fcb8525bd9c8ea9a4cbedf778fc9216af8a69d4
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/get_free_var_range.lean
4174e3d7d8db8f204899d484cd83b53ff5d22d0f
[ "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
262
lean
-- should be 0 #eval expr.get_free_var_range `(Type) -- should be 2 #eval expr.get_free_var_range (expr.lam `hello binder_info.default `(Type) $ expr.app (expr.var 1) (expr.var 2)) -- should be 3 #eval expr.get_free_var_range (expr.app (expr.var 1) (expr.var 2))
164d0bbe85965b7280fded35f66c65a682c0021b
7cef822f3b952965621309e88eadf618da0c8ae9
/src/group_theory/perm/sign.lean
ccc3f63400670ff72c82dd203eb170c252a8299c
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
32,962
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype universes u v open equiv function fintype finset variables {α : Type u} {β : Type v} namespace equiv.perm def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp, λ _, by simp⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext _ _ $ λ ⟨_, _⟩, rfl def of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : perm α := ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by simp; split_ifs at *; simp * at *⟩ instance of_subtype.is_group_hom {p : α → Prop} [decidable_pred p] : is_group_hom (@of_subtype α p _) := { map_mul := λ f g, equiv.ext _ _ $ λ x, begin rw [of_subtype, of_subtype, of_subtype], by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp [h, h₁, h₂] }, { simp [h] } end } @[simp] lemma of_subtype_one (p : α → Prop) [decidable_pred p] : @of_subtype α p _ 1 = 1 := is_group_hom.map_one of_subtype lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp [disjoint, or.comm] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext _ _ $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := begin induction hp, { refl }, { rw [list.prod_cons, list.prod_cons, hp_ih (list.pairwise_cons.1 hl).2] }, { simp [list.prod_cons, disjoint_mul_comm, (mul_assoc _ _ _).symm, *, list.pairwise_cons] at * }, { rw [hp_ih_a hl, hp_ih_a_1 ((list.perm_pairwise (λ x y (h : disjoint x y), disjoint.symm h) hp_a).1 hl)] } end lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext _ _ $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp [hx] }, { haveI := classical.prop_decidable, simp [hx, not_not.1 (mt (h₂ x) hx)] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext _ _ $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp [support] def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext _ _ $ λ z, begin simp [mul_apply, swap_apply_def], split_ifs; simp [*, eq_inv_iff_eq] at * <|> cc end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] @[simp] lemma swap_mul_self (i j : α) : equiv.swap i j * equiv.swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_swap_apply (i j k : α) : equiv.swap i j (equiv.swap i j k) = k := equiv.swap_core_swap_core k i j lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp at hxy; tauto, equiv.ext _ _ $ λ z, begin rw [hxy.2, of_subtype], simp [swap_apply_def], split_ifs; cc <|> simp * at * end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp * at * }, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext.2 $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp * at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp * at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext _ _ $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [decidable_linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp [hl.1.symm] {contextual := tt} }, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext _ _ $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a.1).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp [fin_pairs_lt, fin.lt_def] def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := (fin_pairs_lt n).prod (λ x, if a x.1 ≤ a x.2 then -1 else 1) @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp [*, injective.eq_iff f.injective, sigma.mk.inj_eq] at * end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp [not_le_of_gt hab]; congr }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end instance sign_aux.is_group_hom {n : ℕ} : is_group_hom (@sign_aux n) := { map_mul := sign_aux_mul } private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = (finset.singleton (⟨one, zero⟩ : Σ a : fin n, fin n)).prod (λ x : Σ a : fin n, fin n, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1), begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp [*, lt_irrefl, -not_lt, not_le.symm, -not_le, le_refl, fin.lt_def, fin.le_def, nat.zero_le, zero, one, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact is_group_hom.is_conj _ (is_conj_swap hxy dec_trivial) def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext _ _ $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, from equiv.ext _ _ (λ z, by rw ← equiv.symm_trans_swap_trans; simp [mul_def]), have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp } end def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp [list.mem_of_perm h]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext _ _ (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] (f : perm α) := sign_aux3 f mem_univ instance sign.is_group_hom [fintype α] : is_group_hom (@sign α _ _) := { map_mul := λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1 } section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := is_mul_hom.map_mul sign _ _ @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := is_group_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := is_group_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [is_group_hom.map_inv sign, int.units_inv_eq_self]; apply_instance lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext _ _ (λ x, by simp))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = -1 ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, ← is_group_hom.map_prod (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α → units ℤ} [is_group_hom s] (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact is_group_hom.is_conj _ (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [is_group_hom.map_prod s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), funext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, is_group_hom.map_prod s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [← is_group_hom.map_prod of_subtype l.1, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext _ _ $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (show function.bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})), from ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩)) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp [eq_inv_iff_eq, inv_eq_iff_eq, *] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp [inv_eq_iff_eq, eq_inv_iff_eq] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext _ _ $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext.2 $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap [fintype α] {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x::y::0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext]; cc lemma sign_cycle [fintype α] : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1 ^ f.support.card) | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1 ^ f.support.card) : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, by conv in (f) {rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1 }; simp [mul_def, one_def], by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp [pow_add] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} end sign end equiv.perm lemma finset.prod_univ_perm [fintype α] [comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).prod f = univ.prod (λ z, f (σ z)) := eq.symm $ prod_bij (λ z _, σ z) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ H, σ.injective H) (λ b _, ⟨σ⁻¹ b, mem_univ _, by simp⟩) lemma finset.sum_univ_perm [fintype α] [add_comm_monoid β] {f : α → β} (σ : perm α) : (univ : finset α).sum f = univ.sum (λ z, f (σ z)) := @finset.prod_univ_perm _ (multiplicative β) _ _ f σ attribute [to_additive] finset.prod_univ_perm
f0f419bf6eedd42585c64f97cd2552f9fc791d65
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/group.lean
216472bfea4305a951ab3ed644ac945b5b7944b9
[ "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
24,027
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. Partially modeled on Isabelle's library. -/ import logic.eq data.sigma data.prod import algebra.binary algebra.priority open binary variable {A : Type} /- semigroup -/ /- TODO(Leo): decide whether we keep this annotation or not -/ -- attribute inv [light 3] -- attribute neg [light 3] structure semigroup [class] (A : Type) extends has_mul A := (mul_assoc : ∀a b c : A, a * b * c = a * (b * c)) -- We add pattern hints to the following lemma because we want it to be used in both directions -- at inst_simp strategy. attribute [simp] theorem mul.assoc [semigroup A] (a b c : A) : a * b * c = a * (b * c) := semigroup.mul_assoc a b c set_option pp.all true structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b : A, a * b = b * a) attribute [simp] theorem mul.comm [comm_semigroup A] (a b : A) : a * b = b * a := comm_semigroup.mul_comm a b attribute [simp] theorem mul.left_comm [comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul.comm A _) (@mul.assoc A _) a b c theorem mul.right_comm [comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := sorry -- by simp structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c : A, a * b = a * c → b = c) theorem mul.left_cancel [left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c := left_cancel_semigroup.mul_left_cancel a b c abbreviation eq_of_mul_eq_mul_left' := @mul.left_cancel structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c : A, a * b = c * b → a = c) theorem mul.right_cancel [right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c := right_cancel_semigroup.mul_right_cancel a b c abbreviation eq_of_mul_eq_mul_right' := @mul.right_cancel /- additive semigroup -/ structure add_semigroup [class] (A : Type) extends has_add A := (add_assoc : ∀a b c : A, a + b + c = a + (b + c)) attribute [simp] theorem add.assoc [add_semigroup A] (a b c : A) : a + b + c = a + (b + c) := add_semigroup.add_assoc a b c structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b : A, a + b = b + a) attribute [simp] theorem add.comm [add_comm_semigroup A] (a b : A) : a + b = b + a := add_comm_semigroup.add_comm a b attribute [simp] theorem add.left_comm [add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add.comm A _) (@add.assoc A _) a b c theorem add.right_comm [add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := sorry -- by simp structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c : A, a + b = a + c → b = c) theorem add.left_cancel [add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c := add_left_cancel_semigroup.add_left_cancel a b c abbreviation eq_of_add_eq_add_left := @add.left_cancel structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c : A, a + b = c + b → a = c) theorem add.right_cancel [add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c := add_right_cancel_semigroup.add_right_cancel a b c abbreviation eq_of_add_eq_add_right := @add.right_cancel /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, has_one A := (one_mul : ∀a : A, 1 * a = a) (mul_one : ∀a : A, a * 1 = a) attribute [simp] theorem one_mul [monoid A] (a : A) : 1 * a = a := monoid.one_mul a attribute [simp] theorem mul_one [monoid A] (a : A) : a * 1 = a := monoid.mul_one a structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A /- additive monoid -/ structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (zero_add : ∀a : A, 0 + a = a) (add_zero : ∀a : A, a + 0 = a) attribute [simp] theorem zero_add [add_monoid A] (a : A) : 0 + a = a := add_monoid.zero_add a attribute [simp] theorem add_zero [add_monoid A] (a : A) : a + 0 = a := add_monoid.add_zero a structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A definition add_monoid.to_monoid {A : Type} [add_monoid A] : monoid A := ⦃ monoid, mul := add_monoid.add, mul_assoc := add_monoid.add_assoc, one := add_monoid.zero A, mul_one := add_monoid.add_zero, one_mul := add_monoid.zero_add ⦄ definition add_comm_monoid.to_comm_monoid {A : Type} [add_comm_monoid A] : comm_monoid A := ⦃ comm_monoid, add_monoid.to_monoid, mul_comm := add_comm_monoid.add_comm ⦄ section add_comm_monoid variables [add_comm_monoid A] theorem add_comm_three (a b c : A) : a + b + c = c + b + a := sorry -- by simp theorem add.comm4 : ∀ (n m k l : A), n + m + (k + l) = n + k + (m + l) := sorry -- by simp end add_comm_monoid /- group -/ structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a : A, a⁻¹ * a = 1) -- Note: with more work, we could derive the axiom one_mul section group variable [group A] attribute [simp] theorem mul.left_inv (a : A) : a⁻¹ * a = 1 := group.mul_left_inv a attribute [simp] theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := sorry -- by rewrite [-mul.assoc, mul.left_inv, one_mul] attribute [simp] theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := sorry -- by simp theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b := sorry /- have a⁻¹ * 1 = b, by inst_simp, by inst_simp -/ attribute [simp] theorem one_inv : 1⁻¹ = (1 : A) := inv_eq_of_mul_eq_one (one_mul 1) attribute [simp] theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul.left_inv a) variable (A) theorem left_inverse_inv : function.left_inverse (λ a : A, a⁻¹) (λ a, a⁻¹) := take a, inv_inv a variable {A} theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := sorry /- have a = a⁻¹⁻¹, by simp_nohyps, by inst_simp -/ theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := sorry -- iff.intro (assume H, inv.inj H) (by simp) theorem inv_eq_one_iff_eq_one (a : A) : a⁻¹ = 1 ↔ a = 1 := sorry /- have a⁻¹ = 1⁻¹ ↔ a = 1, from inv_eq_inv_iff_eq a 1, by simp -/ theorem eq_one_of_inv_eq_one (a : A) : a⁻¹ = 1 → a = 1 := iff.mp (inv_eq_one_iff_eq_one a) theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := sorry -- by simp theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := iff.intro eq_inv_of_eq_inv eq_inv_of_eq_inv theorem eq_inv_of_mul_eq_one {a b : A} (H : a * b = 1) : a = b⁻¹ := sorry /- have a⁻¹ = b, from inv_eq_of_mul_eq_one H, by inst_simp -/ attribute [simp] theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := sorry /- have a = a⁻¹⁻¹, by simp, by inst_simp -/ attribute [simp] theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := sorry -- by inst_simp attribute [simp] theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := sorry -- by inst_simp attribute [simp] theorem mul_inv (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := sorry -- inv_eq_of_mul_eq_one (by inst_simp) theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b := sorry /- have a⁻¹ * 1 = a⁻¹, by inst_simp, by inst_simp -/ theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * c = b) : a = b * c⁻¹ := sorry -- by simp theorem eq_inv_mul_of_mul_eq {a b c : A} (H : b * a = c) : a = b⁻¹ * c := sorry -- by simp theorem inv_mul_eq_of_eq_mul {a b c : A} (H : b = a * c) : a⁻¹ * b = c := sorry -- by simp theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = c * b) : a * b⁻¹ = c := sorry -- by simp theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * c⁻¹ = b) : a = b * c := sorry -- by simp theorem eq_mul_of_inv_mul_eq {a b c : A} (H : b⁻¹ * a = c) : a = b * c := sorry -- by simp theorem mul_eq_of_eq_inv_mul {a b c : A} (H : b = a⁻¹ * c) : a * b = c := sorry -- by simp theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = c * b⁻¹) : a * b = c := sorry -- by simp theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c := iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ := iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c := sorry /- have a⁻¹ * (a * b) = b, by inst_simp, by inst_simp -/ theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c := sorry /- have a * b * b⁻¹ = a, by inst_simp, by inst_simp -/ theorem mul_eq_one_of_mul_eq_one {a b : A} (H : b * a = 1) : a * b = 1 := sorry -- by rewrite [-inv_eq_of_mul_eq_one H, mul.left_inv] theorem mul_eq_one_iff_mul_eq_one (a b : A) : a * b = 1 ↔ b * a = 1 := iff.intro mul_eq_one_of_mul_eq_one mul_eq_one_of_mul_eq_one definition conj_by (g a : A) := g * a * g⁻¹ definition is_conjugate (a b : A) := ∃ x, conj_by x b = a local infixl ` ~ ` := is_conjugate local infixr ` ∘c `:55 := conj_by local attribute conj_by [reducible] attribute [simp] lemma conj_compose (f g a : A) : f ∘c g ∘c a = f*g ∘c a := sorry -- by inst_simp attribute [simp] lemma conj_id (a : A) : 1 ∘c a = a := sorry -- by inst_simp attribute [simp] lemma conj_one (g : A) : g ∘c 1 = 1 := sorry -- by inst_simp attribute [simp] lemma conj_inv_cancel (g : A) : ∀ a, g⁻¹ ∘c g ∘c a = a := sorry -- by inst_simp attribute [simp] lemma conj_inv (g : A) : ∀ a, (g ∘c a)⁻¹ = g ∘c a⁻¹ := sorry -- by inst_simp lemma is_conj.refl (a : A) : a ~ a := exists.intro 1 (conj_id a) lemma is_conj.symm (a b : A) : a ~ b → b ~ a := sorry /- assume Pab, obtain x (Pconj : x ∘c b = a), from Pab, have Pxinv : x⁻¹ ∘c x ∘c b = x⁻¹ ∘c a, by simp, exists.intro x⁻¹ (by simp) -/ lemma is_conj.trans (a b c : A) : a ~ b → b ~ c → a ~ c := sorry /- assume Pab, assume Pbc, obtain x (Px : x ∘c b = a), from Pab, obtain y (Py : y ∘c c = b), from Pbc, exists.intro (x*y) (by inst_simp) -/ end group attribute [instance] definition group.to_left_cancel_semigroup [s : group A] : left_cancel_semigroup A := ⦃ left_cancel_semigroup, s, mul_left_cancel := @mul_left_cancel A s ⦄ attribute [instance] definition group.to_right_cancel_semigroup [s : group A] : right_cancel_semigroup A := ⦃ right_cancel_semigroup, s, mul_right_cancel := @mul_right_cancel A s ⦄ structure comm_group [class] (A : Type) extends group A, comm_monoid A /- additive group -/ structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a : A, -a + a = 0) definition add_group.to_group {A : Type} [add_group A] : group A := ⦃ group, add_monoid.to_monoid, mul_left_inv := add_group.add_left_inv ⦄ section add_group variables [s : add_group A] include s attribute [simp] theorem add.left_inv (a : A) : -a + a = 0 := add_group.add_left_inv a attribute [simp] theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := calc -a + (a + b) = (-a + a) + b : sorry -- by rewrite add.assoc ... = b : sorry -- by simp attribute [simp] theorem neg_add_cancel_right (a b : A) : a + -b + b = a := sorry -- by simp theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b := sorry /- have -a + 0 = b, by inst_simp, by inst_simp -/ attribute [simp] theorem neg_zero : -0 = (0 : A) := neg_eq_of_add_eq_zero (zero_add 0) attribute [simp] theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a) variable (A) theorem left_inverse_neg : function.left_inverse (λ a : A, - a) (λ a, - a) := take a, neg_neg a variable {A} theorem eq_neg_of_add_eq_zero {a b : A} (H : a + b = 0) : a = -b := have -a = b, from neg_eq_of_add_eq_zero H, sorry -- by inst_simp theorem neg.inj {a b : A} (H : -a = -b) : a = b := sorry /- have a = -(-a), by simp_nohyps, by inst_simp -/ theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := sorry -- iff.intro (assume H, neg.inj H) (by simp) theorem eq_of_neg_eq_neg {a b : A} : -a = -b → a = b := iff.mp (neg_eq_neg_iff_eq a b) theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 := have -a = -0 ↔ a = 0, from neg_eq_neg_iff_eq a 0, sorry -- by simp theorem eq_zero_of_neg_eq_zero {a : A} : -a = 0 → a = 0 := iff.mp (neg_eq_zero_iff_eq_zero a) theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a := sorry -- by simp theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := iff.intro eq_neg_of_eq_neg eq_neg_of_eq_neg attribute [simp] theorem add.right_inv (a : A) : a + -a = 0 := sorry /- have a = -(-a), by simp, by inst_simp -/ attribute [simp] theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := sorry -- by inst_simp attribute [simp] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := sorry -- by simp attribute [simp] theorem neg_add_rev (a b : A) : -(a + b) = -b + -a := sorry -- neg_eq_of_add_eq_zero (by simp) -- TODO: delete these in favor of sub rules? theorem eq_add_neg_of_add_eq {a b c : A} (H : a + c = b) : a = b + -c := sorry -- by simp theorem eq_neg_add_of_add_eq {a b c : A} (H : b + a = c) : a = -b + c := sorry -- by simp theorem neg_add_eq_of_eq_add {a b c : A} (H : b = a + c) : -a + b = c := sorry -- by simp theorem add_neg_eq_of_eq_add {a b c : A} (H : a = c + b) : a + -b = c := sorry -- by simp theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -c = b) : a = b + c := sorry -- by simp theorem eq_add_of_neg_add_eq {a b c : A} (H : -b + a = c) : a = b + c := sorry -- by simp theorem add_eq_of_eq_neg_add {a b c : A} (H : b = -a + c) : a + b = c := sorry -- by simp theorem add_eq_of_eq_add_neg {a b c : A} (H : a = c + -b) : a + b = c := sorry -- by simp theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c := iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b := iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c := sorry /- have -a + (a + b) = b, by inst_simp, by inst_simp -/ theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c := sorry /- have a + b + -b = a, by inst_simp, by inst_simp -/ attribute [instance] definition add_group.to_left_cancel_semigroup : add_left_cancel_semigroup A := ⦃ add_left_cancel_semigroup, s, add_left_cancel := @add_left_cancel A s ⦄ attribute [instance] definition add_group.to_add_right_cancel_semigroup : add_right_cancel_semigroup A := ⦃ add_right_cancel_semigroup, s, add_right_cancel := @add_right_cancel A s ⦄ theorem add_neg_eq_neg_add_rev {a b : A} : a + -b = -(b + -a) := sorry -- by simp theorem ne_add_of_ne_zero_right (a : A) {b : A} (H : b ≠ 0) : a ≠ b + a := sorry /- begin intro Heq, apply H, rewrite [-zero_add a at Heq{1}], let Heq' := eq_of_add_eq_add_right Heq, apply eq.symm Heq' end -/ theorem ne_add_of_ne_zero_left (a : A) {b : A} (H : b ≠ 0) : a ≠ a + b := sorry /- begin intro Heq, apply H, rewrite [-add_zero a at Heq{1}], let Heq' := eq_of_add_eq_add_left Heq, apply eq.symm Heq' end -/ /- sub -/ -- TODO: derive corresponding facts for div in a field attribute [reducible] protected definition algebra.sub (a b : A) : A := a + -b attribute [instance] definition add_group_has_sub : has_sub A := has_sub.mk algebra.sub attribute [simp] theorem sub_eq_add_neg (a b : A) : a - b = a + -b := rfl theorem sub_self (a : A) : a - a = 0 := add.right_inv a theorem sub_add_cancel (a b : A) : a - b + b = a := neg_add_cancel_right a b theorem add_sub_cancel (a b : A) : a + b - b = a := add_neg_cancel_right a b theorem add_sub_assoc (a b c : A) : a + b - c = a + (b - c) := sorry -- by rewrite [sub_eq_add_neg, add.assoc, -sub_eq_add_neg] theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b := sorry /- have -a + 0 = -a, by inst_simp, by inst_simp -/ theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 := iff.intro (assume H, eq.subst H (sub_self _)) (assume H, eq_of_sub_eq_zero H) theorem zero_sub (a : A) : 0 - a = -a := zero_add (-a) theorem sub_zero (a : A) : a - 0 = a := sorry -- by simp theorem sub_ne_zero_of_ne {a b : A} (H : a ≠ b) : a - b ≠ 0 := sorry /- begin intro Hab, apply H, apply eq_of_sub_eq_zero Hab end -/ theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b := sorry -- by simp theorem neg_sub (a b : A) : -(a - b) = b - a := sorry -- neg_eq_of_add_eq_zero (by inst_simp) theorem add_sub (a b c : A) : a + (b - c) = a + b - c := sorry -- by simp theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b := sorry -- by inst_simp theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H) theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H) theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := calc a = b ↔ a - b = 0 : eq_iff_sub_eq_zero a b ... = (c - d = 0) : sorry -- by rewrite H ... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d) theorem eq_sub_of_add_eq {a b c : A} (H : a + c = b) : a = b - c := sorry -- by simp theorem sub_eq_of_eq_add {a b c : A} (H : a = c + b) : a - b = c := sorry -- by simp theorem eq_add_of_sub_eq {a b c : A} (H : a - c = b) : a = b + c := sorry -- by simp theorem add_eq_of_eq_sub {a b c : A} (H : a = c - b) : a + b = c := sorry -- by simp theorem left_inverse_sub_add_left (c : A) : function.left_inverse (λ x, x - c) (λ x, x + c) := take x, add_sub_cancel x c theorem left_inverse_add_left_sub (c : A) : function.left_inverse (λ x, x + c) (λ x, x - c) := take x, sub_add_cancel x c theorem left_inverse_add_right_neg_add (c : A) : function.left_inverse (λ x, c + x) (λ x, - c + x) := take x, add_neg_cancel_left c x theorem left_inverse_neg_add_add_right (c : A) : function.left_inverse (λ x, - c + x) (λ x, c + x) := take x, neg_add_cancel_left c x end add_group structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A section add_comm_group variable [s : add_comm_group A] include s theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c := sorry -- by simp theorem neg_add_eq_sub (a b : A) : -a + b = b - a := sorry -- by simp theorem neg_add (a b : A) : -(a + b) = -a + -b := sorry -- by simp theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b := sorry -- by simp theorem sub_sub (a b c : A) : a - b - c = a - (b + c) := sorry -- by simp theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b := sorry -- by simp theorem eq_sub_of_add_eq' {a b c : A} (H : c + a = b) : a = b - c := sorry -- by simp theorem sub_eq_of_eq_add' {a b c : A} (H : a = b + c) : a - b = c := sorry -- by simp theorem eq_add_of_sub_eq' {a b c : A} (H : a - b = c) : a = b + c := sorry -- by simp theorem add_eq_of_eq_sub' {a b c : A} (H : b = c - a) : a + b = c := sorry -- by simp theorem sub_sub_self (a b : A) : a - (a - b) = b := sorry -- by simp theorem add_sub_comm (a b c d : A) : a + b - (c + d) = (a - c) + (b - d) := sorry -- by simp theorem sub_eq_sub_add_sub (a b c : A) : a - b = c - b + (a - c) := sorry -- by simp theorem neg_neg_sub_neg (a b : A) : - (-a - -b) = a - b := sorry -- by simp end add_comm_group definition group_of_add_group (A : Type) [G : add_group A] : group A := ⦃group, mul := has_add.add, mul_assoc := add.assoc, one := has_zero.zero A, one_mul := zero_add, mul_one := add_zero, inv := has_neg.neg, mul_left_inv := add.left_inv⦄ namespace norm_num reveal add.assoc definition add1 [has_add A] [has_one A] (a : A) : A := add a one local attribute add1 bit0 bit1 [reducible] theorem add_comm_four [add_comm_semigroup A] (a b : A) : a + a + (b + b) = (a + b) + (a + b) := sorry -- by simp theorem add_comm_middle [add_comm_semigroup A] (a b c : A) : a + b + c = a + c + b := sorry -- by simp theorem bit0_add_bit0 [add_comm_semigroup A] (a b : A) : bit0 a + bit0 b = bit0 (a + b) := sorry -- by simp theorem bit0_add_bit0_helper [add_comm_semigroup A] (a b t : A) (H : a + b = t) : bit0 a + bit0 b = bit0 t := sorry -- by rewrite -H; simp theorem bit1_add_bit0 [add_comm_semigroup A] [has_one A] (a b : A) : bit1 a + bit0 b = bit1 (a + b) := sorry -- by simp theorem bit1_add_bit0_helper [add_comm_semigroup A] [has_one A] (a b t : A) (H : a + b = t) : bit1 a + bit0 b = bit1 t := sorry -- by rewrite -H; simp theorem bit0_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) : bit0 a + bit1 b = bit1 (a + b) := sorry -- by simp theorem bit0_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t : A) (H : a + b = t) : bit0 a + bit1 b = bit1 t := sorry -- by rewrite -H; simp theorem bit1_add_bit1 [add_comm_semigroup A] [has_one A] (a b : A) : bit1 a + bit1 b = bit0 (add1 (a + b)) := sorry -- by simp theorem bit1_add_bit1_helper [add_comm_semigroup A] [has_one A] (a b t s: A) (H : (a + b) = t) (H2 : add1 t = s) : bit1 a + bit1 b = bit0 s := sorry -- by inst_simp theorem bin_add_zero [add_monoid A] (a : A) : a + zero = a := sorry -- by simp theorem bin_zero_add [add_monoid A] (a : A) : zero + a = a := sorry -- by simp theorem one_add_bit0 [add_comm_semigroup A] [has_one A] (a : A) : one + bit0 a = bit1 a := sorry -- by simp theorem bit0_add_one [has_add A] [has_one A] (a : A) : bit0 a + one = bit1 a := rfl theorem bit1_add_one [has_add A] [has_one A] (a : A) : bit1 a + one = add1 (bit1 a) := rfl theorem bit1_add_one_helper [has_add A] [has_one A] (a t : A) (H : add1 (bit1 a) = t) : bit1 a + one = t := sorry -- by inst_simp theorem one_add_bit1 [add_comm_semigroup A] [has_one A] (a : A) : one + bit1 a = add1 (bit1 a) := sorry -- by simp theorem one_add_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A) (H : add1 (bit1 a) = t) : one + bit1 a = t := sorry -- by inst_simp theorem add1_bit0 [has_add A] [has_one A] (a : A) : add1 (bit0 a) = bit1 a := rfl theorem add1_bit1 [add_comm_semigroup A] [has_one A] (a : A) : add1 (bit1 a) = bit0 (add1 a) := sorry -- by simp theorem add1_bit1_helper [add_comm_semigroup A] [has_one A] (a t : A) (H : add1 a = t) : add1 (bit1 a) = bit0 t := sorry -- by inst_simp theorem add1_one [has_add A] [has_one A] : add1 (one : A) = bit0 one := rfl theorem add1_zero [add_monoid A] [has_one A] : add1 (zero : A) = one := sorry -- by simp theorem one_add_one [has_add A] [has_one A] : (one : A) + one = bit0 one := rfl theorem subst_into_sum [has_add A] (l r tl tr t : A) (prl : l = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := sorry -- by simp theorem neg_zero_helper [add_group A] (a : A) (H : a = 0) : - a = 0 := sorry -- by simp end norm_num attribute [simp] zero_add add_zero one_mul mul_one attribute [simp] neg_neg sub_eq_add_neg attribute [simp] add.assoc add.comm add.left_comm mul.left_comm mul.comm mul.assoc
3a4a4771fc211254800901308ae06e345cb52e22
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/analysis/normed_space/finite_dimension.lean
d01acb2c07f0830a5f3a047d2875710bae4e9e51
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
12,345
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.operator_norm import linear_algebra.finite_dimensional import tactic.omega /-! # Finite dimensional normed spaces over complete fields Over a complete nondiscrete field, in finite dimension, all norms are equivalent and all linear maps are continuous. Moreover, a finite-dimensional subspace is always complete and closed. ## Main results: * `linear_map.continuous_of_finite_dimensional` : a linear map on a finite-dimensional space over a complete field is continuous. * `finite_dimensional.complete` : a finite-dimensional space over a complete field is complete. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. * `submodule.closed_of_finite_dimensional` : a finite-dimensional subspace over a complete field is closed * `finite_dimensional.proper` : a finite-dimensional space over a proper field is proper. This is not registered as an instance, as the field would be an unknown metavariable in typeclass resolution. It is however registered as an instance for `𝕜 = ℝ` and `𝕜 = ℂ`. As properness implies completeness, there is no need to also register `finite_dimensional.complete` on `ℝ` or `ℂ`. ## Implementation notes The fact that all norms are equivalent is not written explicitly, as it would mean having two norms on a single space, which is not the way type classes work. However, if one has a finite-dimensional vector space `E` with a norm, and a copy `E'` of this type with another norm, then the identities from `E` to `E'` and from `E'`to `E` are continuous thanks to `linear_map.continuous_of_finite_dimensional`. This gives the desired norm equivalence. -/ universes u v w x open set finite_dimensional open_locale classical big_operators /-- A linear map on `ι → 𝕜` (where `ι` is a fintype) is continuous -/ lemma linear_map.continuous_on_pi {ι : Type w} [fintype ι] {𝕜 : Type u} [normed_field 𝕜] {E : Type v} [add_comm_group E] [vector_space 𝕜 E] [topological_space E] [topological_add_group E] [topological_vector_space 𝕜 E] (f : (ι → 𝕜) →ₗ[𝕜] E) : continuous f := begin -- for the proof, write `f` in the standard basis, and use that each coordinate is a continuous -- function. have : (f : (ι → 𝕜) → E) = (λx, ∑ i : ι, x i • (f (λj, if i = j then 1 else 0))), by { ext x, exact f.pi_apply_eq_sum_univ x }, rw this, refine continuous_finset_sum _ (λi hi, _), exact (continuous_apply i).smul continuous_const end section complete_field variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {F : Type w} [normed_group F] [normed_space 𝕜 F] {F' : Type x} [add_comm_group F'] [vector_space 𝕜 F'] [topological_space F'] [topological_add_group F'] [topological_vector_space 𝕜 F'] [complete_space 𝕜] /-- In finite dimension over a complete field, the canonical identification (in terms of a basis) with `𝕜^n` together with its sup norm is continuous. This is the nontrivial part in the fact that all norms are equivalent in finite dimension. This statement is superceded by the fact that every linear map on a finite-dimensional space is continuous, in `linear_map.continuous_of_finite_dimensional`. -/ lemma continuous_equiv_fun_basis {ι : Type v} [fintype ι] (ξ : ι → E) (hξ : is_basis 𝕜 ξ) : continuous (equiv_fun_basis hξ) := begin unfreezeI, induction hn : fintype.card ι with n IH generalizing ι E, { apply linear_map.continuous_of_bound _ 0 (λx, _), have : equiv_fun_basis hξ x = 0, by { ext i, exact (fintype.card_eq_zero_iff.1 hn i).elim }, change ∥equiv_fun_basis hξ x∥ ≤ 0 * ∥x∥, rw this, simp [norm_nonneg] }, { haveI : finite_dimensional 𝕜 E := of_finite_basis hξ, -- first step: thanks to the inductive assumption, any n-dimensional subspace is equivalent -- to a standard space of dimension n, hence it is complete and therefore closed. have H₁ : ∀s : submodule 𝕜 E, findim 𝕜 s = n → is_closed (s : set E), { assume s s_dim, rcases exists_is_basis_finite 𝕜 s with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have U : uniform_embedding (equiv_fun_basis b_basis).symm.to_equiv, { have : fintype.card b = n, by { rw ← s_dim, exact (findim_eq_card_basis b_basis).symm }, have : continuous (equiv_fun_basis b_basis) := IH (subtype.val : b → s) b_basis this, exact (equiv_fun_basis b_basis).symm.uniform_embedding (linear_map.continuous_on_pi _) this }, have : is_complete (s : set E), from complete_space_coe_iff_is_complete.1 ((complete_space_congr U).1 (by apply_instance)), exact is_closed_of_is_complete this }, -- second step: any linear form is continuous, as its kernel is closed by the first step have H₂ : ∀f : E →ₗ[𝕜] 𝕜, continuous f, { assume f, have : findim 𝕜 f.ker = n ∨ findim 𝕜 f.ker = n.succ, { have Z := f.findim_range_add_findim_ker, rw [findim_eq_card_basis hξ, hn] at Z, have : findim 𝕜 f.range = 0 ∨ findim 𝕜 f.range = 1, { have I : ∀(k : ℕ), k ≤ 1 ↔ k = 0 ∨ k = 1, by omega manual, have : findim 𝕜 f.range ≤ findim 𝕜 𝕜 := submodule.findim_le _, rwa [findim_of_field, I] at this }, cases this, { rw this at Z, right, simpa using Z }, { left, rw [this, add_comm, nat.add_one] at Z, exact nat.succ_inj Z } }, have : is_closed (f.ker : set E), { cases this, { exact H₁ _ this }, { have : f.ker = ⊤, by { apply eq_top_of_findim_eq, rw [findim_eq_card_basis hξ, hn, this] }, simp [this] } }, exact linear_map.continuous_iff_is_closed_ker.2 this }, -- third step: applying the continuity to the linear form corresponding to a coefficient in the -- basis decomposition, deduce that all such coefficients are controlled in terms of the norm have : ∀i:ι, ∃C, 0 ≤ C ∧ ∀(x:E), ∥equiv_fun_basis hξ x i∥ ≤ C * ∥x∥, { assume i, let f : E →ₗ[𝕜] 𝕜 := (linear_map.proj i).comp (equiv_fun_basis hξ), let f' : E →L[𝕜] 𝕜 := { cont := H₂ f, ..f }, exact ⟨∥f'∥, norm_nonneg _, λx, continuous_linear_map.le_op_norm f' x⟩ }, -- fourth step: combine the bound on each coefficient to get a global bound and the continuity choose C0 hC0 using this, let C := ∑ i, C0 i, have C_nonneg : 0 ≤ C := finset.sum_nonneg (λi hi, (hC0 i).1), have C0_le : ∀i, C0 i ≤ C := λi, finset.single_le_sum (λj hj, (hC0 j).1) (finset.mem_univ _), apply linear_map.continuous_of_bound _ C (λx, _), rw pi_norm_le_iff, { exact λi, le_trans ((hC0 i).2 x) (mul_le_mul_of_nonneg_right (C0_le i) (norm_nonneg _)) }, { exact mul_nonneg C_nonneg (norm_nonneg _) } } end /-- Any linear map on a finite dimensional space over a complete field is continuous. -/ theorem linear_map.continuous_of_finite_dimensional [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : continuous f := begin -- for the proof, go to a model vector space `b → 𝕜` thanks to `continuous_equiv_fun_basis`, and -- argue that all linear maps there are continuous. rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have A : continuous (equiv_fun_basis b_basis) := continuous_equiv_fun_basis _ b_basis, have B : continuous (f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E)) := linear_map.continuous_on_pi _, have : continuous ((f.comp ((equiv_fun_basis b_basis).symm : (b → 𝕜) →ₗ[𝕜] E)) ∘ (equiv_fun_basis b_basis)) := B.comp A, convert this, ext x, dsimp, rw linear_equiv.symm_apply_apply end /-- The continuous linear map induced by a linear map on a finite dimensional space -/ def linear_map.to_continuous_linear_map [finite_dimensional 𝕜 E] (f : E →ₗ[𝕜] F') : E →L[𝕜] F' := { cont := f.continuous_of_finite_dimensional, ..f } /-- The continuous linear equivalence induced by a linear equivalence on a finite dimensional space. -/ def linear_equiv.to_continuous_linear_equiv [finite_dimensional 𝕜 E] (e : E ≃ₗ[𝕜] F) : E ≃L[𝕜] F := { continuous_to_fun := e.to_linear_map.continuous_of_finite_dimensional, continuous_inv_fun := begin haveI : finite_dimensional 𝕜 F := e.finite_dimensional, exact e.symm.to_linear_map.continuous_of_finite_dimensional end, ..e } /-- Any finite-dimensional vector space over a complete field is complete. We do not register this as an instance to avoid an instance loop when trying to prove the completeness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ variables (𝕜 E) lemma finite_dimensional.complete [finite_dimensional 𝕜 E] : complete_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, have : uniform_embedding (equiv_fun_basis b_basis).symm := linear_equiv.uniform_embedding _ (linear_map.continuous_of_finite_dimensional _) (linear_map.continuous_of_finite_dimensional _), change uniform_embedding (equiv_fun_basis b_basis).symm.to_equiv at this, exact (complete_space_congr this).1 (by apply_instance) end variables {𝕜 E} /-- A finite-dimensional subspace is complete. -/ lemma submodule.complete_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_complete (s : set E) := complete_space_coe_iff_is_complete.1 (finite_dimensional.complete 𝕜 s) /-- A finite-dimensional subspace is closed. -/ lemma submodule.closed_of_finite_dimensional (s : submodule 𝕜 E) [finite_dimensional 𝕜 s] : is_closed (s : set E) := is_closed_of_is_complete s.complete_of_finite_dimensional lemma continuous_linear_map.exists_right_inverse_of_surjective [finite_dimensional 𝕜 F] (f : E →L[𝕜] F) (hf : f.range = ⊤) : ∃ g : F →L[𝕜] E, f.comp g = continuous_linear_map.id 𝕜 F := let ⟨g, hg⟩ := (f : E →ₗ[𝕜] F).exists_right_inverse_of_surjective hf in ⟨g.to_continuous_linear_map, continuous_linear_map.ext $ linear_map.ext_iff.1 hg⟩ end complete_field section proper_field variables (𝕜 : Type u) [nondiscrete_normed_field 𝕜] (E : Type v) [normed_group E] [normed_space 𝕜 E] [proper_space 𝕜] /-- Any finite-dimensional vector space over a proper field is proper. We do not register this as an instance to avoid an instance loop when trying to prove the properness of `𝕜`, and the search for `𝕜` as an unknown metavariable. Declare the instance explicitly when needed. -/ lemma finite_dimensional.proper [finite_dimensional 𝕜 E] : proper_space E := begin rcases exists_is_basis_finite 𝕜 E with ⟨b, b_basis, b_finite⟩, letI : fintype b := finite.fintype b_finite, let e := equiv_fun_basis b_basis, let f : E →L[𝕜] (b → 𝕜) := { cont := linear_map.continuous_of_finite_dimensional _, ..e.to_linear_map }, refine metric.proper_image_of_proper e.symm (linear_map.continuous_of_finite_dimensional _) _ (∥f∥) (λx y, _), { exact equiv.range_eq_univ e.symm.to_equiv }, { have A : e (e.symm x) = x := linear_equiv.apply_symm_apply _ _, have B : e (e.symm y) = y := linear_equiv.apply_symm_apply _ _, conv_lhs { rw [← A, ← B] }, change dist (f (e.symm x)) (f (e.symm y)) ≤ ∥f∥ * dist (e.symm x) (e.symm y), exact f.lipschitz.dist_le_mul _ _ } end end proper_field /- Over the real numbers, we can register the previous statement as an instance as it will not cause problems in instance resolution since the properness of `ℝ` is already known. -/ instance finite_dimensional.proper_real (E : Type u) [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : proper_space E := finite_dimensional.proper ℝ E attribute [instance, priority 900] finite_dimensional.proper_real
e145e8301d1bf5678ef6a8093d1c4b8556d3f986
a3d3bdc686e1395146a6eecc22431ac7fafb6bc7
/examples/ping_pong_server.lean
33cc85b2b3912b3aaa9ce5f7731781f5b68e11f7
[ "Apache-2.0" ]
permissive
jroesch/net
c66581150cad7fc8f10fe1b5fecdae2912211f75
218eac82ea4a4956f63a01e88dc3d2fbbad406c8
refs/heads/master
1,606,948,723,891
1,499,287,492,000
1,499,287,492,000
96,160,509
0
0
null
null
null
null
UTF-8
Lean
false
false
431
lean
import system.io import ..src.net variable [io.interface] def main : io unit := do io.print_ln "starting ping-pong server ...", listener ← tcp_listener.bind "localhost" 3000, io.print_ln "listening on localhost:3000", io.forever $ do stream ← tcp_listener.accept listener, io.print_ln "received ping", tcp_stream.write stream "pong", io.print_ln "sent pong", return ()
c982c80fa09f12996b7962e07d1a645b33fe820c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/list/basic.lean
34396e367320d1faa226494e8a07182262340b0c
[ "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
187,697
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] /-! ### 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 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] 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, priority 500] theorem sum_repeat {α : Type*} [add_monoid α] : ∀ (a : α) (n : ℕ), (list.repeat a n).sum = n • a := @list.prod_repeat (multiplicative α) _ @[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 @[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 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
543245e315775e623b66471c5b0f39c673cbddea
63abd62053d479eae5abf4951554e1064a4c45b4
/src/field_theory/mv_polynomial.lean
395b6334349f2451df2a77c9661375c1e4aededa
[ "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
3,355
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in `n` variables. -/ import linear_algebra.finsupp_vector_space import algebra.char_p noncomputable theory open_locale classical open set linear_map submodule open_locale big_operators namespace mv_polynomial universes u v variables {σ : Type u} {α : Type v} section variables (σ α) [field α] (m : ℕ) def restrict_total_degree : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m } lemma mem_restrict_total_degree (p : mv_polynomial σ α) : p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end end section variables (σ α) def restrict_degree (m : ℕ) [field α] : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | ∀i, n i ≤ m } end lemma mem_restrict_degree [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_supported], refl end lemma mem_restrict_degree_iff_sup [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end lemma map_range_eq_map {β : Type*} [comm_ring α] [comm_ring β] (p : mv_polynomial σ α) (f : α →+* β) : finsupp.map_range f f.map_zero p = map f p := begin rw [← finsupp.sum_single p, finsupp.sum], -- It's not great that we need to use an `erw` here, -- but hopefully it will become smoother when we move entirely away from `is_semiring_hom`. erw [finsupp.map_range_finset_sum (f : α →+ β)], rw [← p.support.sum_hom (map f)], { refine finset.sum_congr rfl (assume n _, _), rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial], refl, }, apply_instance end section variables (σ α) lemma is_basis_monomials [field α] : is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) := suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)), begin apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩), split, { intros x y hxy, simpa using hxy }, { intros x, rcases x with ⟨x₁, x₂⟩, use x₁, rw punit_eq punit.star x₂ } end, begin apply finsupp.is_basis_single (λ _ _, (1 : α)), intro _, apply is_basis_singleton_one, end end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [field α] open_locale classical lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) := by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim] end mv_polynomial namespace mv_polynomial variables (σ : Type*) (R : Type*) [comm_ring R] (p : ℕ) instance [char_p R p] : char_p (mv_polynomial σ R) p := { cast_eq_zero_iff := λ n, by rw [← C_eq_coe_nat, ← C_0, C_inj, char_p.cast_eq_zero_iff R p] } end mv_polynomial
3d4671f8e5902e9c8d6dc2957a90f2d5f442fc0e
a51edd9a1700339fa6dc7dc428eb5dfa3994b8bc
/src/misc/keyed_array.lean
4f410c92aa07c64d61aa5583fe7b23bbc0c383ce
[]
no_license
avigad/formal_logic
83f5c0534b3e9e7da53eff01bb82289daad65555
59d7fe7cb7a7927fb72d89d4fd40965bcd769349
refs/heads/master
1,585,302,642,116
1,541,000,469,000
1,541,000,469,000
146,376,915
1
1
null
null
null
null
UTF-8
Lean
false
false
1,645
lean
/- A keyed_array is an array of data, each with a string key. The array index acts as a unique id. The rbmap provides the inverse: given a key, it finds the index. -/ import data.list structure keyed_array (α : Type*) := (size : nat) (array : array size (string × α)) (rbmap : rbmap string nat) namespace keyed_array def read_key_safe {α : Type*} (k : keyed_array α) {i : nat} (h : i < k.size) := (k.array.read ⟨i, h⟩).1 def read_safe {α : Type*} (k : keyed_array α) {i : nat} (h : i < k.size) := (k.array.read ⟨i, h⟩).2 def read_key {α : Type*} (k : keyed_array α) (i : nat) : option string := if h : i < k.size then some (k.read_key_safe h) else none def read {α : Type*} (k : keyed_array α) (i : nat) : option α := if h : i < k.size then some (k.read_safe h) else none def find {α : Type*} (k : keyed_array α) (s : string) : option nat := k.rbmap.find s def is_sound {α : Type*} (k : keyed_array α) : Prop := (∀ i (h : i < k.size), k.find (k.read_key_safe h) = some i) ∧ (∀ s i, k.find s = some i → ∃ h : i < k.size, k.read_key_safe h = s) end keyed_array namespace list private def to_rbmap_aux {α : Type*} : ℕ → list (string × α) → rbmap string nat | n [] := mk_rbmap string nat | n ((k, d) :: l) := (to_rbmap_aux (n+1) l).insert k n private def to_rbmap {α : Type*} (l : list (string × α)) : rbmap string nat := to_rbmap_aux 0 l def to_keyed_array {α : Type*} (l : list (string × α)) : keyed_array α := ⟨l.length, l.to_array, to_rbmap l⟩ -- TODO: show this gives a sound keyed_array if there are no duplicates on the list. end list
bb9007b59e49f21d518999f5617f1e671c216ab9
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/ExamPractice/Exam-1-Practice.lean
c2b36419c5b8e62623cbcbbbfdf67e3d45769d7c
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
9,900
lean
/- Grading rubric. 7 points per question up to 100 max. Partial credit by subproblem. -/ /- Note: An incorrect answer above or below a correct answer can cause Lean to be unable to process the correct answer. If you are not able to complete a problem succesfully please comment out your incomplete answer so that we can see your work but so that your incomplete work does not cause problems for surrounding problems and answers. -/ /- PART I: Functions. Functions are an essential element of the language of predicate logic. In this section, you show that you understand how to define, use, and reason about functions in Lean. -/ /- 1. Study each of the following definitions, then answer the associated question about the types involved in these definitions. -/ -- Consider this function def f (n : ℕ) (s : string) := s /- a. What is it's return type? Answer: string -/ /- b. What is the type of (f 5)? Answer: string → string -/ #check f 5 /- c. What is the value of (f 0 "yay") "yay" -/ #eval f 0 "yay" /- d. What is the type of this function? nat → string → string -/ #check f /- 2. Define three functions called square, square', and square'', each of type ℕ to ℕ. Each function must return the square of the value to which it is applied. Write the first function in "C" style, the second using a tactic script, and the third using a lambda abstraction. Declare argument and return types explicitly in each case. -/ def square (n : ℕ) : ℕ := n^2 def square' (n : ℕ) : ℕ := begin exact n^2 end def square'' : ℕ → ℕ := λ n : ℕ, n^2 /- 3. Construct three proofs to test your function definitions. The first must use "lemma" to define a proof, called square_3_9, of the proposition that (square 3) equals 9. The second must use "theorem" to define a proof, called square'_4_16, of the proposition that square' applied to 4 reduces to 16. The third must prove that square'' 5 is equal to 25. This third proof must not use the equals sign, =, but must use "eq" instead to state the proposition to be proved. Hint on #3, sometimes you need to use parentheses to express how you want terms to be grouped. -/ lemma square_3_9 : square 3 = 9 := rfl theorem square_4_16 : square' 4 = 16 := rfl example : eq (square'' 5) 25 := rfl /- 4. Define a function called last_first. It takes two string values, called "first" and "last" (without quotes), as arguments, and it returns a string consisting of "last" followed by a comma and a space followed by "first". For example (first "Orson" "Welles"). Write a test case for your function to prove that (last_first "Orson" "Welles") is "Welles, Orson". Use "example", to check the proof. Hint: The ++ operator implements the string append function. -/ def last_first (first last : string) := last ++ ", " ++ first example: (last_first "Orson" "Welles") = "Welles, Orson" := rfl /- 5. Complete the following definition of a function, called apply3. It takes, as an argument, a function, you might call it f, of type ℕ → ℕ. It must return a function, also of type ℕ to ℕ, that, when applied to a value, n, returns the result of applying the given function, f, to the given value, n, three times. That is, it returns a function that computes f(f(f(n))). -/ def apply3 : (ℕ → ℕ) → (ℕ → ℕ) := λ f : (ℕ → ℕ), λ n, f (f (f n)) -- Just an extra sanity check, not required #reduce apply3 (λ n, n^2) 2 /- 6. The Lean libraries define a function, string.length, that takes a string and returns its length as a natural number. Define a function, len2, that takes two strings and returns the sum of their lengths. You may use the ++ operator but not the + operator in your answer. Follow your function definition with a test case in the form of a proof using "example" showing that len2 applied to "Orson" and "Welles" is 11. -/ def len2 (s1 s2 : string) : ℕ := string.length (s1 ++ s2) example : len2 "Orson" "Welles" = 11 := rfl /- 7. Use "example" to prove that there is a function of the following type: ((ℕ → ℕ) → (ℕ → ℕ)) → ((ℕ → ℕ) → ℕ) → ((ℕ → ℕ) → ℕ) -/ example : ((ℕ → ℕ) → (ℕ → ℕ)) → ((ℕ → ℕ) → ℕ) → ((ℕ → ℕ) → ℕ) := λ f g, g /- PART II: Functions, revited. In mathematics, functions play a central role. A function, f, in the mathematical sense is a triple, f = { D, P, C }, where D, a set, is the domain of definition of f, C is the co-domain of f, and P is a set of ordered pairs, each with a first element from D and a second element from C,. In addition, P has one additional essential property, the subject of one of the following questions. -/ /- 8. What one additional property is essential to the definition of what it means for a triple, { D, P, C } to be a function? Name the property. Answer: Single-Valued Now explain precisely what it means: "That there are no two pairs, (x, y) and (x', y') such that..." Fill in the blank, and use a logical ∧ in answering. You might also want to use = or ≠. Answer: x = x' ∧ y ≠ y' -/ /- 9. Give names to the following concepts: The set of all values appearing as the first element of any pair in P. Answer: domain The set of all values appearing as the second element of any pair in P. Answer: range The property that the set of all values appearing as the first element of P is the same as D. Answer: total Answer: The property that the set of all values appearing as the first element of P is the same as C. Answer: surjective The property of having both of the preceding properties. Answer: bijective -/ /- 10. What does it mean for a function, f, to be injective? Give you answer by completing the following sentences with logical expressions. "A function, f, is said to be injective if it has no two pairs, (x, y) and (x', y'), such that ..." Answer: x ≠ x' ∧ y = y' In other words, "If (x, y) and (x', y') are related by f and x ≠ x' then ..." Answer: y ≠ y' -/ /- 11. Suppose that S and T are types and that f is defined to be a function, *in Lean*, of type S → T. Which of the following properties, if any, does f necessarily have? - N: injective - N: surjective - N: bijective - N: one-to-many - N: one-to-one - N: onto - Y: single-valued - Y: partial (but not strictly partial) - Y: total Answer: single valued, total, partial (if we define partial functions to include total functions) -/ /- PART III: Logic and Proof. -/ /- 12a. Use axiom and/or axioms in Lean to express, in formal logic, the following assumptions: - T is a type - t1 and t2 are values of type T - t1 = t2 Answer immediately after this comment block. If you need to introduce a name, use eqt1t2. -/ axiom T : Type axioms t1 t2 : T axiom eqt1t2 : t1 = t2 /- 12b. Use axiom or axioms to represent the additional assumptions that - P is a property of objects of type T - t1 has property P If you need to use a name, use Pt1 -/ axiom P : T → Prop axiom Pt1 : P t1 /- 12 c. Now use "example" to assert, and then prove, that t2 also has property P. -/ example : P t2 := eq.subst eqt1t2 Pt1 /- 13 a. Define eq_1_0 to be the proposition, 1 = 0. -/ def eq_1_0 := 1 = 0 /- 13 b. Define pf_eq_0_0 to be a proof of the proposition that 0 = 0. Use the lemma keyword. -/ lemma pf_eq_0_0 : 0 = 0 := rfl /- 13 c. Write a function, w, that takes three values, a, b, and c of type ℕ, and that also takes proofs, cb : c = b, and ba : b = a, and that returns a proof that a = c. -/ def w (a b c : ℕ) (cb : c = b) (ba : b = a) : a = c := eq.trans (eq.symm ba) (eq.symm cb) #check w /- 13d. What is the type of this function? Answer: ∀ (a b c : ℕ), c = b → b = a → a = c What is the form of this proposition? Answer: universal generalization What's the form the proposition after the comma? Answer: Implication What is the premise of the proposition after the comma? Answer: c = b -/ /- 14. Complete the following proofs. Give each one in the form indicate by a comment preceding the statement of the conjecture to be proved. When using tactic scripts, remember to write begin/end pairs right away, so Lean knowns you want to use a tactic script. -/ -- lambda expression example : ∀ (s : string), s = s := λ s, eq.refl s -- lambda expresion example : ∀ (n : ℕ), ∀ (m : ℕ), true := λ n m, true.intro -- tactic script example : ∀ (T : Type), ∀ (t : T), eq t t := begin assume T t, exact eq.refl t end -- tactic script example : ∀ (T : Type), ∀ (P : T → Prop), ∀ t1 t2 : T, ∀ Pt1 : P t1, ∀ t2t1 : t2 = t1, P t2 := begin assume T P t1 t2 Pt1 t2t1, exact eq.subst (eq.symm t2t1) Pt1 end /- The following problems involve implications. For example, false → P in an implication. To prove an implication, just show that there is (by giving) a function of the specified type. -/ -- lambda expression example : ∀ (P : Prop), false → P := λ P, λ f, false.elim f -- tactic script example : ∀ (P : Prop), false → P := begin assume P f, exact false.elim f end -- lambda expression example : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := λ P Q pq, and.intro pq.right pq.left -- tactic script example : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q pq, exact and.intro pq.right pq.left end -- tactic script example : ∀ T : Type, ∀ (t1 t2 t3 : T), t1 = t2 ∧ t2 = t3 → t1 = t3 := begin assume T t1 t2 t3 p, exact eq.trans p.left p.right end /- 15. Use Lean to model a world in which there are Dogs, all Dogs are friendly, and Fido is a Dog, then give a proof that in this world, Fido must be friendly, too. -/ axioms Dog : Type axiom Fido : Dog axiom Friendly : Dog → Prop axiom allFriendly : ∀ d : Dog, Friendly d -- proof is by application of forall elimination example : Friendly Fido := allFriendly Fido
cd5de459a053a5c7f9e472f2ab1dcb715d4efe2d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/set/intervals/image_preimage.lean
bab08e24fcdd84a48295bc65caf261d9719a52df
[ "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
20,625
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import data.set.intervals.basic import data.equiv.mul_add import algebra.pointwise /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ universe u namespace set section has_exists_add_of_le /-! The lemmas in this section state that addition maps intervals bijectively. The typeclass `has_exists_add_of_le` is defined specifically to make them work when combined with `ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all `ordered_add_comm_group`, but also to `ℕ` and `ℝ≥0`, which are not groups. TODO : move as much as possible in this file to the setting of this weaker typeclass. -/ variables {α : Type u} [ordered_cancel_add_comm_monoid α] [has_exists_add_of_le α] (a b d : α) lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_lt_add_right h.1 _, add_le_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1.le, rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) := begin refine ⟨λ _ h, ⟨add_le_add_right h.1 _, add_lt_add_right h.2 _⟩, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le h.1, rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) := begin refine ⟨λ x h, add_le_add_right (mem_Ici.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ici.mp h), rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) := begin refine ⟨λ x h, add_lt_add_right (mem_Ioi.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, obtain ⟨c, rfl⟩ := exists_add_of_le (mem_Ioi.mp h).le, rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h, exact ⟨a + c, h, by rw add_right_comm⟩, end end has_exists_add_of_le section ordered_add_comm_group variables {G : Type u} [ordered_add_comm_group G] (a b c : G) /-! ### Preimages under `x ↦ a + x` -/ @[simp] lemma preimage_const_add_Ici : (λ x, a + x) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add'.symm @[simp] lemma preimage_const_add_Ioi : (λ x, a + x) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add'.symm @[simp] lemma preimage_const_add_Iic : (λ x, a + x) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le'.symm @[simp] lemma preimage_const_add_Iio : (λ x, a + x) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt'.symm @[simp] lemma preimage_const_add_Icc : (λ x, a + x) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_const_add_Ico : (λ x, a + x) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_const_add_Ioc : (λ x, a + x) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_const_add_Ioo : (λ x, a + x) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] lemma preimage_add_const_Ici : (λ x, x + a) ⁻¹' (Ici b) = Ici (b - a) := ext $ λ x, sub_le_iff_le_add.symm @[simp] lemma preimage_add_const_Ioi : (λ x, x + a) ⁻¹' (Ioi b) = Ioi (b - a) := ext $ λ x, sub_lt_iff_lt_add.symm @[simp] lemma preimage_add_const_Iic : (λ x, x + a) ⁻¹' (Iic b) = Iic (b - a) := ext $ λ x, le_sub_iff_add_le.symm @[simp] lemma preimage_add_const_Iio : (λ x, x + a) ⁻¹' (Iio b) = Iio (b - a) := ext $ λ x, lt_sub_iff_add_lt.symm @[simp] lemma preimage_add_const_Icc : (λ x, x + a) ⁻¹' (Icc b c) = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_add_const_Ico : (λ x, x + a) ⁻¹' (Ico b c) = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_add_const_Ioc : (λ x, x + a) ⁻¹' (Ioc b c) = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_add_const_Ioo : (λ x, x + a) ⁻¹' (Ioo b c) = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ λ x, le_neg @[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ λ x, neg_le @[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ λ x, lt_neg @[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ λ x, neg_lt @[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] lemma preimage_sub_const_Ici : (λ x, x - a) ⁻¹' (Ici b) = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioi : (λ x, x - a) ⁻¹' (Ioi b) = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iic : (λ x, x - a) ⁻¹' (Iic b) = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Iio : (λ x, x - a) ⁻¹' (Iio b) = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Icc : (λ x, x - a) ⁻¹' (Icc b c) = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ico : (λ x, x - a) ⁻¹' (Ico b c) = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioc : (λ x, x - a) ⁻¹' (Ioc b c) = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] lemma preimage_sub_const_Ioo : (λ x, x - a) ⁻¹' (Ioo b c) = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] lemma preimage_const_sub_Ici : (λ x, a - x) ⁻¹' (Ici b) = Iic (a - b) := ext $ λ x, le_sub @[simp] lemma preimage_const_sub_Iic : (λ x, a - x) ⁻¹' (Iic b) = Ici (a - b) := ext $ λ x, sub_le @[simp] lemma preimage_const_sub_Ioi : (λ x, a - x) ⁻¹' (Ioi b) = Iio (a - b) := ext $ λ x, lt_sub @[simp] lemma preimage_const_sub_Iio : (λ x, a - x) ⁻¹' (Iio b) = Ioi (a - b) := ext $ λ x, sub_lt @[simp] lemma preimage_const_sub_Icc : (λ x, a - x) ⁻¹' (Icc b c) = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] lemma preimage_const_sub_Ico : (λ x, a - x) ⁻¹' (Ico b c) = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioc : (λ x, a - x) ⁻¹' (Ioc b c) = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] lemma preimage_const_sub_Ioo : (λ x, a - x) ⁻¹' (Ioo b c) = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ @[simp] lemma image_const_add_Ici : (λ x, a + x) '' Ici b = Ici (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iic : (λ x, a + x) '' Iic b = Iic (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Iio : (λ x, a + x) '' Iio b = Iio (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Ioi : (λ x, a + x) '' Ioi b = Ioi (a + b) := by simp [add_comm] @[simp] lemma image_const_add_Icc : (λ x, a + x) '' Icc b c = Icc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ico : (λ x, a + x) '' Ico b c = Ico (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioc : (λ x, a + x) '' Ioc b c = Ioc (a + b) (a + c) := by simp [add_comm] @[simp] lemma image_const_add_Ioo : (λ x, a + x) '' Ioo b c = Ioo (a + b) (a + c) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ @[simp] lemma image_add_const_Ici : (λ x, x + a) '' Ici b = Ici (b + a) := by simp @[simp] lemma image_add_const_Iic : (λ x, x + a) '' Iic b = Iic (b + a) := by simp @[simp] lemma image_add_const_Iio : (λ x, x + a) '' Iio b = Iio (b + a) := by simp @[simp] lemma image_add_const_Ioi : (λ x, x + a) '' Ioi b = Ioi (b + a) := by simp @[simp] lemma image_add_const_Icc : (λ x, x + a) '' Icc b c = Icc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ico : (λ x, x + a) '' Ico b c = Ico (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioc : (λ x, x + a) '' Ioc b c = Ioc (b + a) (c + a) := by simp @[simp] lemma image_add_const_Ioo : (λ x, x + a) '' Ioo b c = Ioo (b + a) (c + a) := by simp /-! ### Images under `x ↦ -x` -/ lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] lemma image_const_sub_Ici : (λ x, a - x) '' Ici b = Iic (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iic : (λ x, a - x) '' Iic b = Ici (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioi : (λ x, a - x) '' Ioi b = Iio (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Iio : (λ x, a - x) '' Iio b = Ioi (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Icc : (λ x, a - x) '' Icc b c = Icc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ico : (λ x, a - x) '' Ico b c = Ioc (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioc : (λ x, a - x) '' Ioc b c = Ico (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] @[simp] lemma image_const_sub_Ioo : (λ x, a - x) '' Ioo b c = Ioo (a - c) (a - b) := by simp [sub_eq_add_neg, image_comp (λ x, a + x) (λ x, -x)] /-! ### Images under `x ↦ x - a` -/ @[simp] lemma image_sub_const_Ici : (λ x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iic : (λ x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioi : (λ x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Iio : (λ x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Icc : (λ x, x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ico : (λ x, x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioc : (λ x, x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] lemma image_sub_const_Ioo : (λ x, x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) := begin refine ⟨λ x h, add_le_add_right (mem_Iic.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) := begin refine ⟨λ x h, add_lt_add_right (mem_Iio.mp h) _, λ _ _ _ _ h, add_right_cancel h, λ _ h, _⟩, simpa [add_comm a] using h, end end ordered_add_comm_group /-! ### Multiplication and inverse in a field -/ section linear_ordered_field variables {k : Type u} [linear_ordered_field k] @[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff h).symm @[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff h).symm @[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff h).symm @[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff h).symm @[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iio a) = Ioi (a / c) := ext $ λ x, (div_lt_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioi a) = Iio (a / c) := ext $ λ x, (lt_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Iic a) = Ici (a / c) := ext $ λ x, (div_le_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ici a) = Iic (a / c) := ext $ λ x, (le_div_iff_of_neg h).symm @[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) : (λ x, x * c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iio a) = Iio (a / c) := ext $ λ x, (lt_div_iff' h).symm @[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioi a) = Ioi (a / c) := ext $ λ x, (div_lt_iff' h).symm @[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Iic a) = Iic (a / c) := ext $ λ x, (le_div_iff' h).symm @[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ici a) = Ici (a / c) := ext $ λ x, (div_le_iff' h).symm @[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioo a b) = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ioc a b) = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Ico a b) = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) : ((*) c) ⁻¹' (Icc a b) = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iio a) = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioi a) = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Iic a) = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ici a) = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioo a b) = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ioc a b) = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Ico a b) = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) : ((*) c) ⁻¹' (Icc a b) = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_right_Icc {a b c : k} (hab : a ≤ b) (hc : 0 ≤ c) : (λ x, x * c) '' Icc a b = Icc (a * c) (b * c) := begin cases eq_or_lt_of_le hc, { subst c, simp [(nonempty_Icc.2 hab).image_const] }, exact image_mul_right_Icc' a b ‹0 < c› end lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] } lemma image_mul_left_Icc {a b c : k} (ha : 0 ≤ a) (hbc : b ≤ c) : ((*) a) '' Icc b c = Icc (a * b) (a * c) := by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] } lemma image_mul_right_Ioo (a b : k) {c : k} (h : 0 < c) : (λ x, x * c) '' Ioo a b = Ioo (a * c) (b * c) := ((units.mk0 c h.ne').mul_right.image_eq_preimage _).trans (by simp [h, division_def]) lemma image_mul_left_Ioo {a : k} (h : 0 < a) (b c : k) : ((*) a) '' Ioo b c = Ioo (a * b) (a * c) := by { convert image_mul_right_Ioo b c h using 1; simp only [mul_comm _ a] } /-- The image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi a⁻¹ := begin ext x, exact ⟨λ ⟨y, ⟨hy0, hya⟩, hyx⟩, hyx ▸ (inv_lt_inv ha hy0).2 hya, λ h, ⟨x⁻¹, ⟨inv_pos.2 (lt_trans (inv_pos.2 ha) h), (inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 h⟩, inv_inv' x⟩⟩, end /-! ### Images under `x ↦ a * x + b` -/ @[simp] lemma image_affine_Icc' {a : k} (h : 0 < a) (b c d : k) : (λ x, a * x + b) '' Icc c d = Icc (a * c + b) (a * d + b) := begin suffices : (λ x, x + b) '' ((λ x, a * x) '' Icc c d) = Icc (a * c + b) (a * d + b), { rwa set.image_image at this, }, rw [image_mul_left_Icc' h, image_add_const_Icc], end end linear_ordered_field end set
38fc8349ca5da6e5975009b6f4c61a9a03b58dae
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/factorial/basic.lean
d9fe35f593f0477eae0dfb20d04739996404adda
[ "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,766
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, Yaël Dillies -/ import data.nat.basic import data.nat.pow /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## Main declarations * `nat.factorial`: The factorial. * `nat.asc_factorial`: The ascending factorial. Note that it runs from `n + 1` to `n + k` and *not* from `n` to `n + k - 1`. We might want to change that in the future. * `nat.desc_factorial`: The descending factorial. It runs from `n - k` to `n`. -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : ℕ → ℕ | 0 := 1 | (succ n) := succ n * factorial n localized "notation (name := nat.factorial) n `!`:10000 := nat.factorial n" in nat section factorial variables {m n : ℕ} @[simp] theorem factorial_zero : 0! = 1 := rfl @[simp] theorem factorial_succ (n : ℕ) : n.succ! = (n + 1) * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl @[simp] theorem factorial_two : 2! = 2 := rfl theorem mul_factorial_pred (hn : 0 < n) : n * (n - 1)! = n! := tsub_add_cancel_of_le (nat.succ_le_of_lt hn) ▸ rfl theorem factorial_pos : ∀ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n! ≠ 0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m! ∣ n! := begin induction n with n IH, { simp [nat.eq_zero_of_le_zero h] }, obtain rfl | hl := h.eq_or_lt, { simp }, exact (IH (le_of_lt_succ hl)).mul_left _, end theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) @[mono] theorem factorial_le {m n} (h : m ≤ n) : m! ≤ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m! * m.succ ^ n ≤ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := λ n m, factorial_le lemma factorial_lt (hn : 0 < n) : n! < m! ↔ n < m := begin refine ⟨λ h, not_le.mp $ λ hmn, not_le_of_lt h (factorial_le hmn), λ h, _⟩, have : ∀ {n}, 0 < n → n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], exact mul_pos hk k.factorial_pos }, induction h with k hnk ih generalizing hn, { exact this hn, }, { exact (ih hn).trans (this $ hn.trans $ lt_of_succ_le hnk) } end lemma one_lt_factorial : 1 < n! ↔ 1 < n := factorial_lt one_pos lemma factorial_eq_one : n! = 1 ↔ n ≤ 1 := begin refine ⟨λ h, _, by rintro (_ | _ | _); refl⟩, rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl end lemma factorial_inj (hn : 1 < n!) : n! = m! ↔ n = m := begin refine ⟨λ h, _, congr_arg _⟩, obtain hnm | rfl | hnm := lt_trichotomy n m, { rw [← factorial_lt $ pos_of_gt $ one_lt_factorial.mp hn, h] at hnm, cases lt_irrefl _ hnm }, { refl }, rw [h, one_lt_factorial] at hn, rw [←factorial_lt (lt_trans one_pos hn), h] at hnm, cases lt_irrefl _ hnm end lemma self_le_factorial : ∀ n : ℕ, n ≤ n! | 0 := zero_le_one | (k + 1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) lemma lt_factorial_self {n : ℕ} (hi : 3 ≤ n) : n < n! := begin rw [← succ_pred_eq_of_pos ((zero_lt_two.trans (lt.base 2)).trans_le hi), factorial_succ], exact lt_mul_of_one_lt_right ((pred n).succ_pos) ((one_lt_two.trans_le (le_pred_of_lt (succ_le_iff.mp hi))).trans_le (self_le_factorial _)), end lemma add_factorial_succ_lt_factorial_add_succ {i : ℕ} (n : ℕ) (hi : 2 ≤ i) : i + (n + 1)! < (i + n + 1)! := begin rw [factorial_succ (i + _), add_mul, one_mul], have : i ≤ i + n := le.intro rfl, exact add_lt_add_of_lt_of_le (this.trans_lt ((lt_mul_iff_one_lt_right (zero_lt_two.trans_le (hi.trans this))).mpr (lt_iff_le_and_ne.mpr ⟨(i + n).factorial_pos, λ g, nat.not_succ_le_self 1 ((hi.trans this).trans (factorial_eq_one.mp g.symm))⟩))) (factorial_le ((le_of_eq (add_comm n 1)).trans ((add_le_add_iff_right n).mpr (one_le_two.trans hi)))), end lemma add_factorial_lt_factorial_add {i n : ℕ} (hi : 2 ≤ i) (hn : 1 ≤ n) : i + n! < (i + n)! := begin cases hn, { rw factorial_one, exact lt_factorial_self (succ_le_succ hi) }, exact add_factorial_succ_lt_factorial_add_succ _ hi, end lemma add_factorial_succ_le_factorial_add_succ (i : ℕ) (n : ℕ) : i + (n + 1)! ≤ (i + (n + 1))! := begin obtain i2 | _ | i0 := le_or_lt 2 i, { exact (n.add_factorial_succ_lt_factorial_add_succ i2).le }, { rw [←add_assoc, factorial_succ (1 + n), add_mul, one_mul, add_comm 1 n], exact (add_le_add_iff_right _).mpr (one_le_mul (nat.le_add_left 1 n) (n + 1).factorial_pos) }, rw [le_zero_iff.mp (nat.succ_le_succ_iff.mp i0), zero_add, zero_add] end lemma add_factorial_le_factorial_add (i : ℕ) {n : ℕ} (n1 : 1 ≤ n) : i + n! ≤ (i + n)! := begin cases n1 with h, { exact self_le_factorial _ }, exact add_factorial_succ_le_factorial_add_succ i h, end lemma factorial_mul_pow_sub_le_factorial {n m : ℕ} (hnm : n ≤ m) : n! * n ^ (m - n) ≤ m! := begin suffices : n! * (n + 1) ^ (m - n) ≤ m!, { apply trans _ this, rw mul_le_mul_left, apply pow_le_pow_of_le_left (zero_le n) (le_succ n), exact factorial_pos n }, convert nat.factorial_mul_pow_le_factorial, exact (add_tsub_cancel_of_le hnm).symm, end end factorial /-! ### Ascending and descending factorials -/ section asc_factorial /-- `n.asc_factorial k = (n + k)! / n!` (as seen in `nat.asc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def asc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n + k + 1) * asc_factorial k @[simp] lemma asc_factorial_zero (n : ℕ) : n.asc_factorial 0 = 1 := rfl @[simp] lemma zero_asc_factorial (k : ℕ) : (0 : ℕ).asc_factorial k = k! := begin induction k with t ht, { refl }, rw [asc_factorial, ht, zero_add, nat.factorial_succ], end lemma asc_factorial_succ {n k : ℕ} : n.asc_factorial k.succ = (n + k + 1) * n.asc_factorial k := rfl lemma succ_asc_factorial (n : ℕ) : ∀ k, (n + 1) * n.succ.asc_factorial k = (n + k + 1) * n.asc_factorial k | 0 := by rw [add_zero, asc_factorial_zero, asc_factorial_zero] | (k + 1) := by rw [asc_factorial, mul_left_comm, succ_asc_factorial, asc_factorial, succ_add, ←add_assoc] /-- `n.asc_factorial k = (n + k)! / n!` but without ℕ-division. See `nat.asc_factorial_eq_div` for the version with ℕ-division. -/ theorem factorial_mul_asc_factorial (n : ℕ) : ∀ k, n! * n.asc_factorial k = (n + k)! | 0 := by rw [asc_factorial, add_zero, mul_one] | (k + 1) := by rw [asc_factorial_succ, mul_left_comm, factorial_mul_asc_factorial, ← add_assoc, factorial] /-- Avoid in favor of `nat.factorial_mul_asc_factorial` if you can. ℕ-division isn't worth it. -/ lemma asc_factorial_eq_div (n k : ℕ) : n.asc_factorial k = (n + k)! / n! := begin apply mul_left_cancel₀ n.factorial_ne_zero, rw factorial_mul_asc_factorial, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ le.intro rfl).symm end lemma asc_factorial_of_sub {n k : ℕ} (h : k < n) : (n - k) * (n - k).asc_factorial k = (n - (k + 1)).asc_factorial (k + 1) := begin set t := n - k.succ with ht, suffices h' : n - k = t.succ, by rw [←ht, h', succ_asc_factorial, asc_factorial_succ], rw [ht, succ_eq_add_one, ←tsub_tsub_assoc (succ_le_of_lt h) (succ_pos _), succ_sub_one], end lemma pow_succ_le_asc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1)^k ≤ n.asc_factorial k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw pow_succ, exact nat.mul_le_mul (nat.add_le_add_right le_self_add _) (pow_succ_le_asc_factorial k), end lemma pow_lt_asc_factorial' (n k : ℕ) : (n + 1)^(k + 2) < n.asc_factorial (k + 2) := begin rw pow_succ, exact nat.mul_lt_mul (nat.add_lt_add_right (nat.lt_add_of_pos_right succ_pos') 1) (pow_succ_le_asc_factorial n _) (pow_pos succ_pos' _), end lemma pow_lt_asc_factorial (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1)^k < n.asc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨⟨⟩⟩) | (k + 2) := λ _, pow_lt_asc_factorial' n k lemma asc_factorial_le_pow_add (n : ℕ) : ∀ (k : ℕ), n.asc_factorial k ≤ (n + k)^k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw [asc_factorial_succ, pow_succ], exact nat.mul_le_mul_of_nonneg_left ((asc_factorial_le_pow_add k).trans (nat.pow_le_pow_of_le_left (le_succ _) _)), end lemma asc_factorial_lt_pow_add (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → n.asc_factorial k < (n + k)^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨⟨⟩⟩) | (k + 2) := λ _, begin rw [asc_factorial_succ, pow_succ], refine nat.mul_lt_mul' le_rfl ((asc_factorial_le_pow_add n _).trans_lt (pow_lt_pow_of_lt_left (lt_add_one _) (succ_pos _))) (succ_pos _), end lemma asc_factorial_pos (n k : ℕ) : 0 < n.asc_factorial k := (pow_pos (succ_pos n) k).trans_le (pow_succ_le_asc_factorial n k) end asc_factorial section desc_factorial /-- `n.desc_factorial k = n! / (n - k)!` (as seen in `nat.desc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def desc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n - k) * desc_factorial k @[simp] lemma desc_factorial_zero (n : ℕ) : n.desc_factorial 0 = 1 := rfl @[simp] lemma desc_factorial_succ (n k : ℕ) : n.desc_factorial k.succ = (n - k) * n.desc_factorial k := rfl lemma zero_desc_factorial_succ (k : ℕ) : (0 : ℕ).desc_factorial k.succ = 0 := by rw [desc_factorial_succ, zero_tsub, zero_mul] @[simp] lemma desc_factorial_one (n : ℕ) : n.desc_factorial 1 = n := by rw [desc_factorial_succ, desc_factorial_zero, mul_one, tsub_zero] @[simp] lemma succ_desc_factorial_succ (n : ℕ) : ∀ k : ℕ, (n + 1).desc_factorial (k + 1) = (n + 1) * n.desc_factorial k | 0 := by rw [desc_factorial_zero, desc_factorial_one, mul_one] | (succ k) := by rw [desc_factorial_succ, succ_desc_factorial_succ, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma succ_desc_factorial (n : ℕ) : ∀ k, (n + 1 - k) * (n + 1).desc_factorial k = (n + 1) * n.desc_factorial k | 0 := by rw [tsub_zero, desc_factorial_zero, desc_factorial_zero] | (k + 1) := by rw [desc_factorial, succ_desc_factorial, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma desc_factorial_self : ∀ n : ℕ, n.desc_factorial n = n! | 0 := by rw [desc_factorial_zero, factorial_zero] | (succ n) := by rw [succ_desc_factorial_succ, desc_factorial_self, factorial_succ] @[simp] lemma desc_factorial_eq_zero_iff_lt {n : ℕ} : ∀ {k : ℕ}, n.desc_factorial k = 0 ↔ n < k | 0 := by simp only [desc_factorial_zero, nat.one_ne_zero, nat.not_lt_zero] | (succ k) := begin rw [desc_factorial_succ, mul_eq_zero, desc_factorial_eq_zero_iff_lt, lt_succ_iff, tsub_eq_zero_iff_le, lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp], exact λ h _, h, end alias desc_factorial_eq_zero_iff_lt ↔ _ desc_factorial_of_lt lemma add_desc_factorial_eq_asc_factorial (n : ℕ) : ∀ k : ℕ, (n + k).desc_factorial k = n.asc_factorial k | 0 := by rw [asc_factorial_zero, desc_factorial_zero] | (succ k) := by rw [nat.add_succ, succ_desc_factorial_succ, asc_factorial_succ, add_desc_factorial_eq_asc_factorial] /-- `n.desc_factorial k = n! / (n - k)!` but without ℕ-division. See `nat.desc_factorial_eq_div` for the version using ℕ-division. -/ theorem factorial_mul_desc_factorial : ∀ {n k : ℕ}, k ≤ n → (n - k)! * n.desc_factorial k = n! | n 0 := λ _, by rw [desc_factorial_zero, mul_one, tsub_zero] | 0 (succ k) := λ h, by { exfalso, exact not_succ_le_zero k h } | (succ n) (succ k) := λ h, by rw [succ_desc_factorial_succ, succ_sub_succ, ←mul_assoc, mul_comm (n - k)!, mul_assoc, factorial_mul_desc_factorial (nat.succ_le_succ_iff.1 h), factorial_succ] /-- Avoid in favor of `nat.factorial_mul_desc_factorial` if you can. ℕ-division isn't worth it. -/ lemma desc_factorial_eq_div {n k : ℕ} (h : k ≤ n) : n.desc_factorial k = n! / (n - k)! := begin apply mul_left_cancel₀ (factorial_ne_zero (n - k)), rw factorial_mul_desc_factorial h, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ nat.sub_le n k).symm, end lemma pow_sub_le_desc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1 - k)^k ≤ n.desc_factorial k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ, succ_sub_succ], exact nat.mul_le_mul_of_nonneg_left (le_trans (nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ _) _) k) (pow_sub_le_desc_factorial k)), end lemma pow_sub_lt_desc_factorial' {n : ℕ} : ∀ {k : ℕ}, k + 2 ≤ n → (n - (k + 1))^(k + 2) < n.desc_factorial (k + 2) | 0 := λ h, begin rw [desc_factorial_succ, pow_succ, pow_one, desc_factorial_one], exact nat.mul_lt_mul_of_pos_left (tsub_lt_self (lt_of_lt_of_le zero_lt_two h) zero_lt_one) (tsub_pos_of_lt h), end | (k + 1) := λ h, begin rw [desc_factorial_succ, pow_succ], refine nat.mul_lt_mul_of_pos_left ((nat.pow_le_pow_of_le_left (tsub_le_tsub_right (le_succ n) _) _).trans_lt _) (tsub_pos_of_lt h), rw succ_sub_succ, exact (pow_sub_lt_desc_factorial' ((le_succ _).trans h)), end lemma pow_sub_lt_desc_factorial {n : ℕ} : ∀ {k : ℕ}, 2 ≤ k → k ≤ n → (n + 1 - k)^k < n.desc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨⟨⟩⟩) | (k + 2) := λ _ h, by { rw succ_sub_succ, exact pow_sub_lt_desc_factorial' h } lemma desc_factorial_le_pow (n : ℕ) : ∀ (k : ℕ), n.desc_factorial k ≤ n^k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ], exact nat.mul_le_mul (nat.sub_le _ _) (desc_factorial_le_pow k), end lemma desc_factorial_lt_pow {n : ℕ} (hn : 1 ≤ n) : ∀ {k : ℕ}, 2 ≤ k → n.desc_factorial k < n^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨⟨⟩⟩) | (k + 2) := λ _, begin rw [desc_factorial_succ, pow_succ', mul_comm], exact nat.mul_lt_mul' (desc_factorial_le_pow _ _) (tsub_lt_self hn k.zero_lt_succ) (pow_pos hn _), end end desc_factorial end nat
76afff6ebf62725b1fa68825963cf5bf52b61d51
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/complex/circle.lean
66aebc42a9920a4a8324b405785cac0e2dc377d1
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,407
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.special_functions.exp import topology.continuous_function.basic import analysis.normed.field.unit_ball /-! # The circle This file defines `circle` to be the metric sphere (`metric.sphere`) in `ℂ` centred at `0` of radius `1`. We equip it with the following structure: * a submonoid of `ℂ` * a group * a topological group We furthermore define `exp_map_circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`, and show that this map is a group homomorphism. ## Implementation notes Because later (in `geometry.manifold.instances.sphere`) one wants to equip the circle with a smooth manifold structure borrowed from `metric.sphere`, the underlying set is `{z : ℂ | abs (z - 0) = 1}`. This prevents certain algebraic facts from working definitionally -- for example, the circle is not defeq to `{z : ℂ | abs z = 1}`, which is the kernel of `complex.abs` considered as a homomorphism from `ℂ` to `ℝ`, nor is it defeq to `{z : ℂ | norm_sq z = 1}`, which is the kernel of the homomorphism `complex.norm_sq` from `ℂ` to `ℝ`. -/ noncomputable theory open complex metric open_locale complex_conjugate /-- The unit circle in `ℂ`, here given the structure of a submonoid of `ℂ`. -/ def circle : submonoid ℂ := submonoid.unit_sphere ℂ @[simp] lemma mem_circle_iff_abs {z : ℂ} : z ∈ circle ↔ abs z = 1 := mem_sphere_zero_iff_norm lemma circle_def : ↑circle = {z : ℂ | abs z = 1} := set.ext $ λ z, mem_circle_iff_abs @[simp] lemma abs_coe_circle (z : circle) : abs z = 1 := mem_circle_iff_abs.mp z.2 lemma mem_circle_iff_norm_sq {z : ℂ} : z ∈ circle ↔ norm_sq z = 1 := by simp [complex.abs] @[simp] lemma norm_sq_eq_of_mem_circle (z : circle) : norm_sq z = 1 := by simp [norm_sq_eq_abs] lemma ne_zero_of_mem_circle (z : circle) : (z:ℂ) ≠ 0 := ne_zero_of_mem_unit_sphere z instance : comm_group circle := metric.sphere.comm_group @[simp] lemma coe_inv_circle (z : circle) : ↑(z⁻¹) = (z : ℂ)⁻¹ := rfl lemma coe_inv_circle_eq_conj (z : circle) : ↑(z⁻¹) = conj (z : ℂ) := by rw [coe_inv_circle, inv_def, norm_sq_eq_of_mem_circle, inv_one, of_real_one, mul_one] @[simp] lemma coe_div_circle (z w : circle) : ↑(z / w) = (z:ℂ) / w := circle.subtype.map_div z w /-- The elements of the circle embed into the units. -/ def circle.to_units : circle →* units ℂ := unit_sphere_to_units ℂ -- written manually because `@[simps]` was slow and generated the wrong lemma @[simp] lemma circle.to_units_apply (z : circle) : circle.to_units z = units.mk0 z (ne_zero_of_mem_circle z) := rfl instance : compact_space circle := metric.sphere.compact_space _ _ instance : topological_group circle := metric.sphere.topological_group /-- If `z` is a nonzero complex number, then `conj z / z` belongs to the unit circle. -/ @[simps] def circle.of_conj_div_self (z : ℂ) (hz : z ≠ 0) : circle := ⟨conj z / z, mem_circle_iff_abs.2 $ by rw [map_div₀, abs_conj, div_self (complex.abs.ne_zero hz)]⟩ /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`. -/ def exp_map_circle : C(ℝ, circle) := { to_fun := λ t, ⟨exp (t * I), by simp [exp_mul_I, abs_cos_add_sin_mul_I]⟩ } @[simp] lemma exp_map_circle_apply (t : ℝ) : ↑(exp_map_circle t) = complex.exp (t * complex.I) := rfl @[simp] lemma exp_map_circle_zero : exp_map_circle 0 = 1 := subtype.ext $ by rw [exp_map_circle_apply, of_real_zero, zero_mul, exp_zero, submonoid.coe_one] @[simp] lemma exp_map_circle_add (x y : ℝ) : exp_map_circle (x + y) = exp_map_circle x * exp_map_circle y := subtype.ext $ by simp only [exp_map_circle_apply, submonoid.coe_mul, of_real_add, add_mul, complex.exp_add] /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`, considered as a homomorphism of groups. -/ @[simps] def exp_map_circle_hom : ℝ →+ (additive circle) := { to_fun := additive.of_mul ∘ exp_map_circle, map_zero' := exp_map_circle_zero, map_add' := exp_map_circle_add } @[simp] lemma exp_map_circle_sub (x y : ℝ) : exp_map_circle (x - y) = exp_map_circle x / exp_map_circle y := exp_map_circle_hom.map_sub x y @[simp] lemma exp_map_circle_neg (x : ℝ) : exp_map_circle (-x) = (exp_map_circle x)⁻¹ := exp_map_circle_hom.map_neg x
423376fe19532ee90b643080024fb346391b8920
bf532e3e865883a676110e756f800e0ddeb465be
/data/list/basic.lean
4a6c3acc115ae69e813c294c6a70dbaa09e7e4d0
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
126,941
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive algebra.group logic.basic logic.function data.nat.basic data.option data.bool data.prod data.sigma open function nat namespace list universes u v w variables {α : Type u} {β : Type v} {γ : Type w} @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, by intro h; simp [h]⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ 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 mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih; simp at h; cases h with h h, { subst h, exact ⟨[], l, rfl⟩ }, { cases ih h with s e, cases e with t e, subst l, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {simp at h, contradiction }, {simp, simp at h, cases h with h h, {simp *}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {simp at h, contradiction}, {cases (eq_or_mem_of_mem_cons h) with h h, {existsi c, simp [h]}, {cases ih h with a ha, cases ha with ha₁ ha₂, existsi a, simp * }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp [join, @mem_join L, or_and_distrib_right, exists_or_distrib] 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⟩ /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp [subset_def, or_imp_distrib, forall_and_distrib] 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 app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ /- append -/ theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp [foldl], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp [foldr], rw H _} @[simp] lemma append_eq_nil (p q : list α) : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp /- join -/ attribute [simp] join @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; simp * /- repeat take drop -/ /-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [split_at, split_at_eq_take_drop n xs] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [take_append_drop n xs] -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_left_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_left' h rfl theorem append_right_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_right h rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := have b = a ∧ ∀ (x : α), x ∈ l → x = a, by simpa [or_imp_distrib, forall_and_distrib] using H, by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; simp [-add_comm, *] theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl /- concat -/ /-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁ with b l₁ ih; [simp, simp [ih]] @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp [*, concat] @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp [succ_eq_add_one] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := have aux : ∀ l₁ l₂, reverse_core l₁ (concat l₂ a) = concat (reverse_core l₁ l₂) a, by intros l₁; induction l₁; intros; rsimp, aux l nil theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := by simp @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; simp * @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; simp * theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.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 @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; simp * @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; simp * @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; simp [*, or_comm] @[elab_as_eliminator] theorem 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 }, { simp, exact H1 _ _ ih } 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, simp *, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := begin induction l with hd tl ih; rsimp, have haux : tl ++ [a] ≠ [], {apply append_ne_nil_of_ne_nil_right, contradiction}, simp * end theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp * @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head and tail -/ @[simp] theorem head_cons [h : inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [h : inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, simp} theorem cons_head_tail [h : inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, simp} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := have f a = g a, from h _ (mem_cons_self _ _), have map f l = map g l, from map_congr $ assume a', h _ ∘ mem_cons_of_mem _, show f a :: map f l = g a :: map g l, by simp [*] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; simp * theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; simp * @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; simp * @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; simp * theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; simp * theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; simp * theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end) @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; simp * theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by simp [list.bind]; induction l; simp [list.ret, join, *] @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := bind_ret_eq_map _ _ /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := 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; simp * }, { 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 reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih; simp, { exact sublist_app_of_sublist_left ih }, { exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by induction h; [apply sublist.refl, simp [*, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem 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] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih; simp [-add_comm], by_cases h : a = b; simp [h, -add_comm], { intro, contradiction }, { rw ← ih, exact ⟨succ_inj, congr_arg _⟩ } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih; simp [-add_comm, index_of_cons], by_cases h : a = b; simp [h, -add_comm, zero_le], exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_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_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (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_ge_len 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 _⟩ 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 theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))] theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp * @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, by simp); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ /-- Convert a list into an array (whose length is the length of `l`) -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /- nth tail operation -/ /-- Apply a function to the nth tail of `l`. `modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without using `f` if the index is larger than the length of the list. -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) 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 [h, mt succ_inj] 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 [update_nth_eq_modify_nth] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp [nth_modify_nth] @[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 [nth_modify_nth, h]; cases nth l n; refl theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp [update_nth_eq_modify_nth] 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 [update_nth_eq_modify_nth, h] /- take, drop -/ @[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by simp | (succ n) (succ m) nil := by simp | (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take] 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 _ _ 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] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp [update_nth] /- take_while -/ /-- Get the longest initial segment of the list whose members all satisfy `p`. `take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /- foldl, foldr, scanl, scanr -/ @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (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 [foldl_append] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp [foldr_append] @[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 [foldl_join] @[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 [foldr_join] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; simp [*, foldr] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp [foldr_eta l] /-- Fold a function `f` over the list from the left, returning the list of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp [scanr] section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp [foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr 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₂ := by simp | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp [ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc]; simp lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := by simp [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 /- sum -/ /-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/ @[to_additive list.sum] def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp [list.prod] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] 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 list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; simp [list.join, *] at * end monoid @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; simp [*, nat.mul_succ] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; simp * @[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] /- all & any, bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := by simp @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp [or_imp_distrib, forall_and_distrib] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x := by simp theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (by simp) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (by simp [xl]) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, simp [px] end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := by induction l with a l; simp [forall_and_distrib, *] theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp [all_iff_forall] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := by induction l with a l; simp [or_and_distrib_right, exists_or_distrib, *] theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- 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 pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; simp * 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; simp *; apply 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; simp * 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 ⟨a, m, rfl⟩, cases a, 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 [pmap_eq_map_attach] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; simp * /- find -/ section find variables (p : α → Prop) [decidable_pred p] /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 @[simp] theorem find_nil : find p [] = none := rfl @[simp] theorem find_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none {p : α → Prop} [h : decidable_pred p] {l : list α} : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, {simp}, by_cases p a; simp [h, IH] end @[simp] theorem find_some {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α} (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, assumption }, { exact IH H } end @[simp] theorem find_mem {p : α → Prop} [h : decidable_pred p] {l : list α} {a : α} (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, apply mem_cons_self }, { exact mem_cons_of_mem _ (IH H) } end end find /-- `indexes_of a l` is the list of all indexes of `a` in `l`. `indexes_of a [a, b, a, a] = [0, 2, 3]` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp [filter_map, h] theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {simp}, simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH] end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {simp}, by_cases pa : p a; simp [filter_map, option.guard, pa, IH] end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp [h, option.bind] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp [h, h', option.bind] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases p x; simp [h, option.guard, option.bind] end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, {simp}, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp [filter_map_cons_none _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp [filter_map_cons_some _ _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp [map_filter_map, H] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp [filter_map]; cases f a with b; simp [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp [pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain (not_mem_nil a) | (b::l) ain pa := if pb : p b then or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, by simp [pb, this]) (assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end) else or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb) (assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this]) @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l, {simp}, by_cases p a; simp [filter, *], show filter p l ≠ a :: l, intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp [-and.comm, eq_nil_iff_forall_not_mem, mem_filter] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [span, take_while, drop_while, pa, span_eq_take_drop l] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := by by_cases pa : p a; simp [take_while, drop_while, pa, take_while_append_drop l] /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l; [refl, by_cases (p x)]; simp [*, -add_comm] local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp [countp_eq_length_filter, length_pos_iff_exists_mem] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa using length_le_of_sublist (filter_sublist_filter s) end filter /- count -/ section count variable [decidable_eq α] /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count (a : α) : list α → nat := countp (eq a) @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := decidable.by_cases (assume : a = b, begin rw [count_cons, if_pos this, if_pos this] end) (assume : a ≠ b, begin rw [count_cons, if_neg this, if_neg this], reflexivity end) @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_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 := by simp @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa using count_le_of_sublist a h⟩ end count /- prefix, suffix, infix -/ /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] @[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp [h]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, by simp⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s 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 _ _ /-- `inits l` is the list of initial segments of `l`. `inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa, ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ /-- `tails l` is the list of terminal segments of `l`. `tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp [mem_tails s t]; exact show s = 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⟩ /- sublists -/ def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. `sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; simp! * theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; simp! * theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp [sublists'_aux_eq_sublists'] @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s; simp, { exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ (IH.1 h) }, { exact cons_sublist_cons _ (IH.1 h) }, { cases h with _ _ _ h s _ _ h, { exact or.inl (IH.2 h) }, { exact or.inr ⟨s, IH.2 h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp [-add_comm, *]; rw [← two_mul, mul_comm]; refl def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`. `sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp * theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp [sublists_aux], rw [IH₂, IH₁], congr_n 1, induction sublists_aux l cons with _ _ ih; simp * end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp [sublists_aux₁] | (a::l₁) l₂ f := by simp [sublists_aux₁]; rw [sublists_aux₁_append]; simp theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp [sublists_aux₁_append, sublists_aux₁] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := by simp [sublists_aux₁] | (a::l) f g := by simp [sublists_aux₁]; rw [sublists_aux₁_bind]; simp theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp [sublists, sublists_aux_cons_eq_sublists_aux₁], rw [sublists_aux₁_append, sublists_aux₁_bind], congr, funext x, simp, rw [← bind_ret_eq_map, sublists_aux₁_bind], simp [list.ret] end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp [sublists_aux_cons_append, sublists, map_id'] @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by simp [sublists_append]; rw [sublists, sublists_aux_cons_eq_sublists_aux₁]; simp [map_id', sublists_aux₁] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l; simp [(∘), *] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp [sublists_eq_sublists', map_id'] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro; simp [not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp [sublists_eq_sublists', length_sublists'] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp; exact ((append_sublist_append_left _).2 (singleton_sublist.2 $ mem_map.2 ⟨[], by simp [list.ret]⟩)).trans ((append_sublist_append_right _).2 IH) instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_prefix l₁ l₂) $ by rw [← h]; exact ⟨λ⟨t, te⟩, ⟨t, by rw [← te]; refl⟩, λ⟨t, te⟩, list.no_confusion te (λ_ te, ⟨t, te⟩)⟩ else is_false $ λ⟨t, te⟩, list.no_confusion te $ λh', absurd h' h -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ λ⟨t, te⟩, absurd te $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then if he : drop (len2 - len1) l₂ = l₁ then is_true $ ⟨take (len2 - len1) l₂, by rw [← he, take_append_drop]⟩ else is_false $ suffices length l₁ ≤ length l₂ → l₁ <:+ l₂ → drop (length l₂ - length l₁) l₂ = l₁, from λsuf, he (this hl suf), λ hl ⟨t, te⟩, append_inj_right' ((take_append_drop (length l₂ - length l₁) l₂).trans te.symm) (by simp; exact nat.sub_sub_self hl) else is_false $ λ⟨t, te⟩, hl $ show length l₁ ≤ length l₂, by rw [← te, length_append]; apply nat.le_add_left instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- transpose -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. `transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /- permutations -/ section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by simp [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 simp [permutations_aux, permutations_aux.rec, permutations] 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] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp [insert.def, h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp [insert.def, h] @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l; simp [h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; simp * @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by simp [h] @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by simp [h] end insert /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp [erase_cons] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp [erase_cons, h] @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by induction l with _ _ ih; [refl, simp [(ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons h)]] theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by induction l with b l ih; [cases h, { simp at h, by_cases e : b = a, { subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ }, { exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in ⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁, by rw h₂; refl, by simp [e, h₃]⟩ } }] @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl end theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂ | (x::xs) l₂ h := begin by_cases h' : x = a; simp [h'], rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h) end theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a | [] l₂ h := rfl | (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)] theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := if h : a ∈ l then match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp end else by simp [h] theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a | ._ ._ sublist.slnil := sublist.slnil | ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _ | ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head, erase_cons_head]; exact s else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _ 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 := ⟨mem_of_mem_erase, λ al, if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa [ab] using al end else by simp [h, al]⟩ theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by simp [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 [hb, mt mem_of_mem_erase hb] else by simp [ha, mt mem_of_mem_erase ha] 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₂ := by by_cases a ∈ l₁; simp [list.diff, h] 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 [diff_eq_foldl] end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp [zip_unzip l] /- 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 [enum] @[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 _ /- product -/ /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a @[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 [product, and.left_comm] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; simp [*, right_distrib] /- sigma -/ section variable {σ : α → Type*} /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a @[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 [sigma, and.left_comm] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (sigma l₁ l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; simp * end /- disjoint -/ section disjoint /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp [*, 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 by simp [e.symm]; by_cases h : a ∈ t ++ l₂; [existsi t, existsi a::t]; simp [h]; [apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s] theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (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 [or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp [eq_nil_iff_forall_not_mem]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := by cases l₂; simp [h, list.bag_inter] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp | (b::l₁) l₂ := by by_cases b ∈ l₂; simp [*, and_or_distrib_left]; by_cases ba : a = b; simp * theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise variable (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) attribute [simp] pairwise.nil variable {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; simp * theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; simp [*, or_imp_distrib, forall_and_distrib, and_assoc, and.left_comm] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp, by simp *; rw this theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp, induction l with a l IH; simp, cases e : f a with b; simp [e, IH], rw [filter_map_cons_some _ _ _ e], simp [IH], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, simp end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp [pairwise_append, IH, this], simp [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [simp, simpa [pairwise_append, IH] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { apply H.1, simp [nth_le_mem] }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end inductive lex (R : α → α → Prop) : list α → list α → Prop | nil {} (a l) : lex [] (a::l) | cons {} (a) {l l'} : lex l l' → lex (a::l) (a::l') | rel {a a'} (l l') : R a a' → lex (a::l) (a'::l') theorem lex_append_right (R : α → α → Prop) : ∀ {s₁ s₂} t, lex R s₁ s₂ → lex R s₁ (s₂ ++ t) | _ _ t (lex.nil a l) := lex.nil _ _ | _ _ t (lex.cons a h) := lex.cons _ (lex_append_right _ h) | _ _ t (lex.rel _ _ r) := lex.rel _ _ r theorem lex_append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := lex.cons _ (lex_append_left l) theorem lex.imp {R S : α → α → Prop} (H : ∀ a b, R a b → S a b) : ∀ l₁ l₂, lex R l₁ l₂ → lex S l₁ l₂ | _ _ (lex.nil a l) := lex.nil _ _ | _ _ (lex.cons a h) := lex.cons _ (lex.imp _ _ h) | _ _ (lex.rel _ _ r) := lex.rel _ _ (H _ _ r) theorem ne_of_lex_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (lex.cons a h) e := ne_of_lex_ne h (list.cons.inj e).2 | _ _ (lex.rel _ _ r) e := r (list.cons.inj e).1 theorem lex_ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨ne_of_lex_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply lex.nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply lex.cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact lex.rel _ _ ab } } end⟩ theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ (pairwise.nil _) := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp [pairwise_append, pairwise_map], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons _), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel _ _ (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this variable [decidable_rel R] instance decidable_pairwise (l : list α) : decidable (pairwise R l) := by induction l; simp; resetI; apply_instance /- pairwise reduct -/ /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {simp}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH; simp *, by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp [pw_filter_cons_of_pos h], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. `chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/ inductive chain : α → list α → Prop | nil (a : α) : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) attribute [simp] chain.nil variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp [*, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp * theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a; simp, simp at r, simp [r], show chain R b l, from IH r' end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {simp}, apply IH.cons _, simp [r], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp; resetI; apply_instance end chain /- no duplicates predicate -/ /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) section nodup @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp [nodup] theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {simp}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp [nodup_append, and.left_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp [nodup_append, not_or_distrib, and.left_comm, and_assoc] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp [nodup, eq_comm] instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH; simp [list.erase, list.filter], by_cases b = a; simp *, subst b, show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2, simpa only [eq_comm] using m end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp [nodup, pairwise_join, disjoint_left.symm] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, by simp] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa, λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (sigma l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : σ a₁), sigma.mk a₁ b₁ = x → b₁ ∈ l₂ a₁ → ∀ (b₂ : σ a₂), sigma.mk a₂ b₂ = x → b₂ ∉ l₂ a₂, by simpa [and_comm], λ b₁ e mb₁ b₂ e' mb₂, by subst e'; injection e; contradiction)⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by simp; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := by by_cases h' : a ∈ l; simp [h', h]; apply nodup_cons h' h theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, simp, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 (ne_of_lex_ne h))⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/ def erase_dup : list α → list α := pw_filter (≠) @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH; simp, rw ← IH, show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range -/ /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := by simp | s (n+1) := have m = s → m < s + (n + 1), from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l] theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil _ _ | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil _ | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := by simp | s (m+1) (n+1) h := by simp [nth_range' (s+1) (lt_of_add_lt_add_right h)] theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, by simp]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp [range_eq_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp [range_eq_range', zero_le] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp [range_eq_range', nth_range' _ h] theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] := by simp [range_eq_range', range'_concat] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n] @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp [iota_eq_reverse_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp [iota_eq_reverse_range', pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp [iota_eq_reverse_range', nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp [iota_eq_reverse_range', lt_succ_iff] @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp [enum, range_eq_range'] end list
84df0c95bfc8cfaeb6e128eff68f4eebe8e1011e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/hermitian.lean
d2d1767b917d4c0a76c9b710a479f81f3fe24d86
[ "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
8,393
lean
/- Copyright (c) 2022 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import analysis.inner_product_space.pi_L2 /-! # Hermitian matrices This file defines hermitian matrices and some basic results about them. ## Main definition * `matrix.is_hermitian` : a matrix `A : matrix n n α` is hermitian if `Aᴴ = A`. ## Tags self-adjoint matrix, hermitian matrix -/ namespace matrix variables {α β : Type*} {m n : Type*} {A : matrix n n α} open_locale matrix local notation `⟪`x`, `y`⟫` := @inner α (pi_Lp 2 (λ (_ : n), α)) _ x y section non_unital_semiring variables [non_unital_semiring α] [star_ring α] [non_unital_semiring β] [star_ring β] /-- A matrix is hermitian if it is equal to its conjugate transpose. On the reals, this definition captures symmetric matrices. -/ def is_hermitian (A : matrix n n α) : Prop := Aᴴ = A lemma is_hermitian.eq {A : matrix n n α} (h : A.is_hermitian) : Aᴴ = A := h @[ext] lemma is_hermitian.ext {A : matrix n n α} : (∀ i j, star (A j i) = A i j) → A.is_hermitian := by { intros h, ext i j, exact h i j } lemma is_hermitian.apply {A : matrix n n α} (h : A.is_hermitian) (i j : n) : star (A j i) = A i j := by { unfold is_hermitian at h, rw [← h, conj_transpose_apply, star_star, h] } lemma is_hermitian.ext_iff {A : matrix n n α} : A.is_hermitian ↔ ∀ i j, star (A j i) = A i j := ⟨is_hermitian.apply, is_hermitian.ext⟩ lemma is_hermitian_mul_conj_transpose_self [fintype n] (A : matrix n n α) : (A ⬝ Aᴴ).is_hermitian := by rw [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose] lemma is_hermitian_transpose_mul_self [fintype n] (A : matrix n n α) : (Aᴴ ⬝ A).is_hermitian := by rw [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose] lemma is_hermitian_conj_transpose_mul_mul [fintype m] {A : matrix m m α} (B : matrix m n α) (hA : A.is_hermitian) : (Bᴴ ⬝ A ⬝ B).is_hermitian := by simp only [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose, hA.eq, matrix.mul_assoc] lemma is_hermitian_mul_mul_conj_transpose [fintype m] {A : matrix m m α} (B : matrix n m α) (hA : A.is_hermitian) : (B ⬝ A ⬝ Bᴴ).is_hermitian := by simp only [is_hermitian, conj_transpose_mul, conj_transpose_conj_transpose, hA.eq, matrix.mul_assoc] lemma is_hermitian_add_transpose_self (A : matrix n n α) : (A + Aᴴ).is_hermitian := by simp [is_hermitian, add_comm] lemma is_hermitian_transpose_add_self (A : matrix n n α) : (Aᴴ + A).is_hermitian := by simp [is_hermitian, add_comm] @[simp] lemma is_hermitian_zero : (0 : matrix n n α).is_hermitian := conj_transpose_zero @[simp] lemma is_hermitian.map {A : matrix n n α} (h : A.is_hermitian) (f : α → β) (hf : function.semiconj f star star) : (A.map f).is_hermitian := (conj_transpose_map f hf).symm.trans $ h.eq.symm ▸ rfl lemma is_hermitian.transpose {A : matrix n n α} (h : A.is_hermitian) : Aᵀ.is_hermitian := by { rw [is_hermitian, conj_transpose, transpose_map], congr, exact h } @[simp] lemma is_hermitian_transpose_iff (A : matrix n n α) : Aᵀ.is_hermitian ↔ A.is_hermitian := ⟨by { intro h, rw [← transpose_transpose A], exact is_hermitian.transpose h }, is_hermitian.transpose⟩ lemma is_hermitian.conj_transpose {A : matrix n n α} (h : A.is_hermitian) : Aᴴ.is_hermitian := h.transpose.map _ $ λ _, rfl @[simp] lemma is_hermitian_conj_transpose_iff (A : matrix n n α) : Aᴴ.is_hermitian ↔ A.is_hermitian := ⟨by { intro h, rw [← conj_transpose_conj_transpose A], exact is_hermitian.conj_transpose h }, is_hermitian.conj_transpose⟩ @[simp] lemma is_hermitian.add {A B : matrix n n α} (hA : A.is_hermitian) (hB : B.is_hermitian) : (A + B).is_hermitian := (conj_transpose_add _ _).trans (hA.symm ▸ hB.symm ▸ rfl) @[simp] lemma is_hermitian.submatrix {A : matrix n n α} (h : A.is_hermitian) (f : m → n) : (A.submatrix f f).is_hermitian := (conj_transpose_submatrix _ _ _).trans (h.symm ▸ rfl) @[simp] lemma is_hermitian_submatrix_equiv {A : matrix n n α} (e : m ≃ n) : (A.submatrix e e).is_hermitian ↔ A.is_hermitian := ⟨λ h, by simpa using h.submatrix e.symm, λ h, h.submatrix _⟩ /-- The real diagonal matrix `diagonal v` is hermitian. -/ @[simp] lemma is_hermitian_diagonal [decidable_eq n] (v : n → ℝ) : (diagonal v).is_hermitian := diagonal_conj_transpose _ /-- A block matrix `A.from_blocks B C D` is hermitian, if `A` and `D` are hermitian and `Bᴴ = C`. -/ lemma is_hermitian.from_blocks {A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} (hA : A.is_hermitian) (hBC : Bᴴ = C) (hD : D.is_hermitian) : (A.from_blocks B C D).is_hermitian := begin have hCB : Cᴴ = B, {rw ← hBC, simp}, unfold matrix.is_hermitian, rw from_blocks_conj_transpose, congr; assumption end /-- This is the `iff` version of `matrix.is_hermitian.from_blocks`. -/ lemma is_hermitian_from_blocks_iff {A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} : (A.from_blocks B C D).is_hermitian ↔ A.is_hermitian ∧ Bᴴ = C ∧ Cᴴ = B ∧ D.is_hermitian := ⟨λ h, ⟨congr_arg to_blocks₁₁ h, congr_arg to_blocks₂₁ h, congr_arg to_blocks₁₂ h, congr_arg to_blocks₂₂ h⟩, λ ⟨hA, hBC, hCB, hD⟩, is_hermitian.from_blocks hA hBC hD⟩ end non_unital_semiring section semiring variables [semiring α] [star_ring α] [semiring β] [star_ring β] @[simp] lemma is_hermitian_one [decidable_eq n] : (1 : matrix n n α).is_hermitian := conj_transpose_one end semiring section ring variables [ring α] [star_ring α] [ring β] [star_ring β] @[simp] lemma is_hermitian.neg {A : matrix n n α} (h : A.is_hermitian) : (-A).is_hermitian := (conj_transpose_neg _).trans (congr_arg _ h) @[simp] lemma is_hermitian.sub {A B : matrix n n α} (hA : A.is_hermitian) (hB : B.is_hermitian) : (A - B).is_hermitian := (conj_transpose_sub _ _).trans (hA.symm ▸ hB.symm ▸ rfl) end ring section comm_ring variables [comm_ring α] [star_ring α] lemma is_hermitian.inv [fintype m] [decidable_eq m] {A : matrix m m α} (hA : A.is_hermitian) : A⁻¹.is_hermitian := by simp [is_hermitian, conj_transpose_nonsing_inv, hA.eq] @[simp] lemma is_hermitian_inv [fintype m] [decidable_eq m] (A : matrix m m α) [invertible A]: (A⁻¹).is_hermitian ↔ A.is_hermitian := ⟨λ h, by {rw [← inv_inv_of_invertible A], exact is_hermitian.inv h }, is_hermitian.inv⟩ lemma is_hermitian.adjugate [fintype m] [decidable_eq m] {A : matrix m m α} (hA : A.is_hermitian) : A.adjugate.is_hermitian := by simp [is_hermitian, adjugate_conj_transpose, hA.eq] end comm_ring section is_R_or_C open is_R_or_C variables [is_R_or_C α] [is_R_or_C β] /-- The diagonal elements of a complex hermitian matrix are real. -/ lemma is_hermitian.coe_re_apply_self {A : matrix n n α} (h : A.is_hermitian) (i : n) : (re (A i i) : α) = A i i := by rw [←eq_conj_iff_re, ←star_def, ←conj_transpose_apply, h.eq] /-- The diagonal elements of a complex hermitian matrix are real. -/ lemma is_hermitian.coe_re_diag {A : matrix n n α} (h : A.is_hermitian) : (λ i, (re (A.diag i) : α)) = A.diag := funext h.coe_re_apply_self /-- A matrix is hermitian iff the corresponding linear map is self adjoint. -/ lemma is_hermitian_iff_is_symmetric [fintype n] [decidable_eq n] {A : matrix n n α} : is_hermitian A ↔ linear_map.is_symmetric ((pi_Lp.linear_equiv 2 α (λ _ : n, α)).symm.conj A.to_lin' : module.End α (pi_Lp 2 _)) := begin rw [linear_map.is_symmetric, (pi_Lp.equiv 2 (λ _ : n, α)).symm.surjective.forall₂], simp only [linear_equiv.conj_apply, linear_map.comp_apply, linear_equiv.coe_coe, pi_Lp.linear_equiv_apply, pi_Lp.linear_equiv_symm_apply, linear_equiv.symm_symm], simp_rw [euclidean_space.inner_eq_star_dot_product, equiv.apply_symm_apply, to_lin'_apply, star_mul_vec, dot_product_mul_vec], split, { rintro (h : Aᴴ = A) x y, rw h }, { intro h, ext i j, simpa only [(pi.single_star i 1).symm, ← star_mul_vec, mul_one, dot_product_single, single_vec_mul, star_one, one_mul] using h (@pi.single _ _ _ (λ i, add_zero_class.to_has_zero α) i 1) (@pi.single _ _ _ (λ i, add_zero_class.to_has_zero α) j 1) } end end is_R_or_C end matrix
bf47e4bee48c3fb73bb098128612ffb3c8f91f61
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/measurable.lean
6bf30f1d2a32501a7cbdf99f0cf56042621ef2f8
[ "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
219
lean
open prod nat example (a b : nat) : size_of (a, true, bool.tt, (λ c d : nat, c + d), option.some b) = a + b := rfl example : size_of (pair (pair (pair (2:nat) true) (λ a : nat, a)) (option.some (3:nat))) = 5 := rfl
f1b74f388d8dadbb85bd5bd39eb092f76939e1d7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/logic/examples/negative.lean
e62fdf13430f0edf1f0d16bd7df4c513646ca5fd
[ "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
785
lean
/- This example demonstrates why allowing types such as inductive D : Type := | intro : (D → D) → D would make the system inconsistent -/ /- If we were allowed to form the inductive type inductive D : Type := | intro : (D → D) → D we would get the following -/ universe l -- The new type A axiom D : Type.{l} -- The constructor axiom introD : (D → D) → D -- The eliminator axiom recD : Π {C : D → Type}, (Π (f : D → D) (r : Π d, C (f d)), C (introD f)) → (Π (d : D), C d) -- We would also get a computational rule for the eliminator, but we don't need it for deriving the inconsistency. noncomputable definition id' : D → D := λd, d noncomputable definition v : D := introD id' theorem inconsistent : false := recD (λ f ih, ih v) v
d866331f1ab559f29a528543b9c95faf7b725cb9
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/restrict.lean
86846566a239710b69979197b90fdc0903ff0e18
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
12,965
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import measure_theory.measurable_space import measure_theory.measure_space import measure_theory.outer_measure namespace measure_theory namespace measure lemma inter_add_inter_compl {α:Type*} [measurable_space α] (μ : measure α) (s t : set α) (A2 : measurable_set s) (A1 : measurable_set t) : (μ (s ∩ t) + μ (s ∩ tᶜ)) = μ s := begin rw ← measure_union _ (measurable_set.inter A2 A1) (measurable_set.inter A2 (measurable_set.compl A1)), rw set.inter_union_compl, apply set.disjoint_of_subset (set.inter_subset_right s t) (set.inter_subset_right s tᶜ), apply @disjoint_compl_right (set α) t _, end lemma restrict_sub_eq_restrict_sub_restrict {Ω : Type*} [M : measurable_space Ω] (μ ν : measure Ω) {s : set Ω} (h_meas_s : measurable_set s) : (μ - ν).restrict s = (μ.restrict s) - (ν.restrict s) := begin repeat {rw sub_def}, have h_nonempty : {d | μ ≤ d + ν}.nonempty, { apply @set.nonempty_of_mem _ _ μ, simp, intros t h_meas, apply le_add_right (le_refl (μ t)) }, rw restrict_Inf_eq_Inf_restrict h_nonempty h_meas_s, have h_Inf_le_Inf : ∀ s' t' : set (measure Ω), (∀ b ∈ t', ∃ a ∈ s', a ≤ b) → Inf s' ≤ Inf t', { intros s' t' h, rw le_Inf_iff, intros b h_b_in_t', have h_exists_a := h b h_b_in_t', cases h_exists_a with a h_a, cases h_a with h_a_in_s' h_a_le_b, apply Inf_le_of_le h_a_in_s' h_a_le_b }, apply le_antisymm, { apply h_Inf_le_Inf, intros ν' h_ν'_in, simp at h_ν'_in, apply exists.intro (ν'.restrict s), split, { simp, apply exists.intro (ν' + (⊤ : measure_theory.measure Ω).restrict sᶜ), split, { rw [add_assoc, add_comm _ ν, ← add_assoc, measure_theory.measure.le_iff], intros t h_meas_t, have h_inter_inter_eq_inter : ∀ t' : set Ω , t ∩ t' ∩ t' = t ∩ t', { intro t', rw set.inter_eq_self_of_subset_left, apply set.inter_subset_right t t' }, have h_meas_t_inter_s : measurable_set (t ∩ s) := measurable_set.inter h_meas_t h_meas_s, rw [← inter_add_inter_compl μ t s h_meas_t h_meas_s, ← inter_add_inter_compl (ν' + ν + (⊤ : measure Ω).restrict sᶜ) t s h_meas_t h_meas_s], apply add_le_add _ _; rw add_apply, { have h_restrict : ∀ μ₂ : measure Ω, μ₂ (t ∩ s) = μ₂.restrict s (t ∩ s), { intro μ₂, rw [restrict_apply h_meas_t_inter_s], rw [(h_inter_inter_eq_inter s)] }, apply le_add_right _, rw [add_apply, h_restrict μ, h_restrict ν], apply h_ν'_in _ h_meas_t_inter_s }, cases (@set.eq_empty_or_nonempty _ (t ∩ sᶜ)) with h_inter_empty h_inter_nonempty, { simp [h_inter_empty] }, { have h_meas_inter_compl := measurable_set.inter h_meas_t (measurable_set.compl h_meas_s), rw [restrict_apply h_meas_inter_compl, h_inter_inter_eq_inter sᶜ], have h_mu_le_add_top : μ ≤ ν' + ν + ⊤, { rw add_comm, have h_le_top : μ ≤ ⊤ := le_top, apply (λ t₂ h_meas, le_add_right (h_le_top t₂ h_meas)) }, apply h_mu_le_add_top _ h_meas_inter_compl } }, { ext1 t h_meas_t, simp [restrict_apply h_meas_t, restrict_apply (measurable_set.inter h_meas_t h_meas_s), set.inter_assoc] } }, { apply restrict_le_self } }, { apply h_Inf_le_Inf, intros s h_s_in, cases h_s_in with t h_t, cases h_t with h_t_in h_t_eq, subst s, apply exists.intro (t.restrict s), split, { rw [set.mem_set_of_eq, ← restrict_add], apply restrict_mono (set.subset.refl _) h_t_in }, { apply le_refl _ } }, end lemma restrict_apply_self {α : Type*} [measurable_space α] (μ : measure α) {s : set α} (h_meas_s : measurable_set s) : (μ.restrict s) s = μ s := begin rw [restrict_apply h_meas_s, set.inter_self], end lemma sub_apply_eq_zero_of_restrict_le_restrict {Ω:Type*} [measurable_space Ω] (μ ν:measure_theory.measure Ω) (s:set Ω) (h_le : μ.restrict s ≤ ν.restrict s) (h_meas_s : measurable_set s) : (μ - ν) s = 0 := begin rw [← restrict_apply_self _ h_meas_s, restrict_sub_eq_restrict_sub_restrict, sub_eq_zero_of_le], repeat {simp [*]}, end end measure end measure_theory def measure_theory.finite_measure_of_le {Ω:Type*} [M:measurable_space Ω] (μ ν : measure_theory.measure Ω) [measure_theory.finite_measure ν] (H:μ ≤ ν): measure_theory.finite_measure μ := begin apply measure_theory.finite_measure.mk (lt_of_le_of_lt (H set.univ measurable_set.univ) _), apply measure_theory.measure_lt_top ν, end def measure_theory.finite_measure_restrict {Ω:Type*} [M:measurable_space Ω] (μ:measure_theory.measure Ω) [measure_theory.finite_measure μ] (S:set Ω): measure_theory.finite_measure (μ.restrict S) := begin have A1:= @measure_theory.measure.restrict_le_self Ω M μ S, apply measure_theory.finite_measure_of_le (μ.restrict S) μ A1, end --This works with EITHER ν or μ being finite, or even ν S < ⊤. lemma jordan_decomposition_junior_apply {Ω:Type*} [measurable_space Ω] (μ ν:measure_theory.measure Ω) (S:set Ω) [AX:measure_theory.finite_measure ν]: (ν.restrict S ≤ μ.restrict S) → (measurable_set S) → (μ - ν) S = μ S - ν S := begin intros A1 B1, rw ← measure_theory.measure.restrict_apply_self _ B1, rw measure_theory.measure.restrict_sub_eq_restrict_sub_restrict _ _, rw @measure_theory.measure.sub_apply Ω _ _ _ S (measure_theory.finite_measure_restrict ν S) B1 A1, repeat {rw measure_theory.measure.restrict_apply_self}, repeat {exact B1}, end lemma measure_theory.measure.restrict_apply_subset {α : Type*} [measurable_space α] (μ : measure_theory.measure α) {S T : set α} (h₁ : measurable_set S) (h₂ : S ⊆ T) : (μ.restrict T) S = μ S := begin rw measure_theory.measure.restrict_apply h₁, simp [set.inter_eq_self_of_subset_left, h₂], end lemma le_of_subset_of_restrict_le_restrict {α:Type*} [measurable_space α] {μ ν:measure_theory.measure α} {S T:set α}: T ⊆ S → (μ.restrict S) ≤ ν.restrict S → measurable_set S → measurable_set T → μ T ≤ ν T := begin intros A3 A2 A1 A4, rw measure_theory.measure.le_iff at A2, have B3 := A2 T A4, rw measure_theory.measure.restrict_apply_subset μ A4 A3 at B3, rw measure_theory.measure.restrict_apply_subset ν A4 A3 at B3, apply B3, end lemma restrict_le_restrict_of_restrict_le_restrict_of_subset {α:Type*} [measurable_space α] {μ ν:measure_theory.measure α} {X Y:set α}: μ.restrict X ≤ ν.restrict X → Y ⊆ X → measurable_set X → measurable_set Y → μ.restrict Y ≤ ν.restrict Y := begin intros A1 A2 A3 A4, rw measure_theory.measure.le_iff, intros S A5, rw measure_theory.measure.restrict_apply, rw measure_theory.measure.restrict_apply, have A6:S ∩ Y ⊆ X, {apply set.subset.trans _ A2, simp}, apply le_of_subset_of_restrict_le_restrict A6 A1 A3, repeat {simp [measurable_set.inter,*]}, end /-- A jordan decomposition of subtraction. -/ lemma jordan_decomposition_nonneg_sub {Ω:Type*} [M:measurable_space Ω] (μ ν:measure_theory.measure Ω) (S T:set Ω) [A1:measure_theory.finite_measure μ]: measurable_set T → measurable_set S → μ.restrict S ≤ ν.restrict S → ν.restrict Sᶜ ≤ μ.restrict Sᶜ → (ν - μ) T = ν (T ∩ S) - μ (T ∩ S) := begin intros A3 A2 A5 A6, rw ← measure_theory.measure.inter_add_inter_compl (ν - μ) _ _ A3 A2, rw jordan_decomposition_junior_apply ν μ (T ∩ S), rw measure_theory.measure.sub_apply_eq_zero_of_restrict_le_restrict ν μ (T ∩ Sᶜ), rw add_zero, apply @restrict_le_restrict_of_restrict_le_restrict_of_subset Ω M ν μ Sᶜ (T ∩ Sᶜ) A6, repeat {simp [A2, A3]}, apply @restrict_le_restrict_of_restrict_le_restrict_of_subset Ω M μ ν S (T ∩ S) A5, repeat {simp [A2, A3]}, end lemma restrict_le_restrict_of_le_subset {α:Type*} [measurable_space α] {μ ν:measure_theory.measure α} {S:set α} (H:measurable_set S): (∀ T:set α, T ⊆ S → measurable_set T → μ T ≤ ν T) → (μ.restrict S) ≤ ν.restrict S := begin intros A1, rw measure_theory.measure.le_iff, intros s A2, repeat {rw measure_theory.measure.restrict_apply A2}, apply A1, {simp}, {simp [measurable_set.inter,H,A2]}, end lemma restrict_le_restrict_union {α:Type*} [measurable_space α] {μ ν:measure_theory.measure α} {X Y:set α}: μ.restrict X ≤ ν.restrict X → μ.restrict Y ≤ ν.restrict Y → measurable_set X → measurable_set Y → μ.restrict (X ∪ Y) ≤ ν.restrict (X ∪ Y) := begin intros A1 A2 A3 A4, have A6:X ∪ (Y \ X) = X ∪ Y := set.union_diff_self, rw ← A6, have A7:disjoint X (Y \ X) := set.disjoint_diff, repeat {rw measure_theory.measure.restrict_union}, apply measure_theory.measure.add_le_add A1 _, apply restrict_le_restrict_of_restrict_le_restrict_of_subset A2, apply set.diff_subset, repeat {simp [set.disjoint_diff, measurable_set.inter, measurable_set.diff,*]}, end lemma set.directed_has_subset_of_monotone {α:Type*} {f:ℕ → set α}: monotone f → directed has_subset.subset f := begin intros A1, unfold directed, intros x y, apply exists.intro (max x y), split, { rw ← set.le_eq_subset, apply @A1 x (max x y), apply le_max_left, }, { rw ← set.le_eq_subset, apply @A1 y (max x y), apply le_max_right, }, end lemma restrict_le_restrict_m_Union {α:Type*} [measurable_space α] (μ ν:measure_theory.measure α) {f:ℕ → set α}: monotone f → (∀ n:ℕ, measurable_set (f n)) → (∀ n:ℕ, μ.restrict (f n) ≤ ν.restrict (f n)) → (μ.restrict (set.Union f) ≤ ν.restrict (set.Union f)) := begin intros A1 A2 A3 S A5, rw measure_theory.measure.restrict_Union_apply_eq_supr, rw measure_theory.measure.restrict_Union_apply_eq_supr, rw supr_le_iff, intro i, have B1:(μ.restrict (f i)) S ≤ (ν.restrict (f i)) S, {apply A3, apply A5}, apply le_trans B1, apply @le_supr ennreal _ _, repeat {simp [set.directed_has_subset_of_monotone,*]}, end lemma nnreal.add_sub_add_eq_sub_add_sub {a b c d:nnreal} : c ≤ a → d ≤ b → a + b - (c + d) = (a - c) + (b - d) := begin intros A1 A2, have A3:c + d ≤ a + b, { apply add_le_add A1 A2 }, repeat {rw ← nnreal.eq_iff <|> rw nnreal.coe_sub <|> rw nnreal.coe_add}, repeat {assumption}, linarith, end lemma ennreal.add_sub_add_eq_sub_add_sub {a b c d:ennreal}:c < ⊤ → d < ⊤ → c ≤ a → d ≤ b → a + b - (c + d) = (a - c) + (b - d) := begin cases c;cases b;cases a;cases d; simp [ennreal.top_sub_coe, ennreal.none_eq_top, ennreal.some_eq_coe, ennreal.add_top, ← ennreal.coe_add, ← ennreal.coe_sub], apply nnreal.add_sub_add_eq_sub_add_sub, end lemma le_measurable_add {α:Type*} [M:measurable_space α] (μ ν:measure_theory.measure α) {X Y:set α}: μ X < ⊤ → μ Y < ⊤ → measurable_set X → measurable_set Y → μ X ≤ ν X → μ Y ≤ ν Y → disjoint X Y → ν (X ∪ Y) - μ (X ∪ Y) = (ν X - μ X) + (ν Y - μ Y) := begin intros A1 A2 A3 A4 A5 A6 A7, repeat {rw measure_theory.measure_union A7 A3 A4}, rw ennreal.add_sub_add_eq_sub_add_sub A1 A2 A5 A6, end lemma measure_theory.measure.le_of_restrict_le_restrict_self {α:Type*} [measurable_space α] (μ ν:measure_theory.measure α) {S:set α} (H:measurable_set S): (μ.restrict S) ≤ ν.restrict S → μ S ≤ ν S := begin intro A1, apply le_of_subset_of_restrict_le_restrict (set.subset.refl S) A1 H H, end lemma restrict_le_restrict_add {α:Type*} [M:measurable_space α] (μ ν:measure_theory.measure α) {X Y:set α}: μ X < ⊤ → μ Y < ⊤ → measurable_set X → measurable_set Y → μ.restrict X ≤ ν.restrict X → μ.restrict Y ≤ ν.restrict Y → disjoint X Y → ν (X ∪ Y) - μ (X ∪ Y) = (ν X - μ X) + (ν Y - μ Y) := begin intros A1 A2 A3 A4 A5 A6 A7, apply le_measurable_add μ ν A1 A2 A3 A4 (measure_theory.measure.le_of_restrict_le_restrict_self _ _ A3 A5) (measure_theory.measure.le_of_restrict_le_restrict_self _ _ A4 A6) A7, end
dfe13acd4595a758fcc6798a0ee4ed4ae176dfad
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/lint/type_classes.lean
c8a778dacc12f76394c67b3ba6a36666328e3c07
[ "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
23,325
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_inhabited_instances` checks that every type has an `inhabited` 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 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 associated `inhabited` instance. -/ private meta def has_inhabited_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 inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances.", errors_found := "TYPES ARE MISSING INHABITED INSTANCES:", is_fast := ff } attribute [nolint has_inhabited_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 15000, 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 lsewhere 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 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 }
ed2b2ebfe726fcb784c97aaf086ea97d9cb24392
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/meta/quote.lean
78e9bbce5bd6450d78b152bf467a29f72c7732c7
[ "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
1,815
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.tactic open tactic meta class has_quote (α : Type) := (quote : α → pexpr) @[inline] meta def quote {α : Type} [has_quote α] : α → pexpr := has_quote.quote meta instance : has_quote bool := ⟨λ b, if b then ``(true) else ``(false)⟩ meta instance : has_quote nat := ⟨pexpr.mk_prenum_macro⟩ @[priority std.priority.default + 1] meta instance : has_quote string := ⟨pexpr.mk_string_macro⟩ meta instance : has_quote pexpr := ⟨pexpr.mk_quote_macro⟩ meta instance : has_quote char := ⟨λ ⟨n, pr⟩, ``(char.of_nat %%(quote n))⟩ meta instance : has_quote unsigned := ⟨λ ⟨n, pr⟩, ``(unsigned.of_nat' %%(quote n))⟩ meta instance : has_quote pos := ⟨λ ⟨l, c⟩, ``(pos.mk %%(quote l) %%(quote c))⟩ meta def name.quote : name → pexpr | name.anonymous := ``(name.anonymous) | (name.mk_string s n) := ``(name.mk_string %%(quote s) %%(name.quote n)) | (name.mk_numeral i n) := ``(name.mk_numeral %%(quote i) %%(name.quote n)) meta instance : has_quote name := ⟨name.quote⟩ private meta def list.quote {α : Type} [has_quote α] : list α → pexpr | [] := ``([]) | (h::t) := ``(%%(quote h) :: %%(list.quote t)) meta instance {α : Type} [has_quote α] : has_quote (list α) := ⟨list.quote⟩ meta instance {α : Type} [has_quote α] : has_quote (option α) := ⟨λ opt, match opt with | some x := ``(option.some %%(quote x)) | none := ``(option.none) end⟩ meta instance : has_quote unit := ⟨λ _, ``(unit.star)⟩ meta instance {α β : Type} [has_quote α] [has_quote β] : has_quote (α × β) := ⟨λ ⟨x, y⟩, ``((%%(quote x), %%(quote y)))⟩
a7bb0f727b04eb1170eb0b4989ab3e97ccb46b4c
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/topology/order.lean
d1a1c89e6b25dc29942735ca9a6c73820a3eed3a
[ "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
28,737
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 topology.tactic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot [] : t = ⊥) @[priority 100] instance discrete_topology_bot (α : Type*) : @discrete_topology α ⊥ := { eq_bot := rfl } @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := continuous_def.2 $ λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @mem_nhds_sets α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) lemma forall_open_iff_discrete {X : Type*} [topological_space X] : (∀ s : set X, is_open s) ↔ discrete_topology X := ⟨λ h, ⟨by { ext U , show is_open U ↔ true, simp [h U] }⟩, λ a, @is_open_discrete _ _ a⟩ lemma singletons_open_iff_discrete {X : Type*} [topological_space X] : (∀ a : X, is_open ({a} : set X)) ↔ discrete_topology X := ⟨λ h, ⟨eq_bot_of_singletons_open h⟩, λ a _, @is_open_discrete _ _ a _⟩ end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ f ⁻¹' t = s) := ⟨assume ⟨t, ht, heq⟩, ⟨tᶜ, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, compl_compl]⟩, assume ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma continuous.coinduced_le (h : @continuous α β t t' f) : t.coinduced f ≤ t' := λ s hs, (continuous_def.1 h s hs : _) lemma coinduced_le_iff_le_induced {f : α → β} {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma continuous.le_induced (h : @continuous α β t t' f) : t ≤ t'.induced f := coinduced_le_iff_le_induced.1 h.coinduced_le lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.unique_topological_space [subsingleton α] : unique (topological_space α) := { default := ⊥, uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] : discrete_topology α := ⟨unique.eq_default t⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space pempty := ⊥ instance : discrete_topology pempty := ⟨rfl⟩ instance : topological_space punit := ⊥ instance : discrete_topology punit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := continuous_def.trans iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := by { rw continuous_def, assume s h, exact ⟨_, h, rfl⟩ } lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := begin rw continuous_def, rintros s ⟨t, ht, s_eq⟩, simpa [← s_eq] using continuous_def.1 h t ht, end lemma continuous_induced_rng' [topological_space α] [topological_space β] [topological_space γ] {g : γ → α} (f : α → β) (H : ‹topological_space α› = ‹topological_space β›.induced f) (h : continuous (f ∘ g)) : continuous g := H.symm ▸ continuous_induced_rng h lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := by { rw continuous_def, assume s h, exact h } lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := begin rw continuous_def at h ⊢, assume s hs, exact h _ hs end lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₁ _ (h₂ s h) end lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₂ s (h₁ s h) end lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := begin rw continuous_def at h₁ h₂ ⊢, assume s h, exact ⟨h₁ s h, h₂ s h⟩ end lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i @[continuity] lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le @[continuity] lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := by { ext s, rw [mem_nhds_induced, mem_comap_sets] } lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq (a : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] (f a) := by rw [nhds_induced, filter.map_comap, nhds_within] lemma map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap_of_mem h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := by simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from is_open_singleton_true.preimage h, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ lemma is_open_iff_continuous_mem {s : set α} : is_open s ↔ continuous (λ x, x ∈ s) := continuous_Prop.symm end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := is_open_supr_iff end infi
d372aad4a64bc5288310289121017e50e56f0f20
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/prime_counting.lean
8a61f224fd7806aac850ac205188024fe1069ab0
[ "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,386
lean
/- Copyright (c) 2021 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import data.nat.prime import data.nat.totient import data.finset.locally_finite import data.nat.count import data.nat.nth /-! # The Prime Counting Function In this file we define the prime counting function: the function on natural numbers that returns the number of primes less than or equal to its input. ## Main Results The main definitions for this file are - `nat.prime_counting`: The prime counting function π - `nat.prime_counting'`: π(n - 1) We then prove that these are monotone in `nat.monotone_prime_counting` and `nat.monotone_prime_counting'`. The last main theorem `nat.prime_counting'_add_le` is an upper bound on `π'` which arises by observing that all numbers greater than `k` and not coprime to `k` are not prime, and so only at most `φ(k)/k` fraction of the numbers from `k` to `n` are prime. ## Notation We use the standard notation `π` to represent the prime counting function (and `π'` to represent the reindexed version). -/ namespace nat open finset /-- A variant of the traditional prime counting function which gives the number of primes *strictly* less than the input. More convenient for avoiding off-by-one errors. -/ def prime_counting' : ℕ → ℕ := nat.count prime /-- The prime counting function: Returns the number of primes less than or equal to the input. -/ def prime_counting (n : ℕ) : ℕ := prime_counting' (n + 1) localized "notation (name := prime_counting) `π` := nat.prime_counting" in nat localized "notation (name := prime_counting') `π'` := nat.prime_counting'" in nat lemma monotone_prime_counting' : monotone prime_counting' := count_monotone prime lemma monotone_prime_counting : monotone prime_counting := λ a b a_le_b, monotone_prime_counting' (add_le_add_right a_le_b 1) @[simp] lemma prime_counting'_nth_eq (n : ℕ) : π' (nth prime n) = n := count_nth_of_infinite _ infinite_set_of_prime _ @[simp] lemma prime_nth_prime (n : ℕ) : prime (nth prime n) := nth_mem_of_infinite _ infinite_set_of_prime _ /-- A linear upper bound on the size of the `prime_counting'` function -/ lemma prime_counting'_add_le {a k : ℕ} (h0 : 0 < a) (h1 : a < k) (n : ℕ) : π' (k + n) ≤ π' k + nat.totient a * (n / a + 1) := calc π' (k + n) ≤ ((range k).filter (prime)).card + ((Ico k (k + n)).filter (prime)).card : begin rw [prime_counting', count_eq_card_filter_range, range_eq_Ico, ←Ico_union_Ico_eq_Ico (zero_le k) (le_self_add), filter_union], apply card_union_le, end ... ≤ π' k + ((Ico k (k + n)).filter (prime)).card : by rw [prime_counting', count_eq_card_filter_range] ... ≤ π' k + ((Ico k (k + n)).filter (coprime a)).card : begin refine add_le_add_left (card_le_of_subset _) k.prime_counting', simp only [subset_iff, and_imp, mem_filter, mem_Ico], intros p succ_k_le_p p_lt_n p_prime, split, { exact ⟨succ_k_le_p, p_lt_n⟩, }, { rw coprime_comm, exact coprime_of_lt_prime h0 (gt_of_ge_of_gt succ_k_le_p h1) p_prime, }, end ... ≤ π' k + totient a * (n / a + 1) : begin rw [add_le_add_iff_left], exact Ico_filter_coprime_le k n h0, end end nat
26fbac85982f1ebdad97efec32a153d8b3dafdc5
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/module/pi.lean
4adf5a3c12e0899416a8a2782b68d819fe226410
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,524
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.module.basic import algebra.regular.smul import algebra.ring.pi /-! # Pi instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on Pi Types -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ lemma smul_def {α : Type*} [Π i, has_scalar α $ f i] (s : α) : s • x = λ i, s • x i := rfl @[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl lemma _root_.is_smul_regular.pi {α : Type*} [Π i, has_scalar α $ f i] {k : α} (hk : Π i, is_smul_regular (f i) k) : is_smul_regular (Π i, f i) k := λ _ _ h, funext $ λ i, hk i (congr_fun h i : _) instance is_scalar_tower {α β : Type*} [has_scalar α β] [Π i, has_scalar β $ f i] [Π i, has_scalar α $ f i] [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩ instance is_scalar_tower' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar (f i) (g i)] [Π i, has_scalar α $ g i] [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩ instance is_scalar_tower'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (f i) (g i)] [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩ instance smul_comm_class {α β : Type*} [Π i, has_scalar α $ f i] [Π i, has_scalar β $ f i] [∀ i, smul_comm_class α β (f i)] : smul_comm_class α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩ instance smul_comm_class' {g : I → Type*} {α : Type*} [Π i, has_scalar α $ g i] [Π i, has_scalar (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] : smul_comm_class α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩ instance smul_comm_class'' {g : I → Type*} {h : I → Type*} [Π i, has_scalar (g i) (h i)] [Π i, has_scalar (f i) (h i)] [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩ /-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is not an instance as `i` cannot be inferred. -/ lemma has_faithful_scalar_at {α : Type*} [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_scalar α (f i)] : has_faithful_scalar α (Π i, f i) := ⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin classical, have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i, simpa using this, end⟩ instance has_faithful_scalar {α : Type*} [nonempty I] [Π i, has_scalar α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_scalar α (f i)] : has_faithful_scalar α (Π i, f i) := let ⟨i⟩ := ‹nonempty I› in has_faithful_scalar_at i instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } lemma single_smul {α} [monoid α] [Π i, add_monoid $ f i] [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) : single i (r • x) = r • single i x := single_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _ lemma single_smul' {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)] [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) : single i (r • x) = single i r • single i x := single_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _ variables (I f) instance module (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, module α $ f i] : @module α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance module' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, module (f i) (g i)] : module (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } instance (α) {r : semiring α} {m : Π i, add_comm_monoid $ f i} [Π i, module α $ f i] [∀ i, no_zero_smul_divisors α $ f i] : no_zero_smul_divisors α (Π i : I, f i) := ⟨λ c x h, or_iff_not_imp_left.mpr (λ hc, funext (λ i, (smul_eq_zero.mp (congr_fun h i)).resolve_left hc))⟩ end pi
cf9a1c1ade0edf6110835e5833cf6c7953fa7cec
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/category/Cat/limit.lean
d5ece82aebf5ca92af06417ab11e81562810924f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,549
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 category_theory.category.Cat import category_theory.limits.types import category_theory.limits.preserves.basic /-! # The category of small categories has all small limits. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. An object in the limit consists of a family of objects, which are carried to one another by the functors in the diagram. A morphism between two such objects is a family of morphisms between the corresponding objects, which are carried to one another by the action on morphisms of the functors in the diagram. ## Future work Can the indexing category live in a lower universe? -/ noncomputable theory universes v u open category_theory.limits namespace category_theory variables {J : Type v} [small_category J] namespace Cat namespace has_limits instance category_objects {F : J ⥤ Cat.{u u}} {j} : small_category ((F ⋙ Cat.objects.{u u}).obj j) := (F.obj j).str /-- Auxiliary definition: the diagram whose limit gives the morphism space between two objects of the limit category. -/ @[simps] def hom_diagram {F : J ⥤ Cat.{v v}} (X Y : limit (F ⋙ Cat.objects.{v v})) : J ⥤ Type v := { obj := λ j, limit.π (F ⋙ Cat.objects) j X ⟶ limit.π (F ⋙ Cat.objects) j Y, map := λ j j' f g, begin refine eq_to_hom _ ≫ (F.map f).map g ≫ eq_to_hom _, exact (congr_fun (limit.w (F ⋙ Cat.objects) f) X).symm, exact (congr_fun (limit.w (F ⋙ Cat.objects) f) Y), end, map_id' := λ X, begin ext f, dsimp, simp [functor.congr_hom (F.map_id X) f], end, map_comp' := λ X Y Z f g, begin ext h, dsimp, simp [functor.congr_hom (F.map_comp f g) h, eq_to_hom_map], refl, end, } @[simps] instance (F : J ⥤ Cat.{v v}) : category (limit (F ⋙ Cat.objects)) := { hom := λ X Y, limit (hom_diagram X Y), id := λ X, types.limit.mk.{v v} (hom_diagram X X) (λ j, 𝟙 _) (λ j j' f, by simp), comp := λ X Y Z f g, types.limit.mk.{v v} (hom_diagram X Z) (λ j, limit.π (hom_diagram X Y) j f ≫ limit.π (hom_diagram Y Z) j g) (λ j j' h, begin rw [←congr_fun (limit.w (hom_diagram X Y) h) f, ←congr_fun (limit.w (hom_diagram Y Z) h) g], dsimp, simp, end), id_comp' := λ _ _ _, by { ext, simp only [category.id_comp, types.limit.π_mk'] }, comp_id' := λ _ _ _, by { ext, simp only [types.limit.π_mk', category.comp_id] } } /-- Auxiliary definition: the limit category. -/ @[simps] def limit_cone_X (F : J ⥤ Cat.{v v}) : Cat.{v v} := { α := limit (F ⋙ Cat.objects), }. /-- Auxiliary definition: the cone over the limit category. -/ @[simps] def limit_cone (F : J ⥤ Cat.{v v}) : cone F := { X := limit_cone_X F, π := { app := λ j, { obj := limit.π (F ⋙ Cat.objects) j, map := λ X Y, limit.π (hom_diagram X Y) j, }, naturality' := λ j j' f, category_theory.functor.ext (λ X, (congr_fun (limit.w (F ⋙ Cat.objects) f) X).symm) (λ X Y h, (congr_fun (limit.w (hom_diagram X Y) f) h).symm), } } /-- Auxiliary definition: the universal morphism to the proposed limit cone. -/ @[simps] def limit_cone_lift (F : J ⥤ Cat.{v v}) (s : cone F) : s.X ⟶ limit_cone_X F := { obj := limit.lift (F ⋙ Cat.objects) { X := s.X, π := { app := λ j, (s.π.app j).obj, naturality' := λ j j' f, (congr_arg functor.obj (s.π.naturality f) : _), } }, map := λ X Y f, begin fapply types.limit.mk.{v v}, { intro j, refine eq_to_hom _ ≫ (s.π.app j).map f ≫ eq_to_hom _; simp, }, { intros j j' h, dsimp, simp only [category.assoc, functor.map_comp, eq_to_hom_map, eq_to_hom_trans, eq_to_hom_trans_assoc], rw [←functor.comp_map], have := (s.π.naturality h).symm, conv at this { congr, skip, dsimp, simp, }, erw [functor.congr_hom this f], dsimp, simp, }, end, map_id' := λ X, by simp, map_comp' := λ X Y Z f g, by simp } @[simp] lemma limit_π_hom_diagram_eq_to_hom {F : J ⥤ Cat.{v v}} (X Y : limit (F ⋙ Cat.objects.{v v})) (j : J) (h : X = Y) : limit.π (hom_diagram X Y) j (eq_to_hom h) = eq_to_hom (congr_arg (limit.π (F ⋙ Cat.objects.{v v}) j) h) := by { subst h, simp, } /-- Auxiliary definition: the proposed cone is a limit cone. -/ def limit_cone_is_limit (F : J ⥤ Cat.{v v}) : is_limit (limit_cone F) := { lift := limit_cone_lift F, fac' := λ s j, category_theory.functor.ext (by tidy) (λ X Y f, types.limit.π_mk _ _ _ _), uniq' := λ s m w, begin symmetry, fapply category_theory.functor.ext, { intro X, ext, dsimp, simp only [types.limit.lift_π_apply', ←w j], refl, }, { intros X Y f, dsimp, simp [(λ j, functor.congr_hom (w j).symm f)], congr, }, end, } end has_limits /-- The category of small categories has all small limits. -/ instance : has_limits (Cat.{v v}) := { has_limits_of_shape := λ J _, by exactI { has_limit := λ F, ⟨⟨⟨has_limits.limit_cone F, has_limits.limit_cone_is_limit F⟩⟩⟩, } } instance : preserves_limits Cat.objects.{v v} := { preserves_limits_of_shape := λ J _, by exactI { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (limits.is_limit.of_iso_limit (limit.is_limit (F ⋙ Cat.objects)) (cones.ext (by refl) (by tidy))), }} end Cat end category_theory
c0b1802288d2dd9ff27fed258ca8920203bf6572
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/types.lean
9410c3e4c4b4174adf45a43dd59f60bf956ce808
[ "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
15,017
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.shapes.images import category_theory.filtered import tactic.equiv_rw universes u open category_theory open category_theory.limits namespace category_theory.limits.types variables {J : Type u} [small_category J] /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ def limit_cone (F : J ⥤ Type u) : cone F := { X := F.sections, π := { app := λ j u, u.val j } } local attribute [elab_simple] congr_fun /-- (internal implementation) the fact that the proposed limit cone is the limit -/ def limit_cone_is_limit (F : J ⥤ Type u) : is_limit (limit_cone F) := { lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩, uniq' := by { intros, ext x j, exact congr_fun (w j) x } } /-- The category of types has all limits. See https://stacks.math.columbia.edu/tag/002U. -/ instance : has_limits (Type u) := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- The equivalence between a limiting cone of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def is_limit_equiv_sections {F : J ⥤ Type u} {c : cone F} (t : is_limit c) : c.X ≃ F.sections := (is_limit.cone_point_unique_up_to_iso t (limit_cone_is_limit F)).to_equiv @[simp] lemma is_limit_equiv_sections_apply {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (j : J) (x : c.X) : (((is_limit_equiv_sections t) x) : Π j, F.obj j) j = c.π.app j x := rfl @[simp] lemma is_limit_equiv_sections_symm_apply {F : J ⥤ Type u} {c : cone F} (t : is_limit c) (x : F.sections) (j : J) : c.π.app j ((is_limit_equiv_sections t).symm x) = (x : Π j, F.obj j) j := begin equiv_rw (is_limit_equiv_sections t).symm at x, simp, end /-- The equivalence between the abstract limit of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ noncomputable def limit_equiv_sections (F : J ⥤ Type u) : (limit F : Type u) ≃ F.sections := is_limit_equiv_sections (limit.is_limit _) @[simp] lemma limit_equiv_sections_apply (F : J ⥤ Type u) (x : limit F) (j : J) : (((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x := rfl @[simp] lemma limit_equiv_sections_symm_apply (F : J ⥤ Type u) (x : F.sections) (j : J) : limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j := is_limit_equiv_sections_symm_apply _ _ _ /-- Construct a term of `limit F : Type u` from a family of terms `x : Π j, F.obj j` which are "coherent": `∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j'`. -/ @[ext] noncomputable def limit.mk (F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') : (limit F : Type u) := (limit_equiv_sections F).symm ⟨x, h⟩ @[simp] lemma limit.π_mk (F : J ⥤ Type u) (x : Π j, F.obj j) (h : ∀ (j j') (f : j ⟶ j'), F.map f (x j) = x j') (j) : limit.π F j (limit.mk F x h) = x j := by { dsimp [limit.mk], simp, } -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits @[ext] lemma limit_ext (F : J ⥤ Type u) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := begin apply (limit_equiv_sections F).injective, ext j, simp [w j], end -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? @[simp] lemma limit.w_apply {F : J ⥤ Type u} {j j' : J} {x : limit F} (f : j ⟶ j') : F.map f (limit.π F j x) = limit.π F j' x := congr_fun (limit.w F f) x @[simp] lemma limit.lift_π_apply (F : J ⥤ Type u) (s : cone F) (j : J) (x : s.X) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x @[simp] lemma limit.map_π_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) : limit.π G j (lim.map α x) = α.app j (limit.π F j x) := congr_fun (limit.map_π α j) x /-- The relation defining the quotient type which implements the colimit of a functor `F : J ⥤ Type u`. See `category_theory.limits.types.quot`. -/ def quot.rel (F : J ⥤ Type u) : (Σ j, F.obj j) → (Σ j, F.obj j) → Prop := (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2) /-- A quotient type implementing the colimit of a functor `F : J ⥤ Type u`, as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by `⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`. -/ @[nolint has_inhabited_instance] def quot (F : J ⥤ Type u) : Type u := @quot (Σ j, F.obj j) (quot.rel F) /-- (internal implementation) the colimit cocone of a functor, implemented as a quotient of a sigma type -/ def colimit_cocone (F : J ⥤ Type u) : cocone F := { X := quot F, ι := { app := λ j x, quot.mk _ ⟨j, x⟩, naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } } local attribute [elab_with_expected_type] quot.lift /-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/ def colimit_cocone_is_colimit (F : J ⥤ Type u) : is_colimit (colimit_cocone F) := { desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2) (assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) } /-- The category of types has all colimits. See https://stacks.math.columbia.edu/tag/002U. -/ instance : has_colimits (Type u) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } /-- The equivalence between the abstract colimit of `F` in `Type u` and the "concrete" definition as a quotient. -/ noncomputable def colimit_equiv_quot (F : J ⥤ Type u) : (colimit F : Type u) ≃ quot F := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone_is_colimit F)).to_equiv @[simp] lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) : (colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x := rfl @[simp] lemma colimit_equiv_quot_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) : (colimit_equiv_quot F) (colimit.ι F j x) = quot.mk _ ⟨j, x⟩ := begin apply (colimit_equiv_quot F).symm.injective, simp, end @[simp] lemma colimit.w_apply {F : J ⥤ Type u} {j j' : J} {x : F.obj j} (f : j ⟶ j') : colimit.ι F j' (F.map f x) = colimit.ι F j x := congr_fun (colimit.w F f) x @[simp] lemma colimit.ι_desc_apply (F : J ⥤ Type u) (s : cocone F) (j : J) (x : F.obj j) : colimit.desc F s (colimit.ι F j x) = s.ι.app j x := congr_fun (colimit.ι_desc s j) x @[simp] lemma colimit.ι_map_apply {F G : J ⥤ Type u} (α : F ⟶ G) (j : J) (x) : colim.map α (colimit.ι F j x) = colimit.ι G j (α.app j x) := congr_fun (colimit.ι_map α j) x lemma colimit_sound {F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} (f : j ⟶ j') (w : F.map f x = x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←w], simp, end lemma colimit_sound' {F : J ⥤ Type u} {j j' : J} {x : F.obj j} {x' : F.obj j'} {j'' : J} (f : j ⟶ j'') (f' : j' ⟶ j'') (w : F.map f x = F.map f' x') : colimit.ι F j x = colimit.ι F j' x' := begin rw [←colimit.w _ f, ←colimit.w _ f'], rw [types_comp_apply, types_comp_apply, w], end lemma colimit_eq {F : J ⥤ Type u } {j j' : J} {x : F.obj j} {x' : F.obj j'} (w : colimit.ι F j x = colimit.ι F j' x') : eqv_gen (quot.rel F) ⟨j, x⟩ ⟨j', x'⟩ := begin apply quot.eq.1, simpa using congr_arg (colimit_equiv_quot F) w, end lemma jointly_surjective (F : J ⥤ Type u) {t : cocone F} (h : is_colimit t) (x : t.X) : ∃ j y, t.ι.app j y = x := begin suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true), { have := congr_fun this x, have H := congr_arg ulift.down this, dsimp at H, rwa eq_true at H }, refine h.hom_ext _, intro j, ext y, erw iff_true, exact ⟨j, y, rfl⟩ end /-- A variant of `jointly_surjective` for `x : colimit F`. -/ lemma jointly_surjective' {F : J ⥤ Type u} (x : colimit F) : ∃ j y, colimit.ι F j y = x := jointly_surjective F (colimit.is_colimit _) x namespace filtered_colimit /- For filtered colimits of types, we can give an explicit description of the equivalence relation generated by the relation used to form the colimit. -/ variables (F : J ⥤ Type u) /-- An alternative relation on `Σ j, F.obj j`, which generates the same equivalence relation as we use to define the colimit in `Type` above, but that is more convenient when working with filtered colimits. Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right where their images are equal. -/ protected def r (x y : Σ j, F.obj j) : Prop := ∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2 protected lemma r_ge (x y : Σ j, F.obj j) : (∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) → filtered_colimit.r F x y := λ ⟨f, hf⟩, ⟨y.1, f, 𝟙 y.1, by simp [hf]⟩ variables (t : cocone F) local attribute [elab_simple] nat_trans.app /-- Recognizing filtered colimits of types. -/ noncomputable def is_colimit_of (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi) (hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj → ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t := -- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X -- is a bijection. begin apply is_colimit.of_iso_colimit (colimit.is_colimit F), refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _, { exact colimit.desc F t }, { split, { show function.injective _, intros a b h, rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩, rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩, change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h, rw [colimit.ι_desc, colimit.ι_desc] at h, rcases hinj i j xi xj h with ⟨k, f, g, h'⟩, change colimit.ι F i xi = colimit.ι F j xj, rw [←colimit.w F f, ←colimit.w F g], change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj), rw h' }, { show function.surjective _, intro x, rcases hsurj x with ⟨i, xi, rfl⟩, use colimit.ι F i xi, simp } }, { intro j, apply colimit.ι_desc } end variables [is_filtered_or_empty J] protected lemma r_equiv : equivalence (filtered_colimit.r F) := ⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩, λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩, λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩, let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k', ⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in ⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc F.map (f ≫ fl ≫ n) x.2 = F.map (fl ≫ n) (F.map f x.2) : by simp ... = F.map (fl ≫ n) (F.map g y.2) : by rw h ... = F.map ((g ≫ fl) ≫ n) y.2 : by simp ... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn ... = F.map (gl ≫ n) (F.map f' y.2) : by simp ... = F.map (gl ≫ n) (F.map g' z.2) : by rw h' ... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩ protected lemma r_eq : filtered_colimit.r F = eqv_gen (λ x y, ∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) := begin apply le_antisymm, { rintros ⟨i, x⟩ ⟨j, y⟩ ⟨k, f, g, h⟩, exact eqv_gen.trans _ ⟨k, F.map f x⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩) (eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩)) }, { intros x y, convert relation.eqv_gen_mono (filtered_colimit.r_ge F), apply propext, symmetry, exact relation.eqv_gen_iff_of_equivalence (filtered_colimit.r_equiv F) } end lemma colimit_eq_iff_aux {i j : J} {xi : F.obj i} {xj : F.obj j} : (colimit_cocone F).ι.app i xi = (colimit_cocone F).ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := begin change quot.mk _ _ = quot.mk _ _ ↔ _, rw [quot.eq, quot.rel, ←filtered_colimit.r_eq], refl end variables {t} (ht : is_colimit t) lemma is_colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := let t' := colimit_cocone F, e : t' ≅ t := is_colimit.unique_up_to_iso (colimit_cocone_is_colimit F) ht, e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in begin refine iff.trans _ (colimit_eq_iff_aux F), convert e'.to_equiv.apply_eq_iff_eq; rw ←e.hom.w; refl end lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := is_colimit_eq_iff _ (colimit.is_colimit F) end filtered_colimit variables {α β : Type u} (f : α ⟶ β) section -- implementation of `has_image` /-- the image of a morphism in Type is just `set.range f` -/ def image : Type u := set.range f instance [inhabited α] : inhabited (image f) := { default := ⟨f (default α), ⟨_, rfl⟩⟩ } /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ β := subtype.val instance : mono (image.ι f) := (mono_iff_injective _).2 subtype.val_injective variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I) lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in Type through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := set.range_factorization f } /-- the facorisation through a mono has the universal property of the image. -/ noncomputable def is_image : is_image (mono_factorisation f) := { lift := image.lift, lift_fac' := image.lift_fac } instance : has_image f := has_image.mk ⟨_, is_image f⟩ instance : has_images (Type u) := { has_image := by apply_instance } instance : has_image_maps (Type u) := { has_image_map := λ f g st, has_image_map.transport st (mono_factorisation f.hom) (is_image g.hom) (λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2), begin have p := st.w, replace p := congr_fun p (classical.some x.2), simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p, erw [p, classical.some_spec x.2], end⟩⟩) rfl } end category_theory.limits.types
06f2f30b278b7e4e88c4d145b33ae560bfb1d7d9
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/format.lean
705372a4be98a33a42bb8dd739b12973e4f8d623
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
4,669
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.options init.function universes u v inductive format.color | red | green | orange | blue | pink | cyan | grey meta constant format : Type meta constant format.line : format meta constant format.space : format meta constant format.nil : format meta constant format.compose : format → format → format meta constant format.nest : nat → format → format meta constant format.highlight : format → color → format meta constant format.group : format → format meta constant format.of_string : string → format meta constant format.of_nat : nat → format meta constant format.flatten : format → format meta constant format.to_string : format → options → string meta constant format.of_options : options → format meta constant format.is_nil : format → bool meta constant trace_fmt {α : Type u} : format → (unit → α) → α meta instance : inhabited format := ⟨format.space⟩ meta instance : has_append format := ⟨format.compose⟩ meta instance : has_to_string format := ⟨λ f, format.to_string f options.mk⟩ meta class has_to_format (α : Type u) := (to_format : α → format) meta instance : has_to_format format := ⟨id⟩ meta def to_fmt {α : Type u} [has_to_format α] : α → format := has_to_format.to_format meta instance nat_to_format : has_coe nat format := ⟨format.of_nat⟩ meta instance string_to_format : has_coe string format := ⟨format.of_string⟩ open format list meta def format.indent (f : format) (n : nat) : format := nest n (line ++ f) meta def format.when {α : Type u} [has_to_format α] : bool → α → format | tt a := to_fmt a | ff a := nil meta def format.join (xs : list format) : format := foldl compose (of_string "") xs meta instance : has_to_format options := ⟨λ o, format.of_options o⟩ meta instance : has_to_format bool := ⟨λ b, if b then of_string "tt" else of_string "ff"⟩ meta instance {p : Prop} : has_to_format (decidable p) := ⟨λ b : decidable p, @ite p b _ (of_string "tt") (of_string "ff")⟩ meta instance : has_to_format string := ⟨λ s, format.of_string s⟩ meta instance : has_to_format nat := ⟨λ n, format.of_nat n⟩ meta instance : has_to_format unsigned := ⟨λ n, to_fmt n.to_nat⟩ meta instance : has_to_format char := ⟨λ c : char, format.of_string c.to_string⟩ meta def list.to_format {α : Type u} [has_to_format α] : list α → format | [] := to_fmt "[]" | xs := to_fmt "[" ++ group (nest 1 $ format.join $ list.intersperse ("," ++ line) $ xs.map to_fmt) ++ to_fmt "]" meta instance {α : Type u} [has_to_format α] : has_to_format (list α) := ⟨list.to_format⟩ attribute [instance] string.has_to_format meta instance : has_to_format name := ⟨λ n, to_fmt (to_string n)⟩ meta instance : has_to_format unit := ⟨λ u, to_fmt "()"⟩ meta instance {α : Type u} [has_to_format α] : has_to_format (option α) := ⟨λ o, option.cases_on o (to_fmt "none") (λ a, to_fmt "(some " ++ nest 6 (to_fmt a) ++ to_fmt ")")⟩ meta instance sum_has_to_format {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (sum α β) := ⟨λ s, sum.cases_on s (λ a, to_fmt "(inl " ++ nest 5 (to_fmt a) ++ to_fmt ")") (λ b, to_fmt "(inr " ++ nest 5 (to_fmt b) ++ to_fmt ")")⟩ open prod meta instance {α : Type u} {β : Type v} [has_to_format α] [has_to_format β] : has_to_format (prod α β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "(" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt ")"))⟩ open sigma meta instance {α : Type u} {β : α → Type v} [has_to_format α] [s : ∀ x, has_to_format (β x)] : has_to_format (sigma β) := ⟨λ ⟨a, b⟩, group (nest 1 (to_fmt "⟨" ++ to_fmt a ++ to_fmt "," ++ line ++ to_fmt b ++ to_fmt "⟩"))⟩ open subtype meta instance {α : Type u} {p : α → Prop} [has_to_format α] : has_to_format (subtype p) := ⟨λ s, to_fmt (val s)⟩ meta def format.bracket : string → string → format → format | o c f := to_fmt o ++ nest (utf8_length o) f ++ to_fmt c meta def format.paren (f : format) : format := format.bracket "(" ")" f meta def format.cbrace (f : format) : format := format.bracket "{" "}" f meta def format.sbracket (f : format) : format := format.bracket "[" "]" f meta def format.dcbrace (f : format) : format := to_fmt "⦃" ++ nest 1 f ++ to_fmt "⦄"
1317a843e37247c27435d5ca1f47f78149bc32b3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/App.lean
378340ca4c6329c85fe2eba8849408628b4503e5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
66,434
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.FindMVar import Lean.Parser.Term import Lean.Meta.KAbstract import Lean.Meta.Tactic.ElimInfo import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.Arg import Lean.Elab.RecAppSyntax namespace Lean.Elab.Term open Meta builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute ← registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type" def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool := elabWithoutExpectedTypeAttr.hasTag env declName instance : ToString Arg where toString | .stx val => toString val | .expr val => toString val instance : ToString NamedArg where toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")" def throwInvalidNamedArg (namedArg : NamedArg) (fn? : Option Name) : TermElabM α := withRef namedArg.ref <| match fn? with | some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'" | none => throwError "invalid argument name '{namedArg.name}' for function" private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do try ensureHasTypeAux expectedType (← inferType arg) arg f catch | ex@(.error ..) => if (← read).errToSorry then exceptionToSorry ex expectedType else throw ex | ex => throw ex private def mkProjAndCheck (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let r := mkProj structName idx e let eType ← inferType e if (← isProp eType) then let rType ← inferType r if !(← isProp rType) then throwError "invalid projection, the expression{indentExpr e}\nis a proposition and has type{indentExpr eType}\nbut the projected value is not, it has type{indentExpr rType}" return r /-- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) ``` -/ private def tryCoeFun? (α : Expr) (a : Expr) : TermElabM (Option Expr) := do let v ← mkFreshLevelMVar let type ← mkArrow α (mkSort v) let γ ← mkFreshExprMVar type let u ← getLevel α let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[α, γ] let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``CoeFun.coe [u, v]) #[α, γ, mvar, a] else return none catch _ => return none def synthesizeAppInstMVars (instMVars : Array MVarId) (app : Expr) : TermElabM Unit := for mvarId in instMVars do unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass registerMVarErrorImplicitArgInfo mvarId (← getRef) app /-- Return `some namedArg` if `namedArgs` contains an entry for `binderName`. -/ private def findBinderName? (namedArgs : List NamedArg) (binderName : Name) : Option NamedArg := namedArgs.find? fun namedArg => namedArg.name == binderName /-- Erase entry for `binderName` from `namedArgs`. -/ def eraseNamedArg (namedArgs : List NamedArg) (binderName : Name) : List NamedArg := namedArgs.filter (·.name != binderName) /-- Return true if the given type contains `OptParam` or `AutoParams` -/ private def hasOptAutoParams (type : Expr) : MetaM Bool := do forallTelescopeReducing type fun xs _ => xs.anyM fun x => do let xType ← inferType x return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome /-! # Default application elaborator -/ namespace ElabAppArgs structure Context where /-- `true` if `..` was used -/ ellipsis : Bool -- /-- `true` if `@` modifier was used -/ explicit : Bool /-- If the result type of an application is the `outParam` of some local instance, then special support may be needed because type class resolution interacts poorly with coercions in this kind of situation. This flag enables the special support. The idea is quite simple, if the result type is the `outParam` of some local instance, we simply execute `synthesizeSyntheticMVarsUsingDefault`. We added this feature to make sure examples as follows are correctly elaborated. ```lean class GetElem (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where getElem (xs : Cont) (i : Idx) : Elem export GetElem (getElem) instance : GetElem (Array α) Nat α where getElem xs i := xs.get ⟨i, sorry⟩ opaque f : Option Bool → Bool opaque g : Bool → Bool def bad (xs : Array Bool) : Bool := let x := getElem xs 0 f x && g x ``` Without the special support, Lean fails at `g x` saying `x` has type `Option Bool` but is expected to have type `Bool`. From the users point of view this is a bug, since `let x := getElem xs 0` clearly constraints `x` to be `Bool`, but we only obtain this information after we apply the `OfNat` default instance for `0`. Before converging to this solution, we have tried to create a "coercion placeholder" when `resultIsOutParamSupport = true`, but it did not work well in practice. For example, it failed in the example above. -/ resultIsOutParamSupport : Bool /-- Auxiliary structure for elaborating the application `f args namedArgs`. -/ structure State where f : Expr fType : Expr /-- Remaining regular arguments. -/ args : List Arg /-- remaining named arguments to be processed. -/ namedArgs : List NamedArg expectedType? : Option Expr /-- When named arguments are provided and explicit arguments occurring before them are missing, the elaborator eta-expands the declaration. For example, ``` def f (x y : Nat) := x + y #check f (y := 5) -- fun x => f x 5 ``` `etaArgs` stores the fresh free variables for implementing the eta-expansion. When `..` is used, eta-expansion is disabled, and missing arguments are treated as `_`. -/ etaArgs : Array Expr := #[] /-- Metavariables that we need the set the error context using the application being built. -/ toSetErrorCtx : Array MVarId := #[] /-- Metavariables for the instance implicit arguments that have already been processed. -/ instMVars : Array MVarId := #[] /-- The following field is used to implement the `propagateExpectedType` heuristic. It is set to `true` true when `expectedType` still has to be propagated. -/ propagateExpected : Bool /-- If the result type may be the `outParam` of some local instance. See comment at `Context.resultIsOutParamSupport` -/ resultTypeOutParam? : Option MVarId := none abbrev M := ReaderT Context (StateRefT State TermElabM) /-- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/ private def addInstMVar (mvarId : MVarId) : M Unit := modify fun s => { s with instMVars := s.instMVars.push mvarId } /-- Try to synthesize metavariables are `instMVars` using type class resolution. The ones that cannot be synthesized yet are registered. Remark: we use this method before trying to apply coercions to function. -/ def synthesizeAppInstMVars : M Unit := do let s ← get let instMVars := s.instMVars modify fun s => { s with instMVars := #[] } Term.synthesizeAppInstMVars instMVars s.f /-- fType may become a forallE after we synthesize pending metavariables. -/ private def synthesizePendingAndNormalizeFunType : M Unit := do synthesizeAppInstMVars synthesizeSyntheticMVars let s ← get let fType ← whnfForall s.fType if fType.isForall then modify fun s => { s with fType } else match (← tryCoeFun? fType s.f) with | some f => let fType ← inferType f modify fun s => { s with f, fType } | none => for namedArg in s.namedArgs do let f := s.f.getAppFn if f.isConst then throwInvalidNamedArg namedArg f.constName! else throwInvalidNamedArg namedArg none throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}" /-- Normalize and return the function type. -/ private def normalizeFunType : M Expr := do let s ← get let fType ← whnfForall s.fType modify fun s => { s with fType } return fType /-- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /-- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! /-- Remove named argument with name `binderName` from `namedArgs`. -/ def eraseNamedArg (binderName : Name) : M Unit := modify fun s => { s with namedArgs := Term.eraseNamedArg s.namedArgs binderName } /-- Add a new argument to the result. That is, `f := f arg`, update `fType`. This method assumes `fType` is a function type. -/ private def addNewArg (argName : Name) (arg : Expr) : M Unit := do modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } if arg.isMVar then let mvarId := arg.mvarId! if let some mvarErrorInfo ← getMVarErrorInfo? mvarId then registerMVarErrorInfo { mvarErrorInfo with argName? := argName } /-- Elaborate the given `Arg` and add it to the result. See `addNewArg`. Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/ private def elabAndAddNewArg (argName : Name) (arg : Arg) : M Unit := do let s ← get let expectedType := (← getArgExpectedType).consumeTypeAnnotations match arg with | Arg.expr val => let arg ← ensureArgType s.f val expectedType addNewArg argName arg | Arg.stx stx => let val ← elabTerm stx expectedType let arg ← withRef stx <| ensureArgType s.f val expectedType addNewArg argName arg /-- Return true if `fType` contains `OptParam` or `AutoParams` -/ private def fTypeHasOptAutoParams : M Bool := do hasOptAutoParams (← get).fType /-- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. Remark: `(explicit : Bool) == true` when `@` modifier is used. -/ private partial def getForallBody (explicit : Bool) : Nat → List NamedArg → Expr → Option Expr | i, namedArgs, type@(.forallE n d b bi) => match findBinderName? namedArgs n with | some _ => getForallBody explicit i (Term.eraseNamedArg namedArgs n) b | none => if !explicit && !bi.isExplicit then getForallBody explicit i namedArgs b else if i > 0 then getForallBody explicit (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody explicit i namedArgs b else some type | 0, [], type => some type | _, _, _ => none private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool := match nextArg with | .expr _ => false -- it has already been elaborated | .stx stx => -- TODO: make this configurable? stx.getKind != ``Lean.Parser.Term.hole && stx.getKind != ``Lean.Parser.Term.syntheticHole && stx.getKind != ``Lean.Parser.Term.byTactic /-- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean Add.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`). 2- The resultant type contains optional/auto params. We have considered adding the following extra conditions a) The resultant type does not contain any type metavariable. b) The resultant type contains a nontype metavariable. These two conditions would restrict the method to simple functions that are "morally" in the Hindley&Milner fragment. If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`. -/ private def propagateExpectedType (arg : Arg) : M Unit := do if shouldPropagateExpectedTypeFor arg then let s ← get -- TODO: handle s.etaArgs.size > 0 unless !s.etaArgs.isEmpty || !s.propagateExpected do match s.expectedType? with | none => pure () | some expectedType => /- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`). If we propagate `expectedType == Prop` in the following examples, the elaborator would fail ``` def f1 (s : Nat × Bool) : Bool := if s.2 then false else true def f2 (s : List Bool) : Bool := if s.head! then false else true def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true ``` They would all fail for the same reason. So, let's focus on the first one. We would elaborate `s.2` with `expectedType == Prop`. Before we elaborate `s`, this method would be invoked, and `s.fType` is `?α × ?β → ?β` and after propagation we would have `?α × Prop → Prop`. Then, when we would try to elaborate `s`, and get a type error because `?α × Prop` cannot be unified with `Nat × Bool` Most users would have a hard time trying to understand why these examples failed. Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`. Drawback: users use `if-then-else` with conditions that are not Decidable. So, users would have to embrace `propDecidable` and `choice`. This may not be that bad since the developers and users don't seem to care about constructivism. We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/ if expectedType.isProp then modify fun s => { s with propagateExpected := false } else let numRemainingArgs := s.args.length trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}" match getForallBody (← read).explicit numRemainingArgs s.namedArgs s.fType with | none => pure () | some fTypeBody => unless fTypeBody.hasLooseBVars do unless (← hasOptAutoParams fTypeBody) do trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}" if (← isDefEq expectedType fTypeBody) then /- Note that we only set `propagateExpected := false` when propagation has succeeded. -/ modify fun s => { s with propagateExpected := false } /-- This method executes after all application arguments have been processed. -/ private def finalize : M Expr := do let s ← get let mut e := s.f -- all user explicit arguments have been consumed trace[Elab.app.finalize] e let ref ← getRef -- Register the error context of implicits for mvarId in s.toSetErrorCtx do registerMVarErrorImplicitArgInfo mvarId ref e if !s.etaArgs.isEmpty then e ← mkLambdaFVars s.etaArgs e /- Remark: we should not use `s.fType` as `eType` even when `s.etaArgs.isEmpty`. Reason: it may have been unfolded. -/ let eType ← inferType e trace[Elab.app.finalize] "after etaArgs, {e} : {eType}" /- Recall that `resultTypeOutParam? = some mvarId` if the function result type is the output parameter of a local instance. The value of this parameter may be inferable using other arguments. For example, suppose we have ```lean def add_one {X} [Trait X] [One (Trait.R X)] [HAdd X (Trait.R X) X] (x : X) : X := x + (One.one : (Trait.R X)) ``` from test `948.lean`. There are multiple ways to infer `X`, and we don't want to mark it as `syntheticOpaque`. -/ if let some outParamMVarId := s.resultTypeOutParam? then synthesizeAppInstMVars /- If `eType != mkMVar outParamMVarId`, then the function is partially applied, and we do not apply default instances. -/ if !(← outParamMVarId.isAssigned) && eType.isMVar && eType.mvarId! == outParamMVarId then synthesizeSyntheticMVarsUsingDefault return e else return e if let some expectedType := s.expectedType? then -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. trace[Elab.app.finalize] "expected type: {expectedType}" discard <| isDefEq expectedType eType synthesizeAppInstMVars return e /-- Return `true` if there is a named argument that depends on the next argument. -/ private def anyNamedArgDependsOnCurrent : M Bool := do let s ← get if s.namedArgs.isEmpty then return false else forallTelescopeReducing s.fType fun xs _ => do let curr := xs[0]! for i in [1:xs.size] do let xDecl ← xs[i]!.fvarId!.getDecl if s.namedArgs.any fun arg => arg.name == xDecl.userName then if (← localDeclDependsOn xDecl curr.fvarId!) then return true return false /-- Return `true` if there are regular or named arguments to be processed. -/ private def hasArgsToProcess : M Bool := do let s ← get return !s.args.isEmpty || !s.namedArgs.isEmpty /-- Return `true` if the next argument at `args` is of the form `_` -/ private def isNextArgHole : M Bool := do match (← get).args with | Arg.stx (Syntax.node _ ``Lean.Parser.Term.hole _) :: _ => pure true | _ => pure false /-- Return `true` if the next argument to be processed is the outparam of a local instance, and it the result type of the function. For example, suppose we have the class ```lean class Get (Cont : Type u) (Idx : Type v) (Elem : outParam (Type w)) where get (xs : Cont) (i : Idx) : Elem ``` And the current value of `fType` is ``` {Cont : Type u_1} → {Idx : Type u_2} → {Elem : Type u_3} → [self : Get Cont Idx Elem] → Cont → Idx → Elem ``` then the result returned by this method is `false` since `Cont` is not the output param of any local instance. Now assume `fType` is ``` {Elem : Type u_3} → [self : Get Cont Idx Elem] → Cont → Idx → Elem ``` then, the method returns `true` because `Elem` is an output parameter for the local instance `[self : Get Cont Idx Elem]`. Remark: if `resultIsOutParamSupport` is `false`, this method returns `false`. -/ private partial def isNextOutParamOfLocalInstanceAndResult : M Bool := do if !(← read).resultIsOutParamSupport then return false let type := (← get).fType.bindingBody! unless isResultType type 0 do return false if (← hasLocalInstaceWithOutParams type) then let x := mkFVar (← mkFreshFVarId) isOutParamOfLocalInstance x (type.instantiate1 x) else return false where isResultType (type : Expr) (i : Nat) : Bool := match type with | .forallE _ _ b _ => isResultType b (i + 1) | .bvar idx => idx == i | _ => false /-- (quick filter) Return true if `type` constains a binder `[C ...]` where `C` is a class containing outparams. -/ hasLocalInstaceWithOutParams (type : Expr) : CoreM Bool := do let .forallE _ d b bi := type | return false if bi.isInstImplicit then if let .const declName .. := d.getAppFn then if hasOutParams (← getEnv) declName then return true hasLocalInstaceWithOutParams b isOutParamOfLocalInstance (x : Expr) (type : Expr) : MetaM Bool := do let .forallE _ d b bi := type | return false if bi.isInstImplicit then if let .const declName .. := d.getAppFn then if hasOutParams (← getEnv) declName then let cType ← inferType d.getAppFn if (← isOutParamOf x 0 d.getAppArgs cType) then return true isOutParamOfLocalInstance x b isOutParamOf (x : Expr) (i : Nat) (args : Array Expr) (cType : Expr) : MetaM Bool := do if h : i < args.size then match (← whnf cType) with | .forallE _ d b _ => let arg := args.get ⟨i, h⟩ if arg == x && d.isOutParam then return true isOutParamOf x (i+1) args b | _ => return false else return false mutual /-- Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`, and then execute the main loop.-/ private partial def addEtaArg (argName : Name) : M Expr := do let n ← getBindingName let type ← getArgExpectedType withLocalDeclD n type fun x => do modify fun s => { s with etaArgs := s.etaArgs.push x } addNewArg argName x main private partial def addImplicitArg (argName : Name) : M Expr := do let argType ← getArgExpectedType let arg ← if (← isNextOutParamOfLocalInstanceAndResult) then let arg ← mkFreshExprMVar argType /- When the result type is an output parameter, we don't want to propagate the expected type. So, we just mark `propagateExpected := false` to disable it. At `finalize`, we check whether `arg` is still unassigned, if it is, we apply default instances, and try to synthesize pending mvars. -/ modify fun s => { s with resultTypeOutParam? := some arg.mvarId!, propagateExpected := false } pure arg else mkFreshExprMVar argType modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! } addNewArg argName arg main /-- Process a `fType` of the form `(x : A) → B x`. This method assume `fType` is a function type -/ private partial def processExplictArg (argName : Name) : M Expr := do match (← get).args with | arg::args => propagateExpectedType arg modify fun s => { s with args } elabAndAddNewArg argName arg main | _ => let argType ← getArgExpectedType match (← read).explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with | false, some defVal, _ => addNewArg argName defVal; main | false, _, some (.const tacticDecl _) => let env ← getEnv let opts ← getOptions match evalSyntaxConstant env opts tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => -- TODO(Leo): does this work correctly for tactic sequences? let tacticBlock ← `(by $(⟨tacticSyntax⟩)) let argNew := Arg.stx tacticBlock propagateExpectedType argNew elabAndAddNewArg argName argNew main | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if !(← get).namedArgs.isEmpty then if (← anyNamedArgDependsOnCurrent) then addImplicitArg argName else if (← read).ellipsis then addImplicitArg argName else addEtaArg argName else if !(← read).explicit then if (← read).ellipsis then addImplicitArg argName else if (← fTypeHasOptAutoParams) then addEtaArg argName else finalize else finalize /-- Process a `fType` of the form `{x : A} → B x`. This method assume `fType` is a function type -/ private partial def processImplicitArg (argName : Name) : M Expr := do if (← read).explicit then processExplictArg argName else addImplicitArg argName /-- Process a `fType` of the form `{{x : A}} → B x`. This method assume `fType` is a function type -/ private partial def processStrictImplicitArg (argName : Name) : M Expr := do if (← read).explicit then processExplictArg argName else if (← hasArgsToProcess) then addImplicitArg argName else finalize /-- Process a `fType` of the form `[x : A] → B x`. This method assume `fType` is a function type -/ private partial def processInstImplicitArg (argName : Name) : M Expr := do if (← read).explicit then if (← isNextArgHole) then /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic modify fun s => { s with args := s.args.tail! } addInstMVar arg.mvarId! addNewArg argName arg main else processExplictArg argName else let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic addInstMVar arg.mvarId! addNewArg argName arg main /-- Elaborate function application arguments. -/ partial def main : M Expr := do let fType ← normalizeFunType if fType.isForall then let binderName := fType.bindingName! let binfo := fType.bindingInfo! let s ← get match findBinderName? s.namedArgs binderName with | some namedArg => propagateExpectedType namedArg.val eraseNamedArg binderName elabAndAddNewArg binderName namedArg.val main | none => match binfo with | .implicit => processImplicitArg binderName | .instImplicit => processInstImplicitArg binderName | .strictImplicit => processStrictImplicitArg binderName | _ => processExplictArg binderName else if (← hasArgsToProcess) then synthesizePendingAndNormalizeFunType main else finalize end end ElabAppArgs builtin_initialize elabAsElim : TagAttribute ← registerTagAttribute `elabAsElim "instructs elaborator that the arguments of the function application should be elaborated as were an eliminator" fun declName => do let go : MetaM Unit := do discard <| getElimInfo declName let info ← getConstInfo declName if (← hasOptAutoParams info.type) then throwError "[elabAsElim] attribute cannot be used in declarations containing optional and auto parameters" go.run' {} {} /-! # Eliminator-like function application elaborator -/ namespace ElabElim /-- Context of the `elabAsElim` elaboration procedure. -/ structure Context where elimInfo : ElimInfo expectedType : Expr /-- State of the `elabAsElim` elaboration procedure. -/ structure State where /-- The resultant expression being built. -/ f : Expr /-- `f : fType -/ fType : Expr /-- User-provided named arguments that still have to be processed. -/ namedArgs : List NamedArg /-- User-providedarguments that still have to be processed. -/ args : List Arg /-- Discriminants processed so far. -/ discrs : Array Expr := #[] /-- Instance implicit arguments collected so far. -/ instMVars : Array MVarId := #[] /-- Position of the next argument to be processed. We use it to decide whether the argument is the motive or a discriminant. -/ idx : Nat := 0 /-- Store the metavariable used to represent the motive that will be computed at `finalize`. -/ motive? : Option Expr := none abbrev M := ReaderT Context $ StateRefT State TermElabM /-- Infer the `motive` using the expected type by `kabstract`ing the discriminants. -/ def mkMotive (discrs : Array Expr) (expectedType : Expr): MetaM Expr := do discrs.foldrM (init := expectedType) fun discr motive => do let discr ← instantiateMVars discr let motiveBody ← kabstract motive discr /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/ let discrType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType discr)) return Lean.mkLambda (← mkFreshBinderName) BinderInfo.default discrType motiveBody /-- If the eliminator is over-applied, we "revert" the extra arguments. -/ def revertArgs (args : List Arg) (f : Expr) (expectedType : Expr) : TermElabM (Expr × Expr) := args.foldrM (init := (f, expectedType)) fun arg (f, expectedType) => do let val ← match arg with | .expr val => pure val | .stx stx => elabTerm stx none let val ← instantiateMVars val let expectedTypeBody ← kabstract expectedType val /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. -/ let valType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType val)) return (mkApp f val, mkForall (← mkFreshBinderName) BinderInfo.default valType expectedTypeBody) /-- Contruct the resulting application after all discriminants have bee elaborated, and we have consumed as many given arguments as possible. -/ def finalize : M Expr := do unless (← get).namedArgs.isEmpty do throwError "failed to elaborate eliminator, unused named arguments: {(← get).namedArgs.map (·.name)}" let some motive := (← get).motive? | throwError "failed to elaborate eliminator, insufficient number of arguments" forallTelescope (← get).fType fun xs _ => do let mut expectedType := (← read).expectedType let mut f := (← get).f if xs.size > 0 then assert! (← get).args.isEmpty try expectedType ← instantiateForall expectedType xs catch _ => throwError "failed to elaborate eliminator, insufficient number of arguments, expected type:{indentExpr expectedType}" else -- over-application, simulate `revert` (f, expectedType) ← revertArgs (← get).args f expectedType let result := mkAppN f xs let mut discrs := (← get).discrs let idx := (← get).idx if (← get).discrs.size < (← read).elimInfo.targetsPos.size then for i in [idx:idx + xs.size], x in xs do if (← read).elimInfo.targetsPos.contains i then discrs := discrs.push x let motiveVal ← mkMotive discrs expectedType unless (← isDefEq motive motiveVal) do throwError "failed to elaborate eliminator, invalid motive{indentExpr motiveVal}" synthesizeAppInstMVars (← get).instMVars result let result ← mkLambdaFVars xs (← instantiateMVars result) return result /-- Return the next argument to be processed. The result is `.none` if it is an implicit argument which was not provided using a named argument. The result is `.undef` if `args` is empty and `namedArgs` does contain an entry for `binderName`. -/ def getNextArg? (binderName : Name) (binderInfo : BinderInfo) : M (LOption Arg) := do match findBinderName? (← get).namedArgs binderName with | some namedArg => modify fun s => { s with namedArgs := eraseNamedArg s.namedArgs binderName } return .some namedArg.val | none => if binderInfo.isExplicit then match (← get).args with | [] => return .undef | arg :: args => modify fun s => { s with args } return .some arg else return .none /-- Set the `motive` field in the state. -/ def setMotive (motive : Expr) : M Unit := modify fun s => { s with motive? := motive } /-- Push the given expression into the `discrs` field in the state. -/ def addDiscr (discr : Expr) : M Unit := modify fun s => { s with discrs := s.discrs.push discr } /-- Elaborate the given argument with the given expected type. -/ private def elabArg (arg : Arg) (argExpectedType : Expr) : M Expr := do match arg with | Arg.expr val => ensureArgType (← get).f val argExpectedType | Arg.stx stx => let val ← elabTerm stx argExpectedType withRef stx <| ensureArgType (← get).f val argExpectedType /-- Save information for producing error messages. -/ def saveArgInfo (arg : Expr) (binderName : Name) : M Unit := do if arg.isMVar then let mvarId := arg.mvarId! if let some mvarErrorInfo ← getMVarErrorInfo? mvarId then registerMVarErrorInfo { mvarErrorInfo with argName? := binderName } /-- Create an implicit argument using the given `BinderInfo`. -/ def mkImplicitArg (argExpectedType : Expr) (bi : BinderInfo) : M Expr := do let arg ← mkFreshExprMVar argExpectedType (if bi.isInstImplicit then .synthetic else .natural) if bi.isInstImplicit then modify fun s => { s with instMVars := s.instMVars.push arg.mvarId! } return arg /-- Main loop of the `elimAsElab` procedure. -/ partial def main : M Expr := do let .forallE binderName binderType body binderInfo ← whnfForall (← get).fType | finalize let addArgAndContinue (arg : Expr) : M Expr := do modify fun s => { s with idx := s.idx + 1, f := mkApp s.f arg, fType := body.instantiate1 arg } saveArgInfo arg binderName main let idx := (← get).idx if (← read).elimInfo.motivePos == idx then let motive ← mkImplicitArg binderType binderInfo setMotive motive addArgAndContinue motive else if (← read).elimInfo.targetsPos.contains idx then match (← getNextArg? binderName binderInfo) with | .some arg => let discr ← elabArg arg binderType; addDiscr discr; addArgAndContinue discr | .undef => finalize | .none => let discr ← mkImplicitArg binderType binderInfo; addDiscr discr; addArgAndContinue discr else match (← getNextArg? binderName binderInfo) with | .some (.stx stx) => addArgAndContinue (← postponeElabTerm stx binderType) | .some (.expr val) => addArgAndContinue (← ensureArgType (← get).f val binderType) | .undef => finalize | .none => addArgAndContinue (← mkImplicitArg binderType binderInfo) end ElabElim /-- Return `true` if `declName` is a candidate for `ElabElim.main` elaboration. -/ private def shouldElabAsElim (declName : Name) : CoreM Bool := do if (← isRec declName) then return true let env ← getEnv if isCasesOnRecursor env declName then return true if isBRecOnRecursor env declName then return true if isRecOnRecursor env declName then return true return elabAsElim.hasTag env declName private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool := match f.getAppFn.constName? with | some declName => return !hasElabWithoutExpectedType (← getEnv) declName | _ => return true /-! # Function application elaboration -/ /-- Elaborate a `f`-application using `namedArgs` and `args` as the arguments. - `expectedType?` the expected type if available. It is used to propagate typing information only. This method does **not** ensure the result has this type. - `explicit = true` when notation `@` is used, and implicit arguments are assumed to be provided at `namedArgs` and `args`. - `ellipsis = true` when notation `..` is used. That is, we add `_` for missing arguments. - `resultIsOutParamSupport` is used to control whether special support is used when processing applications of functions that return output parameter of some local instance. Example: ``` GetElem.getElem : {Cont : Type u_1} → {Idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` The result type `elem` is the output parameter of the local instance `self`. When this parameter is set to `true`, we execute `synthesizeSyntheticMVarsUsingDefault`. For additional details, see comment at `ElabAppArgs.resultIsOutParam`. -/ def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (resultIsOutParamSupport := true) : TermElabM Expr := do -- Coercions must be available to use this flag. -- If `@` is used (i.e., `explicit = true`), we disable `resultIsOutParamSupport`. let resultIsOutParamSupport := ((← getEnv).contains ``Lean.Internal.coeM) && resultIsOutParamSupport && !explicit let fType ← inferType f let fType ← instantiateMVars fType unless namedArgs.isEmpty && args.isEmpty do tryPostponeIfMVar fType trace[Elab.app.args] "explicit: {explicit}, ellipsis: {ellipsis}, {f} : {fType}" trace[Elab.app.args] "namedArgs: {namedArgs}" trace[Elab.app.args] "args: {args}" if let some elimInfo ← elabAsElim? then tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | throwError "failed to elaborate eliminator, expected type is not available" let expectedType ← instantiateMVars expectedType if expectedType.getAppFn.isMVar then throwError "failed to elaborate eliminator, expected type is not available" ElabElim.main.run { elimInfo, expectedType } |>.run' { f, fType args := args.toList namedArgs := namedArgs.toList } else ElabAppArgs.main.run { explicit, ellipsis, resultIsOutParamSupport } |>.run' { args := args.toList expectedType?, f, fType namedArgs := namedArgs.toList propagateExpected := (← propagateExpectedTypeFor f) } where /-- Return `some info` if we should elaborate as an eliminator. -/ elabAsElim? : TermElabM (Option ElimInfo) := do if explicit || ellipsis then return none let .const declName _ := f | return none unless (← shouldElabAsElim declName) do return none let elimInfo ← getElimInfo declName forallTelescopeReducing (← inferType f) fun xs _ => do if h : elimInfo.motivePos < xs.size then let x := xs[elimInfo.motivePos] let localDecl ← x.fvarId!.getDecl if findBinderName? namedArgs.toList localDecl.userName matches some _ then -- motive has been explicitly provided, so we should use standard app elaborator return none return some elimInfo else return none /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution where | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) private def throwLValError (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}" /-- `findMethod? env S fName`. - If `env` contains `S ++ fName`, return `(S, S++fName)` - Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o - Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name × Name) := let fullName := structName ++ fieldName match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructure env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName else none /-- Return `some (structName', fullName)` if `structName ++ fieldName` is an alias for `fullName`, and `fullName` is of the form `structName' ++ fieldName`. TODO: if there is more than one applicable alias, it returns `none`. We should consider throwing an error or warning. -/ private def findMethodAlias? (env : Environment) (structName fieldName : Name) : Option (Name × Name) := let fullName := structName ++ fieldName -- We never skip `protected` aliases when resolving dot-notation. let aliasesCandidates := getAliases env fullName (skipProtected := false) |>.filterMap fun alias => match alias.eraseSuffix? fieldName with | none => none | some structName' => some (structName', alias) match aliasesCandidates with | [r] => some r | _ => none private def throwInvalidFieldNotation (e eType : Expr) : TermElabM α := throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do if eType.isForall then match lval with | LVal.fieldName _ fieldName _ _ => let fullName := `Function ++ fieldName if (← getEnv).contains fullName then return LValResolution.const `Function `Function fullName | _ => pure () match eType.getAppFn.constName?, lval with | some structName, LVal.fieldIdx _ idx => if idx == 0 then throwError "invalid projection, index must be greater than 0" let env ← getEnv unless isStructureLike env structName do throwLValError e eType "invalid projection, structure expected" let numFields := getStructureLikeNumFields env structName if idx - 1 < numFields then if isStructure env structName then let fieldNames := getStructureFields env structName return LValResolution.projFn structName structName fieldNames[idx - 1]! else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ return LValResolution.projIdx structName (idx - 1) else throwLValError e eType m!"invalid projection, structure has only {numFields} field(s)" | some structName, LVal.fieldName _ fieldName _ _ => let env ← getEnv let searchEnv : Unit → TermElabM LValResolution := fun _ => do if let some (baseStructName, fullName) := findMethod? env structName fieldName then return LValResolution.const baseStructName structName fullName else if let some (structName', fullName) := findMethodAlias? env structName fieldName then return LValResolution.const structName' structName' fullName else throwLValError e eType m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'" -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do let fullName := Name.mkStr structName fieldName for localDecl in (← getLCtx) do if localDecl.binderInfo == BinderInfo.auxDecl then if let some localDeclFullName := (← read).auxDeclToFullName.find? localDecl.fvarId then if fullName == (privateToUserName? localDeclFullName).getD localDeclFullName then /- LVal notation is being used to make a "local" recursive call. -/ return LValResolution.localRec structName fullName localDecl.toExpr searchEnv () if isStructure env structName then match findField? env structName (Name.mkSimple fieldName) with | some baseStructName => return LValResolution.projFn baseStructName structName (Name.mkSimple fieldName) | none => searchCtx () else searchCtx () | none, LVal.fieldName _ _ (some suffix) _ => if e.isConst then throwUnknownConstant (e.constName! ++ suffix) else throwInvalidFieldNotation e eType | _, _ => throwInvalidFieldNotation e eType /-- whnfCore + implicit consumption. Example: given `e` with `eType := {α : Type} → (fun β => List β) α `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/ private partial def consumeImplicits (stx : Syntax) (e eType : Expr) (hasArgs : Bool) : TermElabM (Expr × Expr) := do let eType ← whnfCore eType match eType with | .forallE _ d b bi => if bi.isImplicit || (hasArgs && bi.isStrictImplicit) then let mvar ← mkFreshExprMVar d registerMVarErrorHoleInfo mvar.mvarId! stx consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) hasArgs else if bi.isInstImplicit then let mvar ← mkInstMVar d let r := mkApp e mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r consumeImplicits stx r (b.instantiate1 mvar) hasArgs else match d.getOptParamDefault? with | some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) hasArgs -- TODO: we do not handle autoParams here. | _ => return (e, eType) | _ => return (e, eType) private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) (hasArgs : Bool) : TermElabM (Expr × LValResolution) := do let (e, eType) ← consumeImplicits lval.getRef e eType hasArgs tryPostponeIfMVar eType /- If `eType` is still a metavariable application, we try to apply default instances to "unblock" it. -/ if (← isMVarApp eType) then synthesizeSyntheticMVarsUsingDefault let eType ← instantiateMVars eType try let lvalRes ← resolveLValAux e eType lval return (e, lvalRes) catch | ex@(Exception.error _ _) => let eType? ← unfoldDefinition? eType match eType? with | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) hasArgs | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(Exception.internal _ _) => throw ex private def resolveLVal (e : Expr) (lval : LVal) (hasArgs : Bool) : TermElabM (Expr × LValResolution) := do let eType ← inferType e resolveLValLoop lval e eType #[] hasArgs private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do let env ← getEnv match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => let mut e := e for projFunName in path do let projFn ← mkConst projFunName e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false) return e private def typeMatchesBaseName (type : Expr) (baseName : Name) : MetaM Bool := do if baseName == `Function then return (← whnfR type).isForall else if type.consumeMData.isAppOf baseName then return true else return (← whnfR type).isAppOf baseName /-- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`. This method first finds the parameter with a type of the form `(baseName ...)`. When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`. Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`. Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr) : TermElabM (Array Arg × Array NamedArg) := forallTelescopeReducing fType fun xs _ => do let mut argIdx := 0 -- position of the next explicit argument let mut remainingNamedArgs := namedArgs for i in [:xs.size] do let x := xs[i]! let xDecl ← x.fvarId!.getDecl /- If there is named argument with name `xDecl.userName`, then we skip it. -/ match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with | some idx => remainingNamedArgs := remainingNamedArgs.eraseIdx idx | none => let type := xDecl.type if (← typeMatchesBaseName type baseName) then /- We found a type of the form (baseName ...). First, we check if the current argument is an explicit one, and the current explicit position "fits" at `args` (i.e., it must be ≤ arg.size) -/ if argIdx ≤ args.size && xDecl.binderInfo.isExplicit then /- We insert `e` as an explicit argument -/ return (args.insertAt argIdx (Arg.expr e), namedArgs) /- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible if there isn't an argument with the same name occurring before it. -/ for j in [:i] do let prev := xs[j]! let prevDecl ← prev.fvarId!.getDecl if prevDecl.userName == xDecl.userName then throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used" return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e }) if xDecl.binderInfo.isExplicit then -- advance explicit argument position argIdx := argIdx + 1 throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name" private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (f : Expr) (lvals : List LVal) : TermElabM Expr := let rec loop : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis | f, lval::lvals => do if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then addDotCompletionInfo targetStx f expectedType? fieldStx let hasArgs := !namedArgs.isEmpty || !args.isEmpty let (f, lvalRes) ← resolveLVal f lval hasArgs match lvalRes with | LValResolution.projIdx structName idx => let f ← mkProjAndCheck structName idx f let f ← addTermInfo lval.getRef f loop f lvals | LValResolution.projFn baseStructName structName fieldName => let f ← mkBaseProjections baseStructName structName f if let some info := getFieldInfo? (← getEnv) baseStructName fieldName then if isPrivateNameFromImportedModule (← getEnv) info.projFn then throwError "field '{fieldName}' from structure '{structName}' is private" let projFn ← mkConst info.projFn let projFn ← addTermInfo lval.getRef projFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals else unreachable! | LValResolution.const baseStructName structName constName => let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f let projFn ← mkConst constName let projFn ← addTermInfo lval.getRef projFn if lvals.isEmpty then let projFnType ← inferType projFn let (args, namedArgs) ← addLValArg baseStructName constName f args namedArgs projFnType elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.localRec baseName fullName fvar => let fvar ← addTermInfo lval.getRef fvar if lvals.isEmpty then let fvarType ← inferType fvar let (args, namedArgs) ← addLValArg baseName fullName f args namedArgs fvarType elabAppArgs fvar namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals loop f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do if !lvals.isEmpty && explicit then throwError "invalid use of field notation with `@` modifier" elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (init := []) fun stx lvls => return (← elabLevel stx)::lvls /-! # Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let funLVals ← withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType? let overloaded := overloaded || funLVals.length > 1 -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do let lvals' := toLVals fields (first := true) let s ← observing do let f ← addTermInfo fIdent f expectedType? let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s where toName (fields : List Syntax) : Name := let rec go | [] => .anonymous | field :: fields => .mkStr (go fields) field.getId.toString go fields.reverse toLVals : List Syntax → (first : Bool) → List LVal | [], _ => [] | field::fields, true => .fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false | field::fields, false => .fieldName field field.getId.toString none fIdent :: toLVals fields false /-- Resolve `(.$id:ident)` using the expected type to infer namespace. -/ private partial def resolveDotName (id : Syntax) (expectedType? : Option Expr) : TermElabM Name := do tryPostponeIfNoneOrMVar expectedType? let some expectedType := expectedType? | throwError "invalid dotted identifier notation, expected type must be known" forallTelescopeReducing expectedType fun _ resultType => do go resultType expectedType #[] where go (resultType : Expr) (expectedType : Expr) (previousExceptions : Array Exception) : TermElabM Name := do let resultTypeFn := (← instantiateMVars resultType).cleanupAnnotations.getAppFn try tryPostponeIfMVar resultTypeFn let .const declName .. := resultTypeFn.cleanupAnnotations | throwError "invalid dotted identifier notation, expected type is not of the form (... → C ...) where C is a constant{indentExpr expectedType}" let idNew := declName ++ id.getId.eraseMacroScopes unless (← getEnv).contains idNew do throwError "invalid dotted identifier notation, unknown identifier `{idNew}` from expected type{indentExpr expectedType}" return idNew catch | ex@(.error ..) => match (← unfoldDefinition? resultType) with | some resultType => go (← whnfCore resultType) expectedType (previousExceptions.push ex) | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(.internal _ _) => throw ex private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := false }) do f.getArgs.foldlM (init := acc) fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc else let elabFieldName (e field : Syntax) := do let newLVals := field.identComponents.map fun comp => -- We use `none` in `suffix?` since `field` can't be part of a composite name LVal.fieldName comp (toString comp.getId) none e elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc let elabFieldIdx (e idxStx : Syntax) := do let idx := idxStx.isFieldIdx?.get! elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc match f with | `($(e).$idx:fieldIdx) => elabFieldIdx e idx | `($e |>.$idx:fieldIdx) => elabFieldIdx e idx | `($(e).$field:ident) => elabFieldName e field | `($e |>.$field:ident) => elabFieldName e field | `($_:ident@$_:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident.{$us,*}) => do let us ← elabExplicitUnivs us elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$_:ident.{$_us,*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$_) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | `(.$id:ident) => addCompletionInfo <| CompletionInfo.dotId f id.getId (← getLCtx) expectedType? let fConst ← mkConst (← resolveDotName id expectedType?) let fConst ← addTermInfo f fConst let s ← observing do let e ← elabAppLVals fConst lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s | _ => do let catchPostpone := !overloaded /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms. Recall that `observing` does not catch `postponeExceptionId`. -/ if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/ let s ← observing do if overloaded then elabTermEnsuringType f expectedType? catchPostpone else elabTerm f expectedType? return acc.push s else let s ← observing do let f ← elabTerm f none catchPostpone let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else return e return acc.push s /-- Return the successful candidates. Recall we have Syntax `choice` nodes and overloaded symbols when we open multiple namespaces. -/ private def getSuccesses (candidates : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let r₁ := candidates.filter fun | EStateM.Result.ok .. => true | _ => false if r₁.size ≤ 1 then return r₁ let r₂ ← candidates.filterM fun | .ok e s => do if e.isMVar then /- Make sure `e` is not a delayed coercion. Recall that coercion insertion may be delayed when the type and expected type contains metavariables that block TC resolution. When processing overloaded notation, we disallow delayed coercions at `e`. -/ try s.restore synthesizeSyntheticMVars -- Tries to process pending coercions (and elaboration tasks) let e ← instantiateMVars e if e.isMVar then /- If `e` is still a metavariable, and its `SyntheticMVarDecl` is a coercion, we discard this solution -/ if let some synDecl ← getSyntheticMVarDecl? e.mvarId! then if synDecl.kind matches SyntheticMVarKind.coe .. then return false catch _ => -- If `synthesizeSyntheticMVars` failed, we just eliminate the candidate. return false return true | _ => return false if r₂.size == 0 then return r₁ else return r₂ /-- Throw an error message that describes why each possible interpretation for the overloaded notation and symbols did not work. We use a nested error message to aggregate the exceptions produced by each failure. -/ private def mergeFailures (failures : Array (TermElabResult Expr)) : TermElabM α := do let exs := failures.map fun | .error ex _ => ex | _ => unreachable! throwErrorWithNestedErrors "overloaded" exs private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[] if candidates.size == 1 then applyResult candidates[0]! else let successes ← getSuccesses candidates if successes.size == 1 then applyResult successes[0]! else if successes.size > 1 then let msgs : Array MessageData ← successes.mapM fun success => do match success with | .ok e s => withMCtx s.meta.meta.mctx <| withEnv s.meta.core.env do addMessageContext m!"{e} : {← inferType e}" | _ => unreachable! throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}" else withRef f <| mergeFailures candidates /-- We annotate recursive applications with their `Syntax` node to make sure we can produce error messages with correct position information at `WF` and `Structural`. -/ -- TODO: It is overkill to store the whole `Syntax` object, and we have to make sure we erase it later. -- We should store only the position information in the future. -- Recall that we will need to have a compact way of storing position information in the future anyway, if we -- want to support debugging information private def annotateIfRec (stx : Syntax) (e : Expr) : TermElabM Expr := do if (← read).saveRecAppSyntax then let resultFn := e.getAppFn if resultFn.isFVar then let localDecl ← resultFn.fvarId!.getDecl if localDecl.isAuxDecl then return mkRecAppWithSyntax e stx return e @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => universeConstraintsCheckpoint do let (f, namedArgs, args, ellipsis) ← expandApp stx annotateIfRec stx (← elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType?) private def elabAtom : TermElab := fun stx expectedType? => do annotateIfRec stx (← elabAppAux stx #[] #[] (ellipsis := false) expectedType?) @[builtinTermElab ident] def elabIdent : TermElab := elabAtom @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom @[builtinTermElab dotIdent] def elabDotIdent : TermElab := elabAtom @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom @[builtinTermElab pipeProj] def elabPipeProj : TermElab | `($e |>.$f $args*), expectedType? => universeConstraintsCheckpoint do let (namedArgs, args, ellipsis) ← expandArgs args elabAppAux (← `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType? | _, _ => throwUnsupportedSyntax @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match stx with | `(@$_:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$_:ident.{$_us,*}) => elabAtom stx expectedType? | `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom builtin_initialize registerTraceClass `Elab.app end Lean.Elab.Term
cfd89e188c7201f7c51092ddfbda3a89c3d1f067
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/dold_kan/p_infty.lean
bfdcca8a76d360f10a7c058db206b9db621851c0
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,929
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.projections import category_theory.idempotents.functor_categories import category_theory.idempotents.functor_extension /-! # Construction of the projection `P_infty` for the Dold-Kan correspondence TODO (@joelriou) continue adding the various files referenced below In this file, we construct the projection `P_infty : K[X] ⟶ K[X]` by passing to the limit the projections `P q` defined in `projections.lean`. This projection is a critical tool in this formalisation of the Dold-Kan correspondence, because in the case of abelian categories, `P_infty` corresponds to the projection on the normalized Moore subcomplex, with kernel the degenerate subcomplex. (See `equivalence.lean` for the general strategy of proof.) -/ open category_theory open category_theory.category open category_theory.preadditive open category_theory.simplicial_object open category_theory.idempotents open opposite open_locale simplicial dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] {X : simplicial_object C} lemma P_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((P (q+1)).f n : X _[n] ⟶ _ ) = (P q).f n := begin cases n, { simp only [P_f_0_eq], }, { unfold P, simp only [add_right_eq_self, comp_add, homological_complex.comp_f, homological_complex.add_f_apply, comp_id], exact (higher_faces_vanish.of_P q n).comp_Hσ_eq_zero (nat.succ_le_iff.mp hqn), }, end lemma Q_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((Q (q+1)).f n : X _[n] ⟶ _ ) = (Q q).f n := by simp only [Q, homological_complex.sub_f_apply, P_is_eventually_constant hqn] /-- The endomorphism `P_infty : K[X] ⟶ K[X]` obtained from the `P q` by passing to the limit. -/ def P_infty : K[X] ⟶ K[X] := chain_complex.of_hom _ _ _ _ _ _ (λ n, ((P n).f n : X _[n] ⟶ _ )) (λ n, by simpa only [← P_is_eventually_constant (show n ≤ n, by refl), alternating_face_map_complex.obj_d_eq] using (P (n+1)).comm (n+1) n) @[simp] lemma P_infty_f_0 : (P_infty.f 0 : X _[0] ⟶ X _[0]) = 𝟙 _ := rfl lemma P_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ X _[n] ) = (P n).f n := rfl @[simp, reassoc] lemma P_infty_f_naturality (n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ P_infty.f n = P_infty.f n ≫ f.app (op [n]) := P_f_naturality n n f @[simp, reassoc] lemma P_infty_f_idem (n : ℕ) : (P_infty.f n : X _[n] ⟶ _) ≫ (P_infty.f n) = P_infty.f n := by simp only [P_infty_f, P_f_idem] @[simp, reassoc] lemma P_infty_idem : (P_infty : K[X] ⟶ _) ≫ P_infty = P_infty := by { ext n, exact P_infty_f_idem n, } variable (C) /-- `P_infty` induces a natural transformation, i.e. an endomorphism of the functor `alternating_face_map_complex C`. -/ @[simps] def nat_trans_P_infty : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ _, P_infty, naturality' := λ X Y f, by { ext n, exact P_infty_f_naturality n f, }, } /-- The natural transformation in each degree that is induced by `nat_trans_P_infty`. -/ @[simps] def nat_trans_P_infty_f (n : ℕ) := nat_trans_P_infty C ◫ 𝟙 (homological_complex.eval _ _ n) variable {C} @[simp] lemma map_P_infty_f {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (n : ℕ) : (P_infty : K[((whiskering C D).obj G).obj X] ⟶ _).f n = G.map ((P_infty : alternating_face_map_complex.obj X ⟶ _).f n) := by simp only [P_infty_f, map_P] /-- Given an object `Y : karoubi (simplicial_object C)`, this lemma computes `P_infty` for the associated object in `simplicial_object (karoubi C)` in terms of `P_infty` for `Y.X : simplicial_object C` and `Y.p`. -/ lemma karoubi_P_infty_f {Y : karoubi (simplicial_object C)} (n : ℕ) : ((P_infty : K[(karoubi_functor_category_embedding _ _).obj Y] ⟶ _).f n).f = Y.p.app (op [n]) ≫ (P_infty : K[Y.X] ⟶ _).f n := begin -- We introduce P_infty endomorphisms P₁, P₂, P₃, P₄ on various objects Y₁, Y₂, Y₃, Y₄. let Y₁ := (karoubi_functor_category_embedding _ _).obj Y, let Y₂ := Y.X, let Y₃ := (((whiskering _ _).obj (to_karoubi C)).obj Y.X), let Y₄ := (karoubi_functor_category_embedding _ _).obj ((to_karoubi _).obj Y.X), let P₁ : K[Y₁] ⟶ _ := P_infty, let P₂ : K[Y₂] ⟶ _ := P_infty, let P₃ : K[Y₃] ⟶ _ := P_infty, let P₄ : K[Y₄] ⟶ _ := P_infty, -- The statement of lemma relates P₁ and P₂. change (P₁.f n).f = Y.p.app (op [n]) ≫ P₂.f n, -- The proof proceeds by obtaining relations h₃₂, h₄₃, h₁₄. have h₃₂ : (P₃.f n).f = P₂.f n := karoubi.hom_ext.mp (map_P_infty_f (to_karoubi C) Y₂ n), have h₄₃ : P₄.f n = P₃.f n, { have h := functor.congr_obj (to_karoubi_comp_karoubi_functor_category_embedding _ _) Y₂, simp only [← nat_trans_P_infty_f_app], congr', }, let τ₁ := 𝟙 (karoubi_functor_category_embedding (simplex_categoryᵒᵖ) C), let τ₂ := nat_trans_P_infty_f (karoubi C) n, let τ := τ₁ ◫ τ₂, have h₁₄ := idempotents.nat_trans_eq τ Y, dsimp [τ, τ₁, τ₂, nat_trans_P_infty_f] at h₁₄, rw [id_comp, id_comp, comp_id, comp_id] at h₁₄, /- We use the three equalities h₃₂, h₄₃, h₁₄. -/ rw [← h₃₂, ← h₄₃, h₁₄], simp only [karoubi_functor_category_embedding.map_app_f, karoubi.decomp_id_p_f, karoubi.decomp_id_i_f, karoubi.comp], let π : Y₄ ⟶ Y₄ := (to_karoubi _ ⋙ karoubi_functor_category_embedding _ _).map Y.p, have eq := karoubi.hom_ext.mp (P_infty_f_naturality n π), simp only [karoubi.comp] at eq, dsimp [π] at eq, rw [← eq, reassoc_of (app_idem Y (op [n]))], end end dold_kan end algebraic_topology
1739a5b427166521cfff74bfab3e9743cf306a14
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/num_bug2.lean
b9c53b3aa1d07534f35c8b243050d8dbc818233a
[ "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
373
lean
import algebra.ring data.num open algebra variable A : Type variable s : ring A variable H0 : 0 = (0:A) -- since algebra defines notation '0' it should have precedence over num variable H1 : 1 = (1:A) -- since algebra defines notation '1' it should have precedence over num example : has_zero.zero A = has_zero.zero A := H0 example : has_one.one A = has_one.one A := H1
b827c23bea6cf9afbf9ed23a01165168c5eddead
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/mynat/definition.lean
0aeb2d7885da2d1defbe94a5c0bd94495c352f34
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
912
lean
import tactic.structure_helper import tactic.less_leaky /- mynat/definition.lean -- definition of mynat. Supplies: constants zero : mynat and one : mynat function S : mynat → mynat notation 0 for zero and 1 for one. The below code will be *invisible to the player* -/ -- definition of "the natural numbers" inductive mynat | zero : mynat | succ (n : mynat) : mynat namespace mynat instance : has_zero mynat := ⟨mynat.zero⟩ @[leakage] theorem mynat_zero_eq_zero : mynat.zero = 0 := rfl def one : mynat := succ 0 instance : has_one mynat := ⟨mynat.one⟩ theorem one_eq_succ_zero : 1 = succ 0 := rfl lemma zero_ne_succ (m : mynat) : (0 : mynat) ≠ succ m := λ h, by cases h lemma succ_inj {m n : mynat} (h : succ m = succ n) : m = n := by cases h; refl end mynat theorem ne_iff_implies_false ⦃a b : mynat⦄ : a ≠ b ↔ (a = b) → false := iff.rfl attribute [symm] ne.symm
255bd5c9958c749aa5b9d86015e4d90b9db3d192
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/p_infty.lean
9cd1e7881ba99675aacd44978425014cae41fc72
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,844
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.projections import category_theory.idempotents.functor_categories import category_theory.idempotents.functor_extension /-! # Construction of the projection `P_infty` for the Dold-Kan correspondence TODO (@joelriou) continue adding the various files referenced below In this file, we construct the projection `P_infty : K[X] ⟶ K[X]` by passing to the limit the projections `P q` defined in `projections.lean`. This projection is a critical tool in this formalisation of the Dold-Kan correspondence, because in the case of abelian categories, `P_infty` corresponds to the projection on the normalized Moore subcomplex, with kernel the degenerate subcomplex. (See `equivalence.lean` for the general strategy of proof.) -/ open category_theory open category_theory.category open category_theory.preadditive open category_theory.simplicial_object open category_theory.idempotents open opposite open_locale simplicial dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan variables {C : Type*} [category C] [preadditive C] {X : simplicial_object C} lemma P_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((P (q+1)).f n : X _[n] ⟶ _ ) = (P q).f n := begin cases n, { simp only [P_f_0_eq], }, { unfold P, simp only [add_right_eq_self, comp_add, homological_complex.comp_f, homological_complex.add_f_apply, comp_id], exact (higher_faces_vanish.of_P q n).comp_Hσ_eq_zero (nat.succ_le_iff.mp hqn), }, end lemma Q_is_eventually_constant {q n : ℕ} (hqn : n ≤ q) : ((Q (q+1)).f n : X _[n] ⟶ _ ) = (Q q).f n := by simp only [Q, homological_complex.sub_f_apply, P_is_eventually_constant hqn] /-- The endomorphism `P_infty : K[X] ⟶ K[X]` obtained from the `P q` by passing to the limit. -/ def P_infty : K[X] ⟶ K[X] := chain_complex.of_hom _ _ _ _ _ _ (λ n, ((P n).f n : X _[n] ⟶ _ )) (λ n, by simpa only [← P_is_eventually_constant (show n ≤ n, by refl), alternating_face_map_complex.obj_d_eq] using (P (n+1)).comm (n+1) n) /-- The endomorphism `Q_infty : K[X] ⟶ K[X]` obtained from the `Q q` by passing to the limit. -/ def Q_infty : K[X] ⟶ K[X] := 𝟙 _ - P_infty @[simp] lemma P_infty_f_0 : (P_infty.f 0 : X _[0] ⟶ X _[0]) = 𝟙 _ := rfl lemma P_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ X _[n] ) = (P n).f n := rfl @[simp] lemma Q_infty_f_0 : (Q_infty.f 0 : X _[0] ⟶ X _[0]) = 0 := by { dsimp [Q_infty], simp only [sub_self], } lemma Q_infty_f (n : ℕ) : (Q_infty.f n : X _[n] ⟶ X _[n] ) = (Q n).f n := rfl @[simp, reassoc] lemma P_infty_f_naturality (n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ P_infty.f n = P_infty.f n ≫ f.app (op [n]) := P_f_naturality n n f @[simp, reassoc] lemma Q_infty_f_naturality (n : ℕ) {X Y : simplicial_object C} (f : X ⟶ Y) : f.app (op [n]) ≫ Q_infty.f n = Q_infty.f n ≫ f.app (op [n]) := Q_f_naturality n n f @[simp, reassoc] lemma P_infty_f_idem (n : ℕ) : (P_infty.f n : X _[n] ⟶ _) ≫ (P_infty.f n) = P_infty.f n := by simp only [P_infty_f, P_f_idem] @[simp, reassoc] lemma P_infty_idem : (P_infty : K[X] ⟶ _) ≫ P_infty = P_infty := by { ext n, exact P_infty_f_idem n, } @[simp, reassoc] lemma Q_infty_f_idem (n : ℕ) : (Q_infty.f n : X _[n] ⟶ _) ≫ (Q_infty.f n) = Q_infty.f n := Q_f_idem _ _ @[simp, reassoc] lemma Q_infty_idem : (Q_infty : K[X] ⟶ _) ≫ Q_infty = Q_infty := by { ext n, exact Q_infty_f_idem n, } @[simp, reassoc] lemma P_infty_f_comp_Q_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ _) ≫ Q_infty.f n = 0 := begin dsimp only [Q_infty], simp only [homological_complex.sub_f_apply, homological_complex.id_f, comp_sub, comp_id, P_infty_f_idem, sub_self], end @[simp, reassoc] lemma P_infty_comp_Q_infty : (P_infty : K[X] ⟶ _) ≫ Q_infty = 0 := by { ext n, apply P_infty_f_comp_Q_infty_f, } @[simp, reassoc] lemma Q_infty_f_comp_P_infty_f (n : ℕ) : (Q_infty.f n : X _[n] ⟶ _) ≫ P_infty.f n = 0 := begin dsimp only [Q_infty], simp only [homological_complex.sub_f_apply, homological_complex.id_f, sub_comp, id_comp, P_infty_f_idem, sub_self], end @[simp, reassoc] lemma Q_infty_comp_P_infty : (Q_infty : K[X] ⟶ _) ≫ P_infty = 0 := by { ext n, apply Q_infty_f_comp_P_infty_f, } @[simp] lemma P_infty_add_Q_infty : (P_infty : K[X] ⟶ _) + Q_infty = 𝟙 _ := by { dsimp only [Q_infty], simp only [add_sub_cancel'_right], } lemma P_infty_f_add_Q_infty_f (n : ℕ) : (P_infty.f n : X _[n] ⟶ _ ) + Q_infty.f n = 𝟙 _ := homological_complex.congr_hom (P_infty_add_Q_infty) n variable (C) /-- `P_infty` induces a natural transformation, i.e. an endomorphism of the functor `alternating_face_map_complex C`. -/ @[simps] def nat_trans_P_infty : alternating_face_map_complex C ⟶ alternating_face_map_complex C := { app := λ _, P_infty, naturality' := λ X Y f, by { ext n, exact P_infty_f_naturality n f, }, } /-- The natural transformation in each degree that is induced by `nat_trans_P_infty`. -/ @[simps] def nat_trans_P_infty_f (n : ℕ) := nat_trans_P_infty C ◫ 𝟙 (homological_complex.eval _ _ n) variable {C} @[simp] lemma map_P_infty_f {D : Type*} [category D] [preadditive D] (G : C ⥤ D) [G.additive] (X : simplicial_object C) (n : ℕ) : (P_infty : K[((whiskering C D).obj G).obj X] ⟶ _).f n = G.map ((P_infty : alternating_face_map_complex.obj X ⟶ _).f n) := by simp only [P_infty_f, map_P] /-- Given an object `Y : karoubi (simplicial_object C)`, this lemma computes `P_infty` for the associated object in `simplicial_object (karoubi C)` in terms of `P_infty` for `Y.X : simplicial_object C` and `Y.p`. -/ lemma karoubi_P_infty_f {Y : karoubi (simplicial_object C)} (n : ℕ) : ((P_infty : K[(karoubi_functor_category_embedding _ _).obj Y] ⟶ _).f n).f = Y.p.app (op [n]) ≫ (P_infty : K[Y.X] ⟶ _).f n := begin -- We introduce P_infty endomorphisms P₁, P₂, P₃, P₄ on various objects Y₁, Y₂, Y₃, Y₄. let Y₁ := (karoubi_functor_category_embedding _ _).obj Y, let Y₂ := Y.X, let Y₃ := (((whiskering _ _).obj (to_karoubi C)).obj Y.X), let Y₄ := (karoubi_functor_category_embedding _ _).obj ((to_karoubi _).obj Y.X), let P₁ : K[Y₁] ⟶ _ := P_infty, let P₂ : K[Y₂] ⟶ _ := P_infty, let P₃ : K[Y₃] ⟶ _ := P_infty, let P₄ : K[Y₄] ⟶ _ := P_infty, -- The statement of lemma relates P₁ and P₂. change (P₁.f n).f = Y.p.app (op [n]) ≫ P₂.f n, -- The proof proceeds by obtaining relations h₃₂, h₄₃, h₁₄. have h₃₂ : (P₃.f n).f = P₂.f n := karoubi.hom_ext.mp (map_P_infty_f (to_karoubi C) Y₂ n), have h₄₃ : P₄.f n = P₃.f n, { have h := functor.congr_obj (to_karoubi_comp_karoubi_functor_category_embedding _ _) Y₂, simp only [← nat_trans_P_infty_f_app], congr', }, let τ₁ := 𝟙 (karoubi_functor_category_embedding (simplex_categoryᵒᵖ) C), let τ₂ := nat_trans_P_infty_f (karoubi C) n, let τ := τ₁ ◫ τ₂, have h₁₄ := idempotents.nat_trans_eq τ Y, dsimp [τ, τ₁, τ₂, nat_trans_P_infty_f] at h₁₄, rw [id_comp, id_comp, comp_id, comp_id] at h₁₄, /- We use the three equalities h₃₂, h₄₃, h₁₄. -/ rw [← h₃₂, ← h₄₃, h₁₄], simp only [karoubi_functor_category_embedding.map_app_f, karoubi.decomp_id_p_f, karoubi.decomp_id_i_f, karoubi.comp_f], let π : Y₄ ⟶ Y₄ := (to_karoubi _ ⋙ karoubi_functor_category_embedding _ _).map Y.p, have eq := karoubi.hom_ext.mp (P_infty_f_naturality n π), simp only [karoubi.comp_f] at eq, dsimp [π] at eq, rw [← eq, reassoc_of (app_idem Y (op [n]))], end end dold_kan end algebraic_topology
50b185976a541c1f14270ba9e4d22c347a5f111d
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/mv_polynomial/equiv.lean
a1158863d41a6e300b78fb387bc8fc2e43df2069
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,812
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.rename import data.equiv.fin /-! # Equivalences between polynomial rings This file establishes a number of equivalences between polynomial rings, based on equivalences between the underlying types. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ## Tags equivalence, isomorphism, morphism, ring hom, hom -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section equiv variables (R) [comm_semiring R] /-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def pempty_ring_equiv : mv_polynomial pempty R ≃+* R := { to_fun := mv_polynomial.eval₂ (ring_hom.id _) $ pempty.elim, inv_fun := C, left_inv := is_id (C.comp (eval₂_hom (ring_hom.id _) pempty.elim)) (assume a : R, by { dsimp, rw [eval₂_C], refl }) (assume a, a.elim), right_inv := λ r, eval₂_C _ _ _, map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _ } /-- The algebra isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def pempty_alg_equiv : mv_polynomial pempty R ≃ₐ[R] R := { to_fun := mv_polynomial.eval₂ (ring_hom.id _) $ pempty.elim, inv_fun := C, left_inv := is_id (C.comp (eval₂_hom (ring_hom.id _) pempty.elim)) (assume a : R, by { dsimp, rw [eval₂_C], refl }) (assume a, a.elim), right_inv := λ r, eval₂_C _ _ _, map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _, commutes' := λ _, by rw [mv_polynomial.algebra_map_eq]; simp } /-- The ring isomorphism between multivariable polynomials in a single variable and polynomials over the ground ring. -/ @[simps] def punit_ring_equiv : mv_polynomial punit R ≃+* polynomial R := { to_fun := eval₂ polynomial.C (λu:punit, polynomial.X), inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star), left_inv := begin let f : polynomial R →+* mv_polynomial punit R := ring_hom.of (polynomial.eval₂ mv_polynomial.C (X punit.star)), let g : mv_polynomial punit R →+* polynomial R := ring_hom.of (eval₂ polynomial.C (λu:punit, polynomial.X)), show ∀ p, f.comp g p = p, apply is_id, { assume a, dsimp, rw [eval₂_C, polynomial.eval₂_C] }, { rintros ⟨⟩, dsimp, rw [eval₂_X, polynomial.eval₂_X] } end, right_inv := assume p, polynomial.induction_on p (assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C]) (assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq]) (assume p n hp, by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C, eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]), map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _ } /-- The ring isomorphism between multivariable polynomials induced by an equivalence of the variables. -/ @[simps] def ring_equiv_of_equiv (e : S₁ ≃ S₂) : mv_polynomial S₁ R ≃+* mv_polynomial S₂ R := { to_fun := rename e, inv_fun := rename e.symm, left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p, right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p, map_mul' := (rename e).map_mul, map_add' := (rename e).map_add } /-- The algebra isomorphism between multivariable polynomials induced by an equivalence of the variables. -/ @[simps] def alg_equiv_of_equiv (e : S₁ ≃ S₂) : mv_polynomial S₁ R ≃ₐ[R] mv_polynomial S₂ R := { to_fun := rename e, inv_fun := rename e.symm, left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p, right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p, commutes' := λ p, by simp only [alg_hom.commutes], .. rename e } /-- The ring isomorphism between multivariable polynomials induced by a ring isomorphism of the ground ring. -/ @[simps] def ring_equiv_congr [comm_semiring S₂] (e : R ≃+* S₂) : mv_polynomial S₁ R ≃+* mv_polynomial S₁ S₂ := { to_fun := map (e : R →+* S₂), inv_fun := map (e.symm : S₂ →+* R), left_inv := assume p, have (e.symm : S₂ →+* R).comp (e : R →+* S₂) = ring_hom.id _, { ext a, exact e.symm_apply_apply a }, by simp only [map_map, this, map_id], right_inv := assume p, have (e : R →+* S₂).comp (e.symm : S₂ →+* R) = ring_hom.id _, { ext a, exact e.apply_symm_apply a }, by simp only [map_map, this, map_id], map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _ } section variables (S₁ S₂ S₃) /-- The function from multivariable polynomials in a sum of two types, to multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. See `sum_ring_equiv` for the ring isomorphism. -/ def sum_to_iter : mv_polynomial (S₁ ⊕ S₂) R →+* mv_polynomial S₁ (mv_polynomial S₂ R) := eval₂_hom (C.comp C) (λbc, sum.rec_on bc X (C ∘ X)) instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter R S₁ S₂) := eval₂.is_semiring_hom _ _ @[simp] lemma sum_to_iter_C (a : R) : sum_to_iter R S₁ S₂ (C a) = C (C a) := eval₂_C _ _ a @[simp] lemma sum_to_iter_Xl (b : S₁) : sum_to_iter R S₁ S₂ (X (sum.inl b)) = X b := eval₂_X _ _ (sum.inl b) @[simp] lemma sum_to_iter_Xr (c : S₂) : sum_to_iter R S₁ S₂ (X (sum.inr c)) = C (X c) := eval₂_X _ _ (sum.inr c) /-- The function from multivariable polynomials in one type, with coefficents in multivariable polynomials in another type, to multivariable polynomials in the sum of the two types. See `sum_ring_equiv` for the ring isomorphism. -/ def iter_to_sum : mv_polynomial S₁ (mv_polynomial S₂ R) →+* mv_polynomial (S₁ ⊕ S₂) R := eval₂_hom (ring_hom.of (eval₂ C (X ∘ sum.inr))) (X ∘ sum.inl) lemma iter_to_sum_C_C (a : R) : iter_to_sum R S₁ S₂ (C (C a)) = C a := eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _) lemma iter_to_sum_X (b : S₁) : iter_to_sum R S₁ S₂ (X b) = X (sum.inl b) := eval₂_X _ _ _ lemma iter_to_sum_C_X (c : S₂) : iter_to_sum R S₁ S₂ (C (X c)) = X (sum.inr c) := eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _) /-- A helper function for `sum_ring_equiv`. -/ @[simps] def mv_polynomial_equiv_mv_polynomial [comm_semiring S₃] (f : mv_polynomial S₁ R →+* mv_polynomial S₂ S₃) (g : mv_polynomial S₂ S₃ →+* mv_polynomial S₁ R) (hfgC : ∀a, f (g (C a)) = C a) (hfgX : ∀n, f (g (X n)) = X n) (hgfC : ∀a, g (f (C a)) = C a) (hgfX : ∀n, g (f (X n)) = X n) : mv_polynomial S₁ R ≃+* mv_polynomial S₂ S₃ := { to_fun := f, inv_fun := g, left_inv := is_id (ring_hom.comp _ _) hgfC hgfX, right_inv := is_id (ring_hom.comp _ _) hfgC hfgX, map_mul' := f.map_mul, map_add' := f.map_add } /-- The ring isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_ring_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃+* mv_polynomial S₁ (mv_polynomial S₂ R) := begin apply @mv_polynomial_equiv_mv_polynomial R (S₁ ⊕ S₂) _ _ _ _ (sum_to_iter R S₁ S₂) (iter_to_sum R S₁ S₂), { assume p, convert hom_eq_hom ((sum_to_iter R S₁ S₂).comp ((iter_to_sum R S₁ S₂).comp C)) C _ _ p, { assume a, dsimp, rw [iter_to_sum_C_C R S₁ S₂, sum_to_iter_C R S₁ S₂] }, { assume c, dsimp, rw [iter_to_sum_C_X R S₁ S₂, sum_to_iter_Xr R S₁ S₂] } }, { assume b, rw [iter_to_sum_X R S₁ S₂, sum_to_iter_Xl R S₁ S₂] }, { assume a, rw [sum_to_iter_C R S₁ S₂, iter_to_sum_C_C R S₁ S₂] }, { assume n, cases n with b c, { rw [sum_to_iter_Xl, iter_to_sum_X] }, { rw [sum_to_iter_Xr, iter_to_sum_C_X] } }, end /-- The ring isomorphism between multivariable polynomials in `option S₁` and polynomials with coefficients in `mv_polynomial S₁ R`. -/ def option_equiv_left : mv_polynomial (option S₁) R ≃+* polynomial (mv_polynomial S₁ R) := (ring_equiv_of_equiv R $ (equiv.option_equiv_sum_punit.{0} S₁).trans (equiv.sum_comm _ _)).trans $ (sum_ring_equiv R _ _).trans $ punit_ring_equiv _ /-- The ring isomorphism between multivariable polynomials in `option S₁` and multivariable polynomials with coefficients in polynomials. -/ def option_equiv_right : mv_polynomial (option S₁) R ≃+* mv_polynomial S₁ (polynomial R) := (ring_equiv_of_equiv R $ equiv.option_equiv_sum_punit.{0} S₁).trans $ (sum_ring_equiv R S₁ unit).trans $ ring_equiv_congr (mv_polynomial unit R) (punit_ring_equiv R) /-- The ring isomorphism between multivariable polynomials in `fin (n + 1)` and polynomials over multivariable polynomials in `fin n`. -/ def fin_succ_equiv (n : ℕ) : mv_polynomial (fin (n + 1)) R ≃+* polynomial (mv_polynomial (fin n) R) := (ring_equiv_of_equiv R (fin_succ_equiv n)).trans (option_equiv_left R (fin n)) lemma fin_succ_equiv_eq (n : ℕ) : (fin_succ_equiv R n : mv_polynomial (fin (n + 1)) R →+* polynomial (mv_polynomial (fin n) R)) = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) := begin apply ring_hom_ext, { intro r, dsimp [ring_equiv.coe_ring_hom, fin_succ_equiv, option_equiv_left, sum_ring_equiv], simp only [sum_to_iter_C, eval₂_C, rename_C, ring_hom.coe_comp] }, { intro i, dsimp [ring_equiv.coe_ring_hom, fin_succ_equiv, option_equiv_left, sum_ring_equiv, _root_.fin_succ_equiv], by_cases hi : i = 0, { simp only [hi, fin.cases_zero, sum.swap, rename_X, equiv.option_equiv_sum_punit_none, equiv.sum_comm_apply, comp_app, sum_to_iter_Xl, eval₂_X] }, { rw [← fin.succ_pred i hi], simp only [rename_X, equiv.sum_comm_apply, comp_app, eval₂_X, equiv.option_equiv_sum_punit_some, sum.swap, fin.cases_succ, sum_to_iter_Xr, eval₂_C] } } end @[simp] lemma fin_succ_equiv_apply (n : ℕ) (p : mv_polynomial (fin (n + 1)) R) : fin_succ_equiv R n p = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) p := by { rw ← fin_succ_equiv_eq, refl } lemma fin_succ_equiv_comp_C_eq_C {R : Type u} [comm_semiring R] (n : ℕ) : ((mv_polynomial.fin_succ_equiv R n).symm.to_ring_hom).comp ((polynomial.C).comp (mv_polynomial.C)) = (mv_polynomial.C : R →+* mv_polynomial (fin n.succ) R) := begin refine ring_hom.ext (λ x, _), rw ring_hom.comp_apply, refine (mv_polynomial.fin_succ_equiv R n).injective (trans ((mv_polynomial.fin_succ_equiv R n).apply_symm_apply _) _), simp only [mv_polynomial.fin_succ_equiv_apply, mv_polynomial.eval₂_hom_C], end end end equiv end mv_polynomial
213bd1b7c65687149f7c3d7b75aa5a610c59e345
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/universal/monic.lean
bd725f24a9b245f18b340195c048db0322ed6856
[]
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
933
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.limits.equalizers import category_theory.abelian.monic open category_theory open category_theory.limits namespace category_theory.universal.monic universes u v variables {C : Type u} [category.{u v} C] {X Y Z : C} structure regular_mono (f : X ⟶ Y) := (Z : C) (a b : Y ⟶ Z) (w : f ≫ a = f ≫ b) (e : is_equalizer ⟨ ⟨ X ⟩, f, w ⟩) -- EXERCISE -- def SplitMonic_implies_RegularMonic -- {f : Hom X Y} -- (s : SplitMonic f) : RegularMonic f := sorry -- EXERCISE -- def RegularMonic_implies_Monic -- {f : Hom X Y} -- (s : RegularMonic f) : Monic f := sorry structure regular_epi (f : Y ⟶ Z) := (X : C) (a b : X ⟶ Y) (w : a ≫ f = b ≫ f) (c : is_coequalizer ⟨ ⟨ Z ⟩, f, w ⟩) end category_theory.universal.monic
d1c7dc5cdd16dea7dd31d52bfceff84b226b988d
21ee31472b6ad765d2d9f8f655301d8b6ad921c2
/math/leanprover/lean1.lean
3f750c792a3dc26a06099f54f9dd3043e815d542
[]
no_license
anandijain/learning
2229472c40ca651a20cff9c52dabc3e6c3a8aeca
14c98cb0b89805c74e9e8d1afba7945d69ec4b67
refs/heads/master
1,594,406,566,371
1,586,458,652,000
1,586,458,652,000
204,337,259
0
0
null
null
null
null
UTF-8
Lean
false
false
560
lean
import system.io open io def get_file (fn : io char_buffer): io char_buffer := fs.read_file "/home/sippycups/learning/math/leanprover/" ++ fn def hello_world : io unit := do s <- get_file, put_str s.to_string -- #check (@put_str : string → io unit) -- #check(@get_line : io string) #eval hello_world -- theorem and_com (p q : Prop) : p ∧ q → q ∧ p := -- assume hpq : p ∧ q, -- have hp : p, from and.left hpq, -- have hq : q, from and.right hpq, -- show q ∧ p, from and.intro hq hp -- inductive partial_order (n : nat, q : order)
de25016e4bfa425f7c6e21c4c634daff51fec706
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/theories/analysis/ivt.lean
2894a443b305c127d2e5b1c9a494c52f6d437091
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
11,047
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis The intermediate value theorem. -/ import .real_limit open real analysis set classical noncomputable theory private definition inter_sup (a b : ℝ) (f : ℝ → ℝ) := sup {x | x < b ∧ f x < 0} section parameters {f : ℝ → ℝ} (Hf : continuous f) {a b : ℝ} (Hab : a < b) (Ha : f a < 0) (Hb : f b > 0) include Hf Ha Hb Hab private theorem Hinh : ∃ x, x ∈ {x | x < b ∧ f x < 0} := exists.intro a (and.intro Hab Ha) private theorem Hmem : ∀ x, x ∈ {x | x < b ∧ f x < 0} → x ≤ b := λ x Hx, le_of_lt (and.left Hx) private theorem Hsupleb : inter_sup a b f ≤ b := sup_le (Hinh) Hmem local notation 2 := of_num 1 + of_num 1 private theorem ex_delta_lt {x : ℝ} (Hx : f x < 0) (Hxb : x < b) : ∃ δ : ℝ, δ > 0 ∧ x + δ < b ∧ f (x + δ) < 0 := begin let Hcont := neg_on_nbhd_of_cts_of_neg Hf Hx, cases Hcont with δ Hδ, {cases em (x + δ < b) with Haδ Haδ, existsi δ / 2, split, {exact div_pos_of_pos_of_pos (and.left Hδ) two_pos}, split, {apply lt.trans, apply add_lt_add_left, exact div_two_lt_of_pos (and.left Hδ), exact Haδ}, {apply and.right Hδ, krewrite [abs_sub, sub_add_eq_sub_sub, sub_self, zero_sub, abs_neg, abs_of_pos (div_pos_of_pos_of_pos (and.left Hδ) two_pos)], exact div_two_lt_of_pos (and.left Hδ)}, existsi (b - x) / 2, split, {apply div_pos_of_pos_of_pos, exact sub_pos_of_lt Hxb, exact two_pos}, split, {apply add_midpoint Hxb}, {apply and.right Hδ, krewrite [abs_sub, sub_add_eq_sub_sub, sub_self, zero_sub, abs_neg, abs_of_pos (div_pos_of_pos_of_pos (sub_pos_of_lt Hxb) two_pos)], apply lt_of_lt_of_le, apply div_two_lt_of_pos (sub_pos_of_lt Hxb), apply sub_left_le_of_le_add, apply le_of_not_gt Haδ}} end private lemma sup_near_b {δ : ℝ} (Hpos : 0 < δ) (Hgeb : inter_sup a b f + δ / 2 ≥ b) : abs (inter_sup a b f - b) < δ := begin apply abs_lt_of_lt_of_neg_lt, apply sub_lt_left_of_lt_add, apply lt_of_le_of_lt, apply Hsupleb, apply lt_add_of_pos_right Hpos, rewrite neg_sub, apply sub_lt_left_of_lt_add, apply lt_of_le_of_lt, apply Hgeb, apply add_lt_add_left, apply div_two_lt_of_pos Hpos end private lemma delta_of_lt (Hflt : f (inter_sup a b f) < 0) : ∃ δ : ℝ, δ > 0 ∧ inter_sup a b f + δ < b ∧ f (inter_sup a b f + δ) < 0 := if Hlt : inter_sup a b f < b then ex_delta_lt Hflt Hlt else begin let Heq := eq_of_le_of_ge Hsupleb (le_of_not_gt Hlt), apply absurd Hflt, apply not_lt_of_ge, apply le_of_lt, rewrite Heq, exact Hb end private theorem sup_fn_interval_aux1 : f (inter_sup a b f) ≥ 0 := have ¬ f (inter_sup a b f) < 0, from (suppose f (inter_sup a b f) < 0, obtain δ Hδ, from delta_of_lt this, have inter_sup a b f + δ ∈ {x | x < b ∧ f x < 0}, from and.intro (and.left (and.right Hδ)) (and.right (and.right Hδ)), have ¬ inter_sup a b f < inter_sup a b f + δ, from not_lt_of_ge (le_sup this Hmem), show false, from this (lt_add_of_pos_right (and.left Hδ))), le_of_not_gt this private theorem sup_fn_interval_aux2 : f (inter_sup a b f) ≤ 0 := have ¬ f (inter_sup a b f) > 0, from (assume Hfsup : f (inter_sup a b f) > 0, obtain δ Hδ, from pos_on_nbhd_of_cts_of_pos Hf Hfsup, have ∀ x, x ∈ {x | x < b ∧ f x < 0} → x ≤ inter_sup a b f - δ / 2, from (take x, assume Hxset : x ∈ {x | x < b ∧ f x < 0}, have ¬ x > inter_sup a b f - δ / 2, from (assume Hngt, have Habs : abs (x - inter_sup a b f) < δ, begin rewrite abs_sub, apply abs_lt_of_lt_of_neg_lt, apply sub_lt_of_sub_lt, apply gt.trans, exact Hngt, apply sub_lt_sub_left, exact div_two_lt_of_pos (and.left Hδ), rewrite neg_sub, apply lt_of_le_of_lt, rotate 1, apply and.left Hδ, apply sub_nonpos_of_le, apply le_sup, exact Hxset, exact Hmem end, have f x > 0, from and.right Hδ x Habs, show false, from (not_lt_of_gt this) (and.right Hxset)), le_of_not_gt this), have Hle : inter_sup a b f ≤ inter_sup a b f - δ / 2, from sup_le Hinh this, show false, from not_le_of_gt (sub_lt_of_pos _ (div_pos_of_pos_of_pos (and.left Hδ) (two_pos))) Hle), le_of_not_gt this private theorem sup_fn_interval : f (inter_sup a b f) = 0 := eq_of_le_of_ge sup_fn_interval_aux2 sup_fn_interval_aux1 private theorem intermediate_value_incr_aux2 : ∃ δ : ℝ, δ > 0 ∧ a + δ < b ∧ f (a + δ) < 0 := begin let Hcont := neg_on_nbhd_of_cts_of_neg Hf Ha, cases Hcont with δ Hδ, {cases em (a + δ < b) with Haδ Haδ, existsi δ / 2, split, {exact div_pos_of_pos_of_pos (and.left Hδ) two_pos}, split, {apply lt.trans, apply add_lt_add_left, exact div_two_lt_of_pos (and.left Hδ), exact Haδ}, {apply and.right Hδ, krewrite [abs_sub, sub_add_eq_sub_sub, sub_self, zero_sub, abs_neg, abs_of_pos (div_pos_of_pos_of_pos (and.left Hδ) two_pos)], exact div_two_lt_of_pos (and.left Hδ)}, existsi (b - a) / 2, split, {apply div_pos_of_pos_of_pos, exact sub_pos_of_lt Hab, exact two_pos}, split, {apply add_midpoint Hab}, {apply and.right Hδ, krewrite [abs_sub, sub_add_eq_sub_sub, sub_self, zero_sub, abs_neg, abs_of_pos (div_pos_of_pos_of_pos (sub_pos_of_lt Hab) two_pos)], apply lt_of_lt_of_le, apply div_two_lt_of_pos (sub_pos_of_lt Hab), apply sub_left_le_of_le_add, apply le_of_not_gt Haδ}} end theorem intermediate_value_incr_zero : ∃ c, a < c ∧ c < b ∧ f c = 0 := begin existsi inter_sup a b f, split, {cases intermediate_value_incr_aux2 with δ Hδ, apply lt_of_lt_of_le, apply lt_add_of_pos_right, exact and.left Hδ, apply le_sup, exact and.right Hδ, intro x Hx, apply le_of_lt, exact and.left Hx}, split, {cases pos_on_nbhd_of_cts_of_pos Hf Hb with δ Hδ, apply lt_of_le_of_lt, rotate 1, apply sub_lt_of_pos, exact and.left Hδ, rotate_right 1, apply sup_le, exact exists.intro a (and.intro Hab Ha), intro x Hx, apply le_of_not_gt, intro Hxgt, have Hxgt' : b - x < δ, from sub_lt_of_sub_lt Hxgt, krewrite [-(abs_of_pos (sub_pos_of_lt (and.left Hx))) at Hxgt', abs_sub at Hxgt'], note Hxgt'' := and.right Hδ _ Hxgt', exact not_lt_of_ge (le_of_lt Hxgt'') (and.right Hx)}, {exact sup_fn_interval} end end theorem intermediate_value_decr_zero {f : ℝ → ℝ} (Hf : continuous f) {a b : ℝ} (Hab : a < b) (Ha : f a > 0) (Hb : f b < 0) : ∃ c, a < c ∧ c < b ∧ f c = 0 := begin have Ha' : - f a < 0, from neg_neg_of_pos Ha, have Hb' : - f b > 0, from neg_pos_of_neg Hb, have Hcon : continuous (λ x, - f x), from continuous_neg_of_continuous Hf, let Hiv := intermediate_value_incr_zero Hcon Hab Ha' Hb', cases Hiv with c Hc, existsi c, split, exact and.left Hc, split, exact and.left (and.right Hc), apply eq_zero_of_neg_eq_zero, apply and.right (and.right Hc) end theorem intermediate_value_incr {f : ℝ → ℝ} (Hf : continuous f) {a b : ℝ} (Hab : a < b) {v : ℝ} (Hav : f a < v) (Hbv : f b > v) : ∃ c, a < c ∧ c < b ∧ f c = v := have Hav' : f a - v < 0, from sub_neg_of_lt Hav, have Hbv' : f b - v > 0, from sub_pos_of_lt Hbv, have Hcon : continuous (λ x, f x - v), from continuous_offset_of_continuous Hf _, have Hiv : ∃ c, a < c ∧ c < b ∧ f c - v = 0, from intermediate_value_incr_zero Hcon Hab Hav' Hbv', obtain c Hc, from Hiv, exists.intro c (and.intro (and.left Hc) (and.intro (and.left (and.right Hc)) (eq_of_sub_eq_zero (and.right (and.right Hc))))) theorem intermediate_value_decr {f : ℝ → ℝ} (Hf : continuous f) {a b : ℝ} (Hab : a < b) {v : ℝ} (Hav : f a > v) (Hbv : f b < v) : ∃ c, a < c ∧ c < b ∧ f c = v := have Hav' : f a - v > 0, from sub_pos_of_lt Hav, have Hbv' : f b - v < 0, from sub_neg_of_lt Hbv, have Hcon : continuous (λ x, f x - v), from continuous_offset_of_continuous Hf _, have Hiv : ∃ c, a < c ∧ c < b ∧ f c - v = 0, from intermediate_value_decr_zero Hcon Hab Hav' Hbv', obtain c Hc, from Hiv, exists.intro c (and.intro (and.left Hc) (and.intro (and.left (and.right Hc)) (eq_of_sub_eq_zero (and.right (and.right Hc))))) theorem intermediate_value_incr_weak {f : ℝ → ℝ} (Hf : continuous f) {a b : ℝ} (Hab : a ≤ b) {v : ℝ} (Hav : f a ≤ v) (Hbv : f b ≥ v) : ∃ c, a ≤ c ∧ c ≤ b ∧ f c = v := begin cases lt_or_eq_of_le Hab with Hlt Heq, cases lt_or_eq_of_le Hav with Hlt' Heq', cases lt_or_eq_of_le Hbv with Hlt'' Heq'', cases intermediate_value_incr Hf Hlt Hlt' Hlt'' with c Hc, cases Hc with Hc1 Hc2, cases Hc2 with Hc2 Hc3, existsi c, repeat (split; apply le_of_lt; assumption), assumption, existsi b, split, apply le_of_lt, assumption, split, apply le.refl, rewrite Heq'', existsi a, split, apply le.refl, split, apply le_of_lt, repeat assumption, existsi a, split, apply le.refl, split, assumption, apply eq_of_le_of_ge, apply Hav, rewrite Heq, apply Hbv end section roots private definition sqr_lb (x : ℝ) : ℝ := 0 private theorem sqr_lb_is_lb (x : ℝ) (H : x ≥ 0) : (sqr_lb x) * (sqr_lb x) ≤ x := by rewrite [↑sqr_lb, zero_mul]; assumption private definition sqr_ub (x : ℝ) : ℝ := x + 1 private theorem sqr_ub_is_ub (x : ℝ) (H : x ≥ 0) : (sqr_ub x) * (sqr_ub x) ≥ x := begin rewrite [↑sqr_ub, left_distrib, mul_one, right_distrib, one_mul, {x + 1}add.comm, -*add.assoc], apply le_add_of_nonneg_left, repeat apply add_nonneg, apply mul_nonneg, repeat assumption, apply zero_le_one end private theorem lb_le_ub (x : ℝ) (H : x ≥ 0) : sqr_lb x ≤ sqr_ub x := begin rewrite [↑sqr_lb, ↑sqr_ub], apply add_nonneg, assumption, apply zero_le_one end private lemma sqr_cts : continuous (λ x : ℝ, x * x) := continuous_mul_of_continuous id_continuous id_continuous definition sqrt (x : ℝ) : ℝ := if H : x ≥ 0 then some (intermediate_value_incr_weak sqr_cts (lb_le_ub x H) (sqr_lb_is_lb x H) (sqr_ub_is_ub x H)) else 0 theorem sqrt_spec (x : ℝ) (H : x ≥ 0) : sqrt x * sqrt x = x := begin rewrite [↑sqrt, dif_pos H], note Hs := some_spec (intermediate_value_incr_weak sqr_cts (lb_le_ub x H) (sqr_lb_is_lb x H) (sqr_ub_is_ub x H)), cases Hs with Hs1 Hs2, cases Hs2, assumption end end roots
0f632127a58aed4af50ec36f44fd870e86e2e10c
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/category/traversable/lemmas.lean
44ad4da0dfb90b987f83f4ad32adf50466567364
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
2,274
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Lemmas about traversing collections. Inspired by: The Essence of the Iterator Pattern Jeremy Gibbons and Bruno César dos Santos Oliveira In Journal of Functional Programming. Vol. 19. No. 3&4. Pages 377−402. 2009. http://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf -/ import tactic.cache import category.traversable.basic universe variables u open is_lawful_traversable open function (hiding comp) open functor attribute [functor_norm] is_lawful_traversable.naturality namespace traversable variable {t : Type u → Type u} variables [traversable t] [is_lawful_traversable t] variables {G H : Type u → Type u} variables [applicative G] [is_lawful_applicative G] variables [applicative H] [is_lawful_applicative H] variables {α β γ : Type u} variables g : α → G β variables h : β → H γ variables f : β → γ variables G H def pure_transformation : applicative_transformation id G := begin refine { F := @pure G _, .. }; intros, { refl }, { simp, refl } end variables {G H} lemma traverse_eq_map_ident (x : t β) : traverse (id.mk ∘ f) x = id.mk (f <$> x) := calc traverse (id.mk ∘ f) x = traverse id.mk (f <$> x) : by rw [← traverse_map] ... = (<$>) f <$> x : by simp [id_traverse]; refl lemma purity (x : t α) : traverse pure x = (pure x : G (t α)) := let η := pure_transformation G in calc traverse (@pure G _ _) x = traverse (pure ∘ id.mk) x : rfl ... = traverse (@η _ ∘ id.mk) x : rfl ... = η (traverse id.mk x) : by rw [naturality] ... = η x : by rw [id_traverse] ... = pure x : rfl lemma id_sequence (x : t α) : sequence (id.mk <$> x) = id.mk x := by simp [sequence,traverse_map,id_traverse]; refl lemma comp_sequence (x : t (G (H α))) : sequence (comp.mk <$> x) = comp.mk (sequence <$> sequence x) := by simp [sequence,traverse_map]; rw ← comp_traverse; simp [map_id] lemma naturality' (η : applicative_transformation G H) (x : t (G α)) : η (sequence x) = sequence (@η _ <$> x) := by simp [sequence,naturality,traverse_map] end traversable
16271a2e812a321a9c78f6a9761dea463ee44d26
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/analysis/complex/polynomial.lean
dfd928da51f09dd64eb52f37493a3a96fc5095d6
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
5,972
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.polynomial topology.algebra.polynomial analysis.complex.exponential open complex polynomial metric filter is_absolute_value set lattice namespace complex lemma exists_forall_abs_polynomial_eval_le (p : polynomial ℂ) : ∃ x, ∀ y, (p.eval x).abs ≤ (p.eval y).abs := if hp0 : 0 < degree p then let ⟨r, hr0, hr⟩ := polynomial.tendsto_infinity complex.abs hp0 ((p.eval 0).abs) in let ⟨x, hx₁, hx₂⟩ := (proper_space.compact_ball (0:ℂ) r).exists_forall_le (set.ne_empty_iff_exists_mem.2 ⟨0, by simp [le_of_lt hr0]⟩) (continuous_abs.comp p.continuous_eval).continuous_on in ⟨x, λ y, if hy : y.abs ≤ r then hx₂ y $ by simpa [complex.dist_eq] using hy else le_trans (hx₂ _ (by simp [le_of_lt hr0])) (le_of_lt (hr y (lt_of_not_ge hy)))⟩ else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩ /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := exists_forall_abs_polynomial_eval_le f in exists.intro z₀ $ by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous_eval g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hfg0 : 0 < abs (eval z₀ f) * (abs (eval z₀ g))⁻¹, from div_pos hf0' (complex.abs_pos.2 hg0), have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact lt_of_le_of_lt (le_trans (min_le_left _ _) (min_le_left _ _)) (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, by rw [div_eq_mul_inv, mul_right_comm, mul_comm, ← inv_inv' (complex.abs _ * _), mul_inv', inv_inv', ← div_eq_mul_inv, div_lt_iff hfg0, one_mul]; calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self hfg0, have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ end complex
09f557c45edfc969a630673dac2dba3bcd7afd21
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/linear_algebra/char_poly/basic.lean
d79e7c7c20775d673274d5db9f557815692d4a7a
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,809
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.apply_fun import ring_theory.matrix_algebra import ring_theory.polynomial_algebra import linear_algebra.nonsingular_inverse import tactic.squeeze /-! # Characteristic polynomials and the Cayley-Hamilton theorem We define characteristic polynomials of matrices and prove the Cayley–Hamilton theorem over arbitrary commutative rings. ## Main definitions * `char_poly` is the characteristic polynomial of a matrix. ## Implementation details We follow a nice proof from http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf -/ noncomputable theory universes u v w open polynomial matrix open_locale big_operators variables {R : Type u} [comm_ring R] variables {n : Type w} [decidable_eq n] [fintype n] open finset /-- The "characteristic matrix" of `M : matrix n n R` is the matrix of polynomials $t I - M$. The determinant of this matrix is the characteristic polynomial. -/ def char_matrix (M : matrix n n R) : matrix n n (polynomial R) := matrix.scalar n (X : polynomial R) - (C : R →+* polynomial R).map_matrix M @[simp] lemma char_matrix_apply_eq (M : matrix n n R) (i : n) : char_matrix M i i = (X : polynomial R) - C (M i i) := by simp only [char_matrix, sub_left_inj, pi.sub_apply, scalar_apply_eq, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] @[simp] lemma char_matrix_apply_ne (M : matrix n n R) (i j : n) (h : i ≠ j) : char_matrix M i j = - C (M i j) := by simp only [char_matrix, pi.sub_apply, scalar_apply_ne _ _ _ h, zero_sub, ring_hom.map_matrix_apply, map_apply, dmatrix.sub_apply] lemma mat_poly_equiv_char_matrix (M : matrix n n R) : mat_poly_equiv (char_matrix M) = X - C M := begin ext k i j, simp only [mat_poly_equiv_coeff_apply, coeff_sub, pi.sub_apply], by_cases h : i = j, { subst h, rw [char_matrix_apply_eq, coeff_sub], simp only [coeff_X, coeff_C], split_ifs; simp, }, { rw [char_matrix_apply_ne _ _ _ h, coeff_X, coeff_neg, coeff_C, coeff_C], split_ifs; simp [h], } end /-- The characteristic polynomial of a matrix `M` is given by $\det (t I - M)$. -/ def char_poly (M : matrix n n R) : polynomial R := (char_matrix M).det /-- The Cayley-Hamilton theorem, that the characteristic polynomial of a matrix, applied to the matrix itself, is zero. This holds over any commutative ring. -/ -- This proof follows http://drorbn.net/AcademicPensieve/2015-12/CayleyHamilton.pdf theorem aeval_self_char_poly (M : matrix n n R) : aeval M (char_poly M) = 0 := begin -- We begin with the fact $χ_M(t) I = adjugate (t I - M) * (t I - M)$, -- as an identity in `matrix n n (polynomial R)`. have h : (char_poly M) • (1 : matrix n n (polynomial R)) = adjugate (char_matrix M) * (char_matrix M) := (adjugate_mul _).symm, -- Using the algebra isomorphism `matrix n n (polynomial R) ≃ₐ[R] polynomial (matrix n n R)`, -- we have the same identity in `polynomial (matrix n n R)`. apply_fun mat_poly_equiv at h, simp only [mat_poly_equiv.map_mul, mat_poly_equiv_char_matrix] at h, -- Because the coefficient ring `matrix n n R` is non-commutative, -- evaluation at `M` is not multiplicative. -- However, any polynomial which is a product of the form $N * (t I - M)$ -- is sent to zero, because the evaluation function puts the polynomial variable -- to the right of any coefficients, so everything telescopes. apply_fun (λ p, p.eval M) at h, rw eval_mul_X_sub_C at h, -- Now $χ_M (t) I$, when thought of as a polynomial of matrices -- and evaluated at some `N` is exactly $χ_M (N)$. rw [mat_poly_equiv_smul_one, eval_map] at h, -- Thus we have $χ_M(M) = 0$, which is the desired result. exact h, end