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
17f704ae313587001a9b9ab0beb54dd72323c092
ae9f8bf05de0928a4374adc7d6b36af3411d3400
/src/formal_ml/convex_optimization.lean
6abc2663937a1a3d54a598fcbedd3b3b95d53e2f
[ "Apache-2.0" ]
permissive
NeoTim/formal-ml
bc42cf6beba9cd2ed56c1cd054ab4eb5402ed445
c9cbad2837104160a9832a29245471468748bb8d
refs/heads/master
1,671,549,160,900
1,601,362,989,000
1,601,362,989,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,788
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. -/ /- This file proves that if a convex function (by the derivative definition) has a derivative of zero at a point x, then that is a minimum. -/ import analysis.calculus.mean_value import data.complex.exponential import formal_ml.real /- Note: consider dropping this definition, and proving this using has_deriv_at already provided. has_derivative f f' ↔ differentiable f ∧ deriv f = f' -/ def has_derivative (f f':ℝ → ℝ):Prop := (∀ x, has_deriv_at f (f' x) x) lemma has_derivative.differentiable (f f':ℝ → ℝ):(has_derivative f f') → differentiable ℝ f := begin intro A1, unfold differentiable, intro x, apply has_deriv_at.differentiable_at, apply A1, end lemma differentiable.has_derivative (f:ℝ → ℝ):differentiable ℝ f → (has_derivative f (deriv f)) := begin intro A1, unfold differentiable at A1, intro x, apply differentiable_at.has_deriv_at, apply A1, end --Unused lemma has_derivative_add (f f' g g':ℝ → ℝ): has_derivative f f' → has_derivative g g' → has_derivative (f + g) (f' + g') := begin intros A1 A2 x, apply has_deriv_at.add, { apply A1, }, { apply A2, } end --Used in exp_bound.lean lemma has_derivative_sub (f f' g g':ℝ → ℝ): has_derivative f f' → has_derivative g g' → has_derivative (f - g) (f' - g') := begin intros A1 A2 x, apply has_deriv_at.sub, { apply A1, }, { apply A2, } end --Unused lemma has_derivative_const (k:ℝ): has_derivative (λ x:ℝ, k) (λ x:ℝ, 0) := begin intro x, simp, apply has_deriv_at_const, end lemma has_derivative_id: has_derivative (λ x:ℝ, x) (λ x:ℝ, 1) := begin intro x, simp, apply has_deriv_at_id, end lemma has_derivative_neg (f f':ℝ → ℝ): has_derivative f f' → has_derivative (-f) (-f') := begin intros A1 x, apply has_deriv_at.neg, apply A1, end --Used in exp_bound.lean lemma has_derivative_add_const (f f':ℝ → ℝ) (k:ℝ): has_derivative f f' → has_derivative (λ x:ℝ, f x + k) (f') := begin intros A1 x, apply has_deriv_at.add_const, apply A1, end section convex_optimization variables (f f' f'': ℝ → ℝ) lemma exists_has_deriv_at_eq_slope_total (x y:ℝ): (has_derivative f f') → (x < y) → (∃ c ∈ set.Ioo x y, f' c = (f y - f x) / (y - x)) := begin intros A1 A2, apply exists_has_deriv_at_eq_slope, { exact A2, }, { have B1:differentiable ℝ f := has_derivative.differentiable _ _ A1, apply continuous.continuous_on, apply differentiable.continuous B1, }, { intros z C1, apply A1, } end lemma zero_lt_of_neg_lt (x:ℝ):(0 < x) → (-x < 0) := neg_lt_zero.mpr lemma div_pos_of_pos_of_pos {a b:ℝ}:(0 < a) → (0 < b) → 0 < (a/b) := begin intros A1 A2, rw division_ring.div_def, apply mul_pos, apply A1, rw inv_pos, apply A2, end lemma is_minimum (x y:ℝ): (has_derivative f f') → (has_derivative f' f'')→ (∀ z, 0 ≤ (f'' z))→ (f' x = 0) → (f x ≤ f y) := begin intros A1 A2 A3 A4, have A5:differentiable ℝ f := has_derivative.differentiable _ _ A1, have A6:differentiable ℝ f' := has_derivative.differentiable _ _ A2, have A7:continuous f := differentiable.continuous A5, have A8:continuous f' := differentiable.continuous A6, have A9:(x < y)∨ (x=y) ∨ (y < x) := lt_trichotomy x y, cases A9, { have B1:¬(f y < f x), { intro B0, have B1C:∃ c ∈ set.Ioo x y, f' c = (f y - f x) / (y - x), { apply exists_has_deriv_at_eq_slope_total, apply A1, apply A9, }, cases B1C with c B1D, cases B1D with B1E B1F, have B1G:f' c < 0, { rw B1F, apply div_neg_of_neg_of_pos, { -- ⊢ f y - f x < 0 apply sub_lt_zero.mpr, apply B0, }, { -- ⊢ 0 < y - x apply sub_pos.mpr, apply A9, }, }, have B1H:x < c, { have B1H1:x < c ∧ c < y, { apply set.mem_Ioo.mp, exact B1E, }, apply B1H1.left, }, have B1I:∃ d ∈ set.Ioo x c, f'' d = (f' c - f' x) / (c - x), { apply exists_has_deriv_at_eq_slope_total, apply A2, apply B1H, }, cases B1I with d B1J, cases B1J with BIK B1L, have B1M:¬ (f'' d < 0), { apply not_lt_of_le, apply A3, }, apply B1M, rw B1L, apply div_neg_of_neg_of_pos, { rw A4, simp, apply B1G, }, { apply sub_pos.mpr, apply B1H, } }, apply le_of_not_lt B1, }, { cases A9, { rw A9, }, { have B1:¬(f y < f x), { intro B0, have B1A:continuous_on f (set.Icc x y), { apply continuous.continuous_on A7, }, have B1B:differentiable_on ℝ f (set.Ioo y x), { apply differentiable.differentiable_on A5, }, have B1C:∃ c ∈ set.Ioo y x, f' c = (f x - f y) / (x - y), { apply exists_has_deriv_at_eq_slope_total, apply A1, apply A9, }, cases B1C with c B1D, cases B1D with B1E B1F, have B1G:0 < f' c, { rw B1F, -- y < x, f y < f x ⊢ 0 < (f x - f y) / (x - y) -- 0 < x - y, 0 < f x - f y ⊢ 0 < (f x - f y) / (x - y) apply div_pos_of_pos_of_pos, { -- ⊢ f y - f x < 0 apply sub_pos.mpr, apply B0, }, { -- ⊢ 0 < y - x apply sub_pos.mpr, apply A9, }, }, have B1H:c < x, { have B1H1:y < c ∧ c < x, { apply set.mem_Ioo.mp, exact B1E, }, apply B1H1.right, }, have B1I:∃ d ∈ set.Ioo c x, f'' d = (f' x - f' c) / (x - c), { apply exists_has_deriv_at_eq_slope_total, apply A2, apply B1H, }, cases B1I with d B1J, cases B1J with BIK B1L, have B1M:¬ (f'' d < 0), { apply not_lt_of_le, apply A3, }, apply B1M, rw B1L, apply div_neg_of_neg_of_pos, { rw A4, simp, --apply zero_lt_of_neg_lt, apply B1G, }, { apply sub_pos.mpr, apply B1H, } }, apply le_of_not_lt B1, } } end /- Lifting the theorem to the mathlib terminology -/ lemma is_minimum' (x y:ℝ): differentiable ℝ f → differentiable ℝ (deriv f) → (0 ≤ (deriv (deriv f)))→ (deriv f x = 0) → (f x ≤ f y) := begin intros A1 A2 A3 A4, let f' := deriv f, let f'' := deriv f', begin have B1:f' = deriv f := rfl, have B2:f'' = deriv f' := rfl, have C1:=differentiable.has_derivative f A1, rw ← B1 at A2, have C2:=differentiable.has_derivative f' A2, rw ← B2 at C2, rw ← B1 at C1, rw ← B1 at A3, rw ← B2 at A3, rw ← B1 at A4, apply is_minimum f f' f'' x y C1 C2 A3 A4, end end end convex_optimization
54601019ac59be61dfebe27f622da1e651f86f09
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/subset_properties.lean
4a642f95dfc9ec1d219ecf748aacd4c6d79361e3
[ "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
80,325
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import order.filter.pi import topology.bases import data.finset.order import data.set.accumulate import tactic.tfae import topology.bornology.basic /-! # Properties of subsets of topological spaces In this file we define various properties of subsets of a topological space, and some classes on topological spaces. ## Main definitions We define the following properties for sets in a topological space: * `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters. The main property of a compact set is `is_compact.elim_finite_subcover`. * `is_clopen`: a set that is both open and closed. * `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens. See also the section below in the module doc. For each of these definitions (except for `is_clopen`), we also have a class stating that the whole space satisfies that property: `compact_space`, `irreducible_space` Furthermore, we have three more classes: * `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact neighborhood of `x`. The definition is formulated in terms of the neighborhood filter. * `sigma_compact_space`: a space that is the union of a countably many compact subspaces; * `noncompact_space`: a space that is not a compact space. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible`. In other words, the only difference is whether the empty space counts as irreducible. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical topological_space open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} {ι : Type*} {π : ι → Type*} variables [topological_space α] [topological_space β] {s t : set α} /- compact sets -/ section compact /-- A set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/ def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃ a ∈ s, cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) : sᶜ ∈ f := begin contrapose! hf, simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢, exact @hs _ hf inf_le_right end /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) : sᶜ ∈ f := begin refine hs.compl_mem_sets (λ a ha, _), rcases hf a ha with ⟨t, ht, hst⟩, replace ht := mem_inf_principal.1 ht, apply mem_inf_of_inter ht hst, rintros x ⟨h₁, h₂⟩ hs, exact h₂ (h₁ hs) end /-- If `p : set α → Prop` is stable under restriction and union, and each point `x` of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ @[elab_as_eliminator] lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t)) (hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) : p s := let f : filter α := { sets := {t | p tᶜ}, univ_sets := by simpa, sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁, inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds), by simpa /-- The intersection of a compact set and a closed set is a compact set. -/ lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := begin introsI f hnf hstf, obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f := hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))), have : a ∈ t := (ht.mem_of_nhds_within_ne_bot $ ha.mono $ le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), exact ⟨a, ⟨hsa, this⟩, ha⟩ end /-- The intersection of a closed set and a compact set is a compact set. -/ lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs /-- The set difference of a compact set and an open set is a compact set. -/ lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) /-- A closed subset of a compact set is a compact set. -/ lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have : ne_bot (l.comap f ⊓ 𝓟 s) := comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right, use [f a, mem_image_of_mem f has], have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l), { convert (hf a has).inf (@tendsto_comap _ _ f l) using 1, rw nhds_within, ac_refl }, exact @@tendsto.ne_bot _ this ha, end lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma is_compact.adherence_nhdset {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀ a ∈ s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ 𝓝[tᶜ] a, from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this), have A : 𝓝[tᶜ] a = ⊥, from empty_mem_iff_bot.1 $ compl_inter_self t ▸ this, have 𝓝[tᶜ] a ≠ ⊥, from hfa.of_inf_right.ne, absurd A this lemma is_compact_iff_ultrafilter_le_nhds : is_compact s ↔ (∀ f : ultrafilter α, ↑f ≤ 𝓟 s → ∃ a ∈ s, ↑f ≤ 𝓝 a) := begin refine (forall_ne_bot_le_iff _).trans _, { rintro f g hle ⟨a, has, haf⟩, exact ⟨a, has, haf.mono hle⟩ }, { simp only [ultrafilter.cluster_pt_iff] } end alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _ /-- For every open directed cover of a compact set, there exists a single element of the cover which itself includes the set. -/ lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) : ∃ i, s ⊆ U i := hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩ (λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩) (λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in ⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩) (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in ⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩) /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀ i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU) (directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h) lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α) (hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) : ∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 := (hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht, subset.trans ht $ Union₂_mono $ λ _ _, interior_subset lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x := let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2, by rwa finset.set_bUnion_finset_image⟩ /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/ lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f) {s : set α} (hs : is_compact s) : finite {i | (f i ∩ s).nonempty} := begin choose U hxU hUf using hf, rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩, refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _, rintro i ⟨x, hx⟩, rcases mem_Union₂.1 (hsU hx.2) with ⟨c, hct, hcx⟩, exact mem_bUnion hct ⟨x, hx.1, hcx⟩ end /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀ i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) : (s ∩ ⋂ i, Z i).nonempty := begin simp only [← ne_empty_iff_nonempty] at hsZ ⊢, apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ end /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact this.mono (Inter_mono $ λ i, inter_subset_left (Z i) (Z i₀)) }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, exact (hZn i₁).mono (subset_inter hi₁.left $ subset_Inter₂ hi₁.right), end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : antitone Z := antitone_nat_of_succ_le hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {b : set ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i ∈ b, is_open (c i)) (hc₂ : s ⊆ ⋃ i ∈ b, c i) : ∃ b' ⊆ b, finite b' ∧ s ⊆ ⋃ i ∈ b', c i := begin rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩; [skip, simpa using hc₁, simpa using hc₂], refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩, { simp }, { rwa [finset.coe_image, bUnion_image] } end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃ x ∈ s, cluster_pt x f), have hf : ∀ x ∈ s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff], have ¬ ∃ x ∈ s, ∀ t ∈ f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_mem_iff_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_iff] at this; exact this in have ∅ ∈ 𝓝[t₂] x, by { rw [ht, inter_comm], exact inter_mem_nhds_within _ ht₁ }, have 𝓝[t₂] x = ⊥, by rwa [empty_mem_iff_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂ i ∈ t, subtype.val i) ∈ f, from t.Inter_mem_sets.2 $ assume i hi, i.2, have s ∩ (⋂ i ∈ t, subtype.val i) ∈ f, from inter_mem (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃ i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (by { rw mem_Inter₂ at hx, exact hx i hit }), show false, from hxi this, hfn.ne $ by rwa [empty_mem_iff_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_of_finite_subcover (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := is_compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_iff_finite_subcover : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_iff_finite_subfamily_closed : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩ /-- To show that `∀ y ∈ K, P x y` holds for `x` close enough to `x₀` when `K` is compact, it is sufficient to show that for all `y₀ ∈ K` there `P x y` holds for `(x, y)` close enough to `(x₀, y₀)`. -/ lemma is_compact.eventually_forall_of_forall_eventually {x₀ : α} {K : set β} (hK : is_compact K) {P : α → β → Prop} (hP : ∀ y ∈ K, ∀ᶠ (z : α × β) in 𝓝 (x₀, y), P z.1 z.2): ∀ᶠ x in 𝓝 x₀, ∀ y ∈ K, P x y := begin refine hK.induction_on _ _ _ _, { exact eventually_of_forall (λ x y, false.elim) }, { intros s t hst ht, refine ht.mono (λ x h y hys, h y $ hst hys) }, { intros s t hs ht, filter_upwards [hs, ht], rintro x h1 h2 y (hys|hyt), exacts [h1 y hys, h2 y hyt] }, { intros y hyK, specialize hP y hyK, rw [nhds_prod_eq, eventually_prod_iff] at hP, rcases hP with ⟨p, hp, q, hq, hpq⟩, exact ⟨{y | q y}, mem_nhds_within_of_mem_nhds hq, eventually_of_mem hp @hpq⟩ } end @[simp] lemma is_compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf.ne $ empty_mem_iff_bot.1 $ le_principal_iff.1 hsf @[simp] lemma is_compact_singleton {a : α} : is_compact ({a} : set α) := λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds' (hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩ lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s := subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton lemma set.finite.compact_bUnion {s : set ι} {f : ι → set α} (hs : finite s) (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := is_compact_of_finite_subcover $ assume ι U hUo hsU, have ∀ i : subtype s, ∃ t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃ i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃ j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bUnion finset.univ finite_subcovers in have (⋃ i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from Union₂_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma finset.compact_bUnion (s : finset ι) {f : ι → set α} (hf : ∀ i ∈ s, is_compact (f i)) : is_compact (⋃ i ∈ s, f i) := s.finite_to_set.compact_bUnion hf lemma compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) : is_compact (accumulate K n) := (finite_le_nat n).compact_bUnion $ λ k _, hK k lemma compact_Union {f : ι → set α} [fintype ι] (h : ∀ i, is_compact (f i)) : is_compact (⋃ i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.is_compact (hs : finite s) : is_compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, is_compact_singleton) lemma is_compact.finite_of_discrete [discrete_topology α] {s : set α} (hs : is_compact s) : s.finite := begin have : ∀ x : α, ({x} : set α) ∈ 𝓝 x, by simp [nhds_discrete], rcases hs.elim_nhds_subcover (λ x, {x}) (λ x hx, this x) with ⟨t, hts, hst⟩, simp only [← t.set_bUnion_coe, bUnion_of_singleton] at hst, exact t.finite_to_set.subset hst end lemma is_compact_iff_finite [discrete_topology α] {s : set α} : is_compact s ↔ s.finite := ⟨λ h, h.finite_of_discrete, λ h, h.is_compact⟩ lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) := is_compact_singleton.union hs /-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/ lemma exists_subset_nhd_of_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := begin obtain ⟨W, hsubW, W_op, hWU⟩ := exists_open_set_nhds hU, suffices : ∃ i, V i ⊆ W, { rcases this with ⟨i, hi⟩, refine ⟨i, set.subset.trans hi hWU⟩ }, by_contra' H, replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i), have : (⋂ i, V i ∩ Wᶜ).nonempty, { refine is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ (λ i j, _) H (λ i, (hV_cpct i).inter_right W_op.is_closed_compl) (λ i, (hV_closed i).inter W_op.is_closed_compl), rcases hV i j with ⟨k, hki, hkj⟩, refine ⟨k, ⟨λ x, _, λ x, _⟩⟩ ; simp only [and_imp, mem_inter_eq, mem_compl_eq] ; tauto }, have : ¬ (⋂ (i : ι), V i) ⊆ W, by simpa [← Inter_inter, inter_compl_nonempty_iff], contradiction end namespace filter /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def cocompact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ) lemma has_basis_cocompact : (cocompact α).has_basis is_compact compl := has_basis_binfi_principal' (λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t), compl_subset_compl.2 (subset_union_right s t)⟩) ⟨∅, is_compact_empty⟩ lemma mem_cocompact : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s := has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop lemma mem_cocompact' : s ∈ cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t := mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm lemma _root_.is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α := has_basis_cocompact.mem_of_mem hs lemma cocompact_le_cofinite : cocompact α ≤ cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_cocompact lemma cocompact_eq_cofinite (α : Type*) [topological_space α] [discrete_topology α] : cocompact α = cofinite := has_basis_cocompact.eq_of_same_basis $ by { convert has_basis_cofinite, ext s, exact is_compact_iff_finite } @[simp] lemma _root_.nat.cocompact_eq : cocompact ℕ = at_top := (cocompact_eq_cofinite ℕ).trans nat.cofinite_eq_at_top lemma tendsto.is_compact_insert_range_of_cocompact {f : α → β} {b} (hf : tendsto f (cocompact α) (𝓝 b)) (hfc : continuous f) : is_compact (insert b (range f)) := begin introsI l hne hle, by_cases hb : cluster_pt b l, { exact ⟨b, or.inl rfl, hb⟩ }, simp only [cluster_pt_iff, not_forall, ← not_disjoint_iff_nonempty_inter, not_not] at hb, rcases hb with ⟨s, hsb, t, htl, hd⟩, rcases mem_cocompact.1 (hf hsb) with ⟨K, hKc, hKs⟩, have : f '' K ∈ l, { filter_upwards [htl, le_principal_iff.1 hle] with y hyt hyf, rcases hyf with (rfl|⟨x, rfl⟩), exacts [(hd ⟨mem_of_mem_nhds hsb, hyt⟩).elim, mem_image_of_mem _ (not_not.1 $ λ hxK, hd ⟨hKs hxK, hyt⟩)] }, rcases hKc.image hfc (le_principal_iff.2 this) with ⟨y, hy, hyl⟩, exact ⟨y, or.inr $ image_subset_range _ _ hy, hyl⟩ end lemma tendsto.is_compact_insert_range_of_cofinite {f : ι → α} {a} (hf : tendsto f cofinite (𝓝 a)) : is_compact (insert a (range f)) := begin letI : topological_space ι := ⊥, haveI : discrete_topology ι := ⟨rfl⟩, rw ← cocompact_eq_cofinite at hf, exact hf.is_compact_insert_range_of_cocompact continuous_of_discrete_topology end lemma tendsto.is_compact_insert_range {f : ℕ → α} {a} (hf : tendsto f at_top (𝓝 a)) : is_compact (insert a (range f)) := filter.tendsto.is_compact_insert_range_of_cofinite $ nat.cofinite_eq_at_top.symm ▸ hf /-- `filter.coclosed_compact` is the filter generated by complements to closed compact sets. In a Hausdorff space, this is the same as `filter.cocompact`. -/ def coclosed_compact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (h₁ : is_closed s) (h₂ : is_compact s), 𝓟 (sᶜ) lemma has_basis_coclosed_compact : (filter.coclosed_compact α).has_basis (λ s, is_closed s ∧ is_compact s) compl := begin simp only [filter.coclosed_compact, infi_and'], refine has_basis_binfi_principal' _ ⟨∅, is_closed_empty, is_compact_empty⟩, rintro s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, exact ⟨s ∪ t, ⟨⟨hs₁.union ht₁, hs₂.union ht₂⟩, compl_subset_compl.2 (subset_union_left _ _), compl_subset_compl.2 (subset_union_right _ _)⟩⟩ end lemma mem_coclosed_compact : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ tᶜ ⊆ s := by simp [has_basis_coclosed_compact.mem_iff, and_assoc] lemma mem_coclosed_compact' : s ∈ coclosed_compact α ↔ ∃ t, is_closed t ∧ is_compact t ∧ sᶜ ⊆ t := by simp only [mem_coclosed_compact, compl_subset_comm] lemma cocompact_le_coclosed_compact : cocompact α ≤ coclosed_compact α := infi_mono $ λ s, le_infi $ λ _, le_rfl lemma _root_.is_compact.compl_mem_coclosed_compact_of_is_closed (hs : is_compact s) (hs' : is_closed s) : sᶜ ∈ filter.coclosed_compact α := has_basis_coclosed_compact.mem_of_mem ⟨hs', hs⟩ end filter namespace bornology variable (α) /-- Sets that are contained in a compact set form a bornology. Its `cobounded` filter is `filter.cocompact`. See also `bornology.relatively_compact` the bornology of sets with compact closure. -/ def in_compact : bornology α := { cobounded := filter.cocompact α, le_cofinite := filter.cocompact_le_cofinite } variable {α} lemma in_compact.is_bounded_iff : @is_bounded _ (in_compact α) s ↔ ∃ t, is_compact t ∧ s ⊆ t := begin change sᶜ ∈ filter.cocompact α ↔ _, rw filter.mem_cocompact, simp end end bornology section tube_lemma /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : s ×ˢ t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (hn.preimage continuous_swap) (by rwa [←image_subset_iff, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀ x : s, ∃ uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ uv.1 ×ˢ uv.2 ⊆ n, from assume ⟨x, hx⟩, have ({x} : set α) ×ˢ t ⊆ n, from subset.trans (prod_mono (by simpa) subset.rfl) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃ i, (uvs i).1, from assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_Inter₂ (λi _, (h i).2.2.2.1), have u ×ˢ v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃ i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹u ×ˢ v ⊆ n›⟩ /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : s ×ˢ t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ×ˢ v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : is_compact (univ : set α)) @[priority 10] -- see Note [lower instance priority] instance subsingleton.compact_space [subsingleton α] : compact_space α := ⟨subsingleton_univ.is_compact⟩ lemma is_compact_univ_iff : is_compact (univ : set α) ↔ compact_space α := ⟨λ h, ⟨h⟩, λ h, h.1⟩ lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] : ∃ x, cluster_pt x f := by simpa using compact_univ (show f ≤ 𝓟 univ, by simp) lemma compact_space.elim_nhds_subcover [compact_space α] (U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ := begin obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover compact_univ U (λ x m, hU x), exact ⟨t, by { rw eq_top_iff, exact s }⟩, end theorem compact_space_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) : compact_space α := { compact_univ := begin apply is_compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) /-- `α` is a noncompact topological space if it not a compact space. -/ class noncompact_space (α : Type*) [topological_space α] : Prop := (noncompact_univ [] : ¬is_compact (univ : set α)) export noncompact_space (noncompact_univ) lemma is_compact.ne_univ [noncompact_space α] {s : set α} (hs : is_compact s) : s ≠ univ := λ h, noncompact_univ α (h ▸ hs) instance [noncompact_space α] : ne_bot (filter.cocompact α) := begin refine filter.has_basis_cocompact.ne_bot_iff.2 (λ s hs, _), contrapose hs, rw [not_nonempty_iff_eq_empty, compl_empty_iff] at hs, rw hs, exact noncompact_univ α end @[simp] lemma filter.cocompact_eq_bot [compact_space α] : filter.cocompact α = ⊥ := filter.has_basis_cocompact.eq_bot_iff.mpr ⟨set.univ, compact_univ, set.compl_univ⟩ instance [noncompact_space α] : ne_bot (filter.coclosed_compact α) := ne_bot_of_le filter.cocompact_le_coclosed_compact lemma noncompact_space_of_ne_bot (h : ne_bot (filter.cocompact α)) : noncompact_space α := ⟨λ h', (filter.nonempty_of_mem h'.compl_mem_cocompact).ne_empty compl_univ⟩ lemma filter.cocompact_ne_bot_iff : ne_bot (filter.cocompact α) ↔ noncompact_space α := ⟨noncompact_space_of_ne_bot, @filter.cocompact.filter.ne_bot _ _⟩ lemma not_compact_space_iff : ¬compact_space α ↔ noncompact_space α := ⟨λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ h₂⟩ instance : noncompact_space ℤ := noncompact_space_of_ne_bot $ by simp only [filter.cocompact_eq_cofinite, filter.cofinite_ne_bot] /-- A compact discrete space is finite. -/ noncomputable def fintype_of_compact_of_discrete [compact_space α] [discrete_topology α] : fintype α := fintype_of_univ_finite $ compact_univ.finite_of_discrete lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ := let ⟨t, ht⟩ := compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior) (λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩) in ⟨t, univ_subset_iff.1 ht⟩ lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = univ := let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $ ht.symm.subset.trans $ Union₂_mono $ λ x hx, interior_subset⟩ /-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely many nonempty elements. -/ lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) : finite {i | (f i).nonempty} := by simpa only [inter_univ] using hf.finite_nonempty_inter_compact compact_univ /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `set.finite` version. -/ lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : finite (univ : set ι) := by simpa only [hne] using hf.finite_nonempty_of_compact /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `fintype` version. -/ noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : fintype ι := fintype_of_univ_finite (hf.finite_of_compact hne) /-- The comap of the cocompact filter on `β` by a continuous function `f : α → β` is less than or equal to the cocompact filter on `α`. This is a reformulation of the fact that images of compact sets are compact. -/ lemma filter.comap_cocompact_le {f : α → β} (hf : continuous f) : (filter.cocompact β).comap f ≤ filter.cocompact α := begin rw (filter.has_basis_cocompact.comap f).le_basis_iff filter.has_basis_cocompact, intros t ht, refine ⟨f '' t, ht.image hf, _⟩, simpa using t.subset_preimage_image f end lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact compact_univ.image hf /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_is_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), { suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)), by simpa only [map_ne_bot_iff], convert y_closure, calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal }, resetI, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact _, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], convert hx, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm end lemma exists_subset_nhd_of_compact_space [compact_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhd_of_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU /-- If `f : α → β` is an `inducing` map, then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} : is_compact (f '' s) ↔ is_compact s := begin refine ⟨_, λ hs, hs.image hf.continuous⟩, introsI hs F F_ne_bot F_le, obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ := hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le ... = 𝓟 (f '' s) : map_principal), use [x, x_in], suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff], rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap ... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ end /-- If `f : α → β` is an `embedding` (or more generally, an `inducing` map, see `inducing.is_compact_iff`), then the image `f '' s` of a set `s` is compact if and only if the set `s` is closed. -/ lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := hf.to_inducing.is_compact_iff.symm /-- The preimage of a compact set under a closed embedding is a compact set. -/ lemma closed_embedding.is_compact_preimage {f : α → β} (hf : closed_embedding f) {K : set β} (hK : is_compact K) : is_compact (f ⁻¹' K) := begin replace hK := hK.inter_right hf.closed_range, rwa [← hf.to_inducing.is_compact_iff, image_preimage_eq_inter_range] end /-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. Moreover, the preimage of a compact set is compact, see `closed_embedding.is_compact_preimage`. -/ lemma closed_embedding.tendsto_cocompact {f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) := filter.has_basis_cocompact.tendsto_right_iff.mpr $ λ K hK, (hf.is_compact_preimage hK).compl_mem_cocompact lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.is_compact_iff_is_compact_image lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ protected lemma closed_embedding.noncompact_space [noncompact_space α] {f : α → β} (hf : closed_embedding f) : noncompact_space β := noncompact_space_of_ne_bot hf.tendsto_cocompact.ne_bot protected lemma closed_embedding.compact_space [h : compact_space β] {f : α → β} (hf : closed_embedding f) : compact_space α := by { unfreezingI { contrapose! h, rw not_compact_space_iff at h ⊢ }, exact hf.noncompact_space } lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (s ×ˢ t) := begin rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hfs, rw le_principal_iff at hfs, obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ := hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.left)), obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ := ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $ mem_of_superset hfs (λ x, and.right)), rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr) end⟩ instance [fintype ι] [Π i, topological_space (π i)] [∀ i, compact_space (π i)] : compact_space (Σ i, π i) := begin refine ⟨_⟩, rw sigma.univ, exact compact_Union (λ i, is_compact_range continuous_sigma_mk), end /-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on their product. -/ lemma filter.coprod_cocompact : (filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap, filter.mem_cocompact], split, { rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩, refine ⟨t ×ˢ t', ht.prod ht', _⟩, refine subset.trans _ (union_subset hAS hBS), rw compl_subset_comm at ⊢ hAt hBt', refine subset.trans _ (set.prod_mono hAt hBt'), intros x, simp only [compl_union, mem_inter_eq, mem_prod, mem_preimage, mem_compl_eq], tauto }, { rintros ⟨t, ht, htS⟩, refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩, { exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.fst _) }, { exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.snd _) } } end lemma prod.noncompact_space_iff : noncompact_space (α × β) ↔ noncompact_space α ∧ nonempty β ∨ nonempty α ∧ noncompact_space β := by simp [← filter.cocompact_ne_bot_iff, ← filter.coprod_cocompact, filter.coprod_ne_bot_iff] @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_left [noncompact_space α] [nonempty β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[priority 100] -- See Note [lower instance priority] instance prod.noncompact_space_right [nonempty α] [noncompact_space β] : noncompact_space (α × β) := prod.noncompact_space_iff.2 (or.inr ⟨‹_›, ‹_›⟩) section tychonoff variables [Π i, topological_space (π i)] /-- **Tychonoff's theorem**: product of compact sets is compact. -/ lemma is_compact_pi_infinite {s : Π i, set (π i)} : (∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} := begin simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, filter.pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff], intros h f hfs, have : ∀ i:ι, ∃ a, a ∈ s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a), { refine λ i, h i (f.map _) (mem_map.2 _), exact mem_of_superset hfs (λ x hx, hx i) }, choose a ha, exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩ end /-- **Tychonoff's theorem** formulated using `set.pi`: product of compact sets is compact. -/ lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) : is_compact (pi univ s) := by { convert is_compact_pi_infinite h, simp only [← mem_univ_pi, set_of_mem_eq] } instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) := ⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, compact_univ) }⟩ /-- **Tychonoff's theorem** formulated in terms of filters: `filter.cocompact` on an indexed product type `Π d, κ d` the `filter.Coprod` of filters `filter.cocompact` on `κ d`. -/ lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] : filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) := begin refine le_antisymm (supr_le $ λ i, filter.comap_cocompact_le (continuous_apply i)) _, refine compl_surjective.forall.2 (λ s H, _), simp only [compl_mem_Coprod, filter.mem_cocompact, compl_subset_compl, image_subset_iff] at H ⊢, choose K hKc htK using H, exact ⟨set.pi univ K, is_compact_univ_pi hKc, λ f hf i hi, htK i hf⟩ end end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) lemma compact_basis_nhds [locally_compact_space α] (x : α) : (𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) := has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x lemma local_compact_nhds [locally_compact_space α] {x : α} {n : set α} (h : n ∈ 𝓝 x) : ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s := locally_compact_space.local_compact_nhds _ _ h lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop} {s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x)) (hc : ∀ x i, p x i → is_compact (s x i)) : locally_compact_space α := ⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩ instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α] [topological_space β] [locally_compact_space α] [locally_compact_space β] : locally_compact_space (α × β) := have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2), locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂ /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩, exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩, end /-- In a locally compact space every point has a compact neighborhood. -/ lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) : ∃ K, is_compact K ∧ K ∈ 𝓝 x := let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x) in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩ /-- In a locally compact space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) : ∃ K', is_compact K' ∧ K ⊆ interior K' := begin choose U hUc hxU using λ x : K, exists_compact_mem_nhds (x : α), have : K ⊆ ⋃ x, interior (U x), from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 (hxU _)⟩, rcases hK.elim_finite_subcover _ _ this with ⟨t, ht⟩, { refine ⟨_, t.compact_bUnion (λ x _, hUc x), λ x hx, _⟩, rcases mem_Union₂.1 (ht hx) with ⟨y, hyt, hy⟩, exact interior_mono (subset_bUnion_of_mem hyt) hy }, { exact λ _, is_open_interior } end protected lemma closed_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : closed_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, s ∈ 𝓝 (f x) ∧ is_compact s) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact (compact_basis_nhds _).comap _ }, exact locally_compact_space_of_has_basis this (λ x s hs, hf.is_compact_preimage hs.2) end protected lemma is_closed.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_closed s) : locally_compact_space s := (closed_embedding_subtype_coe hs).locally_compact_space protected lemma open_embedding.locally_compact_space [locally_compact_space β] {f : α → β} (hf : open_embedding f) : locally_compact_space α := begin have : ∀ x : α, (𝓝 x).has_basis (λ s, (s ∈ 𝓝 (f x) ∧ is_compact s) ∧ s ⊆ range f) (λ s, f ⁻¹' s), { intro x, rw hf.to_embedding.to_inducing.nhds_eq_comap, exact ((compact_basis_nhds _).restrict_subset $ hf.open_range.mem_nhds $ mem_range_self _).comap _ }, refine locally_compact_space_of_has_basis this (λ x s hs, _), rw [← hf.to_inducing.is_compact_iff, image_preimage_eq_of_subset hs.2], exact hs.1.2 end protected lemma is_open.locally_compact_space [locally_compact_space α] {s : set α} (hs : is_open s) : locally_compact_space s := hs.open_embedding_subtype_coe.locally_compact_space lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) : ↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) := begin rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩, exact le_nhds_Lim ⟨x,h⟩, end theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (V : set α), V ⊆ S ∧ V.nonempty ∧ is_closed V ∧ (∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) := begin let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty}, obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn_subset opens (λ c hc hz, begin by_cases hcne : c.nonempty, { obtain ⟨U₀, hU₀⟩ := hcne, haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩, obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀, use ⋃₀ c, refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩, { exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ }, { exact is_open_sUnion (λ _ h, (hc h).2.1) }, { convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty, { ext, simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall, set.mem_set_of_eq, set.mem_compl_eq, subtype.val_eq_coe], refl, }, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed, { rintros ⟨U, hU⟩ ⟨U', hU'⟩, obtain ⟨V, hVc, hVU, hVU'⟩ := hz.directed_on U hU U' hU', exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, }, { exact λ U, (hc U.2).2.2, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } }, { use Sᶜ, refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩, rw compl_compl, exact hne, } end), refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩, intros V' V'sub V'ne V'cls, have : V'ᶜ = U, { refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub), exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub), simp only [compl_compl, V'ne], }, rw [←this, compl_compl], end /-- A σ-compact space is a space that is the union of a countable collection of compact subspaces. Note that a locally compact separable T₂ space need not be σ-compact. The sequence can be extracted using `topological_space.compact_covering`. -/ class sigma_compact_space (α : Type*) [topological_space α] : Prop := (exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ) @[priority 200] -- see Note [lower instance priority] instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α := ⟨⟨λ _, univ, λ _, compact_univ, Union_const _⟩⟩ lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : countable S) (Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α := ⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩ @[priority 100] -- see Note [lower instance priority] instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α] [second_countable_topology α] : sigma_compact_space α := begin choose K hKc hxK using λ x : α, exists_compact_mem_nhds x, rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩, refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _, rwa sUnion_image end variables (α) [sigma_compact_space α] open sigma_compact_space /-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/ def compact_covering : ℕ → set α := accumulate exists_compact_covering.some lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) := compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ := begin rw [compact_covering, Union_accumulate], exact (classical.some_spec sigma_compact_space.exists_compact_covering).2 end @[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) : compact_covering α m ⊆ compact_covering α n := monotone_accumulate h variable {α} lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n := Union_eq_univ_iff.mp (Union_compact_covering α) x /-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have only countably many elements, `set.countable` version. -/ protected lemma locally_finite.countable_univ {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : countable (univ : set ι) := begin have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n), refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _), rcases hne i with ⟨x, hx⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact mem_Union.2 ⟨n, x, hx, hn⟩ end /-- If `f : ι → set α` is a locally finite covering of a σ-compact topological space by nonempty sets, then the index type `ι` is encodable. -/ protected noncomputable def locally_finite.encodable {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : encodable ι := @encodable.of_equiv _ _ (hf.countable_univ hne).to_encodable (equiv.set.univ _).symm /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`, the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/ lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s) (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, countable t ∧ s ⊆ ⋃ x ∈ t, f x := begin simp only [nhds_within, mem_inf_principal] at hf, choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover _ (λ x hx, hf x hx.right), refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2, countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_Union₂.2 _⟩, rcases exists_mem_compact_covering x with ⟨n, hn⟩, rcases mem_Union₂.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩, exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩ end /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds_of_sigma_compact {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ := begin simp only [← nhds_within_univ] at hf, rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x) with ⟨s, -, hsc, hsU⟩, exact ⟨s, hsc, univ_subset_iff.1 hsU⟩ end end compact /-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and `(⋃ n, K n) = univ`. If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides a choice of an exhaustion by compact sets. This choice is also available as `(default : compact_exhaustion X)`. -/ structure compact_exhaustion (X : Type*) [topological_space X] := (to_fun : ℕ → set X) (is_compact' : ∀ n, is_compact (to_fun n)) (subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1))) (Union_eq' : (⋃ n, to_fun n) = univ) namespace compact_exhaustion instance : has_coe_to_fun (compact_exhaustion α) (λ _, ℕ → set α) := ⟨to_fun⟩ variables {α} (K : compact_exhaustion α) protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) := K.subset_interior_succ' n lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) := subset.trans (K.subset_interior_succ n) interior_subset @[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n := show K m ≤ K n, from monotone_nat_of_le_succ K.subset_succ h lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) := subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq' lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x /-- The minimal `n` such that `x ∈ K n`. -/ protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x) lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x) lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n := ⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩ /-- Prepend the empty set to a compact exhaustion `K n`. -/ def shiftr : compact_exhaustion α := { to_fun := λ n, nat.cases_on n ∅ K, is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact, subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ, Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ } @[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 := nat.find_comp_succ _ _ (not_mem_empty _) lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) := ⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $ by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩ /-- A choice of an [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a locally compact sigma compact space. -/ noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X] [sigma_compact_space X] : compact_exhaustion X := begin apply classical.choice, let K : ℕ → {s : set X // is_compact s} := λ n, nat.rec_on n ⟨∅, is_compact_empty⟩ (λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n, (exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩), refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩, { exact subset.trans (exists_compact_superset (K n).2).some_spec.2 (interior_mono $ subset_union_left _ _) }, { refine univ_subset_iff.1 (Union_compact_covering X ▸ _), exact Union_mono' (λ n, ⟨n + 1, subset_union_right _ _⟩) } end noncomputable instance [locally_compact_space α] [sigma_compact_space α] : inhabited (compact_exhaustion α) := ⟨compact_exhaustion.choice α⟩ end compact_exhaustion section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s protected lemma is_clopen.is_open (hs : is_clopen s) : is_open s := hs.1 protected lemma is_clopen.is_closed (hs : is_clopen s) : is_closed s := hs.2 lemma is_clopen_iff_frontier_eq_empty {s : set α} : is_clopen s ↔ frontier s = ∅ := begin rw [is_clopen, ← closure_eq_iff_is_closed, ← interior_eq_iff_open, frontier, diff_eq_empty], refine ⟨λ h, (h.2.trans h.1.symm).subset, λ h, _⟩, exact ⟨interior_subset.antisymm (subset_closure.trans h), (h.trans interior_subset).antisymm subset_closure⟩ end alias is_clopen_iff_frontier_eq_empty ↔ is_clopen.frontier_eq _ theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨hs.1.union ht.1, hs.2.union ht.2⟩ theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨hs.1.inter ht.1, hs.2.inter ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2.is_open_compl, hs.1.is_closed_compl⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩ theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := hs.inter ht.compl lemma is_clopen_Union {β : Type*} [fintype β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) := ⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩ lemma is_clopen_bUnion {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := begin refine ⟨is_open_bUnion (λ i hi, (h i hi).1), _⟩, show is_closed (⋃ (i : β) (H : i ∈ (s : set β)), f i), rw bUnion_eq_Union, exact is_closed_Union (λ ⟨i, hi⟩,(h i hi).2) end lemma is_clopen_Inter {β : Type*} [fintype β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) := ⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩ lemma is_clopen_bInter {β : Type*} {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_clopen (f i)) : is_clopen (⋂ i ∈ s, f i) := ⟨ is_open_bInter ⟨finset_coe.fintype s⟩ (λ i hi, (h i hi).1), by {show is_closed (⋂ (i : β) (H : i ∈ (↑s : set β)), f i), rw bInter_eq_Inter, apply is_closed_Inter, rintro ⟨i, hi⟩, exact (h i hi).2}⟩ lemma continuous_on.preimage_clopen_of_clopen {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) := ⟨continuous_on.preimage_open_of_open hf hs.1 ht.1, continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z) (cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) := begin refine ⟨is_open.inter h.1 ha, _⟩, have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb), convert this using 1, apply subset.antisymm, { exact inter_subset_inter_right Z (subset_compl_iff_disjoint.2 hab) }, { rintros x ⟨hx₁, hx₂⟩, exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ } end @[simp] lemma is_clopen_discrete [discrete_topology α] (x : set α) : is_clopen x := ⟨is_open_discrete _, is_closed_discrete _⟩ lemma clopen_range_sigma_mk {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] {i : ι} : is_clopen (set.range (@sigma.mk ι σ i)) := ⟨open_embedding_sigma_mk.open_range, closed_embedding_sigma_mk.closed_range⟩ protected lemma quotient_map.is_clopen_preimage {f : α → β} (hf : quotient_map f) {s : set β} : is_clopen (f ⁻¹' s) ↔ is_clopen s := and_congr hf.is_open_preimage hf.is_closed_preimage end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim lemma set.subsingleton.is_preirreducible {s : set α} (hs : s.subsingleton) : is_preirreducible s := λ u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩, ⟨y, hys, hs hxs hys ▸ hxu, hyv⟩ theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, subsingleton_singleton.is_preirreducible⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn_subset_nonempty {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (hcc.total hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) -- see Note [lower instance priority] attribute [instance, priority 50] irreducible_space.to_nonempty lemma irreducible_space.is_irreducible_univ (α : Type u) [topological_space α] [irreducible_space α] : is_irreducible (⊤ : set α) := ⟨by simp, preirreducible_space.is_preirreducible_univ α⟩ lemma irreducible_space_def (α : Type u) [topological_space α] : irreducible_space α ↔ is_irreducible (⊤ : set α) := ⟨@@irreducible_space.is_irreducible_univ α _, λ h, by { haveI : preirreducible_space α := ⟨h.2⟩, exact ⟨⟨h.1.some⟩⟩ }⟩ theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [inter_comm s u', ← u'_eq] at this, rw [inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← mem_preimage, apply mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end /-- A nonemtpy open subset of a preirreducible subspace is dense in the subspace. -/ lemma subset_closure_inter_of_is_preirreducible_of_is_open {S U : set α} (hS : is_preirreducible S) (hU : is_open U) (h : (S ∩ U).nonempty) : S ⊆ closure (S ∩ U) := begin by_contra h', obtain ⟨x, h₁, h₂, h₃⟩ := hS _ (closure (S ∩ U))ᶜ hU (is_open_compl_iff.mpr is_closed_closure) h (set.inter_compl_nonempty_iff.mpr h'), exact h₃ (subset_closure ⟨h₁, h₂⟩) end /-- If `∅ ≠ U ⊆ S ⊆ Z` such that `U` is open and `Z` is preirreducible, then `S` is irreducible. -/ lemma is_preirreducible.subset_irreducible {S U Z : set α} (hZ : is_preirreducible Z) (hU : U.nonempty) (hU' : is_open U) (h₁ : U ⊆ S) (h₂ : S ⊆ Z) : is_irreducible S := begin classical, obtain ⟨z, hz⟩ := hU, replace hZ : is_irreducible Z := ⟨⟨z, h₂ (h₁ hz)⟩, hZ⟩, refine ⟨⟨z, h₁ hz⟩, _⟩, rintros u v hu hv ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨a, -, ha'⟩ := is_irreducible_iff_sInter.mp hZ {U, u, v} (by tidy) _, replace ha' : a ∈ U ∧ a ∈ u ∧ a ∈ v := by simpa using ha', exact ⟨a, h₁ ha'.1, ha'.2⟩, { intros U H, simp only [finset.mem_insert, finset.mem_singleton] at H, rcases H with (rfl|rfl|rfl), exacts [⟨z, h₂ (h₁ hz), hz⟩, ⟨x, h₂ hx, hx'⟩, ⟨y, h₂ hy, hy'⟩] } end lemma is_preirreducible.open_subset {Z U : set α} (hZ : is_preirreducible Z) (hU : is_open U) (hU' : U ⊆ Z) : is_preirreducible U := U.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preirreducible_empty) (λ h, (hZ.subset_irreducible h hU (λ _, id) hU').2) lemma is_preirreducible.interior {Z : set α} (hZ : is_preirreducible Z) : is_preirreducible (interior Z) := hZ.open_subset is_open_interior interior_subset lemma is_preirreducible.preimage {Z : set α} (hZ : is_preirreducible Z) {f : β → α} (hf : open_embedding f) : is_preirreducible (f ⁻¹' Z) := begin rintros U V hU hV ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, obtain ⟨_, h₁, ⟨z, h₂, rfl⟩, ⟨z', h₃, h₄⟩⟩ := hZ _ _ (hf.is_open_map _ hU) (hf.is_open_map _ hV) ⟨f x, hx, set.mem_image_of_mem f hx'⟩ ⟨f y, hy, set.mem_image_of_mem f hy'⟩, cases hf.inj h₄, exact ⟨z, h₁, h₂, h₃⟩ end end preirreducible
4e2ca9ede3b22634e94e192fa83cba844499b7b1
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level01.lean
9260643346170a525e04387b79452435bfdb30f7
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
127
lean
import mynat.le lemma one_add_le_self (x : mynat) : x ≤ 1 + x := begin rw le_iff_exists_add, use 1, exact add_comm 1 x, end
91bbc3e43aae5dd0ef9d97bdf7048eeedf89575c
e967488e2008f07b0aa7b6b18d4398d02c7460e2
/src/game/intro.lean
eaacd58e62be63961dbd93db36a81fc74f1637dd
[]
no_license
thyrgle/real-number-game
5c53eefaa815051f3d70ca5782e41d2adb76fd6e
a420eecef62209b729c910c2170d1dd27b74bc9f
refs/heads/master
1,606,405,407,612
1,574,956,743,000
1,574,956,743,000
229,126,103
0
0
null
1,576,784,273,000
1,576,784,272,000
null
UTF-8
Lean
false
false
1,797
lean
/- # The Real Number Game, version 1.0beta ## By Kevin Buzzard # What is this game? Welcome to the real number game -- a game to help undergraduates learn analysis through Lean, a formal proof verification system. Starting from the real numbers with its usual structure, we develop the theory of bounds, least upper bounds and greatest lower bounds (sups and infs), infinite sequences and infinite series. We develop the theory through problem-solving, getting students to formalise proofs in the theory. This game is a sequel to <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/" target="blank">the natural number game</a>. The levels in the Real Number Game need to be solved using tactics. To learn how to use these tactics, I would recommend that you first play the Natural Number Game up to at least "Advanced Proposition world". I will not go through a careful explanation of the tactics taught by the natural number game here. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- try blue ones higher up the chain first. Green nodes are completed. # Thanks Many thanks to Mohammad Pedramfar, without whom this game would not exist. # Questions? You can ask questions on the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a>, where I am often to be found. The Real Number Game is brought to you by the Xena project, a project based at Imperial College London whose aim is to get mathematics undergraduates using computer theorem provers. Lean is a computer theorem prover being developed at Microsoft Research. Prove a theorem. Write a function. <a href="https://twitter.com/XenaProject" target="blank">@XenaProject</a>. -/ /- Tactic : fish ## Summary eat fish $fish$ `fish` -/
0547c07499ebca056a529fb0511149cddf5ca23c
b73bd2854495d87ad5ce4f247cfcd6faa7e71c7e
/src/game/world3/level8.lean
9b8d72b81b60283324c7f4a8c9b920fd21834d83
[]
no_license
agusakov/category-theory-game
20db0b26270e0c95a3d5605498570273d72f731d
652dd7e90ae706643b2a597e2c938403653e167d
refs/heads/master
1,669,201,216,310
1,595,740,057,000
1,595,740,057,000
280,895,295
12
0
null
null
null
null
UTF-8
Lean
false
false
763
lean
import category_theory.category.default universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory variables (C : Type u) [category.{v} C] --rewrite this /- # Category world ## Level 7: Composition of monomorphisms Now we show that the composition of two monomorphisms produces another monomorphism.-/ /- Lemma If $$f : X ⟶ Y$$ and $$g : X ⟶ Y$$ are monomorphisms, then $$f ≫ g : X ⟶ Z$$ is a monomorphism. -/ lemma epi_of_epi' {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros W h l hyp, rw ← cancel_epi (f ≫ g), rw category.assoc, rw hyp, rw ← category.assoc, end end category_theory
fa5e8cd23fe7c45a85524196c57de0fbadfe5f31
827124860511172deb7ee955917c49b2bccd1b3c
/data/containers/rbtree/default.lean
b1c053ca6bc50346d9b32eda50effea75503c79e
[]
no_license
joehendrix/lean-containers
afec24c7de19c935774738ff3a0415362894956c
ef6ff0533eada75f18922039f8312badf12e6124
refs/heads/master
1,624,853,911,199
1,505,890,599,000
1,505,890,599,000
103,489,962
1
1
null
null
null
null
UTF-8
Lean
false
false
13
lean
import .basic
1ade2d24ed27c8c499d7e1dcab4e90debdd5c3e1
66a6486e19b71391cc438afee5f081a4257564ec
/algebra/direct_sum.hlean
db33e938a87c9dccac00d478af400ada6d6a36f0
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
8,624
hlean
/- Copyright (c) 2015 Floris van Doorn, Egbert Rijke, Favonia. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Favonia Constructions with groups -/ import .quotient_group .free_abelian_group .product_group open eq is_equiv algebra is_trunc set_quotient relation sigma prod sum list trunc function equiv sigma.ops lift namespace group section parameters {I : Type} [is_set I] (Y : I → AbGroup) variables {A' : AbGroup} {Y' : I → AbGroup} definition dirsum_carrier : AbGroup := free_ab_group (Σi, Y i) local abbreviation ι [constructor] := @free_ab_group_inclusion inductive dirsum_rel : dirsum_carrier → Type := | rmk : Πi y₁ y₂, dirsum_rel (ι ⟨i, y₁⟩ * ι ⟨i, y₂⟩ * (ι ⟨i, y₁ * y₂⟩)⁻¹) definition dirsum : AbGroup := quotient_ab_group_gen dirsum_carrier (λg, ∥dirsum_rel g∥) -- definition dirsum_carrier_incl [constructor] (i : I) : Y i →g dirsum_carrier := definition dirsum_incl [constructor] (i : I) : Y i →g dirsum := homomorphism.mk (λy, class_of (ι ⟨i, y⟩)) begin intro g h, symmetry, apply gqg_eq_of_rel, apply tr, apply dirsum_rel.rmk end parameter {Y} definition dirsum.rec {P : dirsum → Type} [H : Πg, is_prop (P g)] (h₁ : Πi (y : Y i), P (dirsum_incl i y)) (h₂ : P 1) (h₃ : Πg h, P g → P h → P (g * h)) : Πg, P g := begin refine @set_quotient.rec_prop _ _ _ H _, refine @set_quotient.rec_prop _ _ _ (λx, !H) _, esimp, intro l, induction l with s l ih, exact h₂, induction s with v v, induction v with i y, exact h₃ _ _ (h₁ i y) ih, induction v with i y, refine h₃ (gqg_map _ _ (class_of [inr ⟨i, y⟩])) _ _ ih, refine transport P _ (h₁ i y⁻¹), refine _ ⬝ !one_mul, refine _ ⬝ ap (λx, mul x _) (to_respect_zero (dirsum_incl i)), apply gqg_eq_of_rel', apply tr, esimp, refine transport dirsum_rel _ (dirsum_rel.rmk i y⁻¹ y), rewrite [mul.left_inv, mul.assoc], end definition dirsum_homotopy {φ ψ : dirsum →g A'} (h : Πi (y : Y i), φ (dirsum_incl i y) = ψ (dirsum_incl i y)) : φ ~ ψ := begin refine dirsum.rec _ _ _, exact h, refine !to_respect_zero ⬝ !to_respect_zero⁻¹, intro g₁ g₂ h₁ h₂, rewrite [* to_respect_mul, h₁, h₂] end definition dirsum_elim_resp_quotient (f : Πi, Y i →g A') (g : dirsum_carrier) (r : ∥dirsum_rel g∥) : free_ab_group_elim (λv, f v.1 v.2) g = 1 := begin induction r with r, induction r, rewrite [to_respect_mul, to_respect_inv, to_respect_mul, ▸*, ↑foldl, *one_mul, to_respect_mul], apply mul.right_inv end definition dirsum_elim [constructor] (f : Πi, Y i →g A') : dirsum →g A' := gqg_elim _ (free_ab_group_elim (λv, f v.1 v.2)) (dirsum_elim_resp_quotient f) definition dirsum_elim_compute (f : Πi, Y i →g A') (i : I) (y : Y i) : dirsum_elim f (dirsum_incl i y) = f i y := begin apply one_mul end definition dirsum_elim_unique (f : Πi, Y i →g A') (k : dirsum →g A') (H : Πi, k ∘g dirsum_incl i ~ f i) : k ~ dirsum_elim f := begin apply gqg_elim_unique, apply free_ab_group_elim_unique, intro x, induction x with i y, exact H i y end end definition binary_dirsum (G H : AbGroup) : dirsum (bool.rec G H) ≃g G ×ag H := let branch := bool.rec G H in let to_hom := (dirsum_elim (bool.rec (product_inl G H) (product_inr G H)) : dirsum (bool.rec G H) →g G ×ag H) in let from_hom := (Group_sum_elim (dirsum (bool.rec G H)) (dirsum_incl branch bool.ff) (dirsum_incl branch bool.tt) : G ×g H →g dirsum branch) in begin fapply isomorphism.mk, { exact dirsum_elim (bool.rec (product_inl G H) (product_inr G H)) }, fapply adjointify, { exact from_hom }, { intro gh, induction gh with g h, exact prod_eq (mul_one (1 * g) ⬝ one_mul g) (ap (λ o, o * h) (mul_one 1) ⬝ one_mul h) }, { refine dirsum.rec _ _ _, { intro b x, refine ap from_hom (dirsum_elim_compute (bool.rec (product_inl G H) (product_inr G H)) b x) ⬝ _, induction b, { exact ap (λ y, dirsum_incl branch bool.ff x * y) (to_respect_one (dirsum_incl branch bool.tt)) ⬝ mul_one _ }, { exact ap (λ y, y * dirsum_incl branch bool.tt x) (to_respect_one (dirsum_incl branch bool.ff)) ⬝ one_mul _ } }, { refine ap from_hom (to_respect_one to_hom) ⬝ to_respect_one from_hom }, { intro g h gβ hβ, refine ap from_hom (to_respect_mul to_hom _ _) ⬝ to_respect_mul from_hom _ _ ⬝ _, exact ap011 mul gβ hβ } } end variables {I J : Type} [is_set I] [is_set J] {Y Y' Y'' : I → AbGroup} definition dirsum_functor [constructor] (f : Πi, Y i →g Y' i) : dirsum Y →g dirsum Y' := dirsum_elim (λi, dirsum_incl Y' i ∘g f i) theorem dirsum_functor_compose (f' : Πi, Y' i →g Y'' i) (f : Πi, Y i →g Y' i) : dirsum_functor f' ∘g dirsum_functor f ~ dirsum_functor (λi, f' i ∘g f i) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable (Y) definition dirsum_functor_gid : dirsum_functor (λi, gid (Y i)) ~ gid (dirsum Y) := begin apply dirsum_homotopy, intro i y, reflexivity, end variable {Y} definition dirsum_functor_mul (f f' : Πi, Y i →g Y' i) : homomorphism_mul (dirsum_functor f) (dirsum_functor f') ~ dirsum_functor (λi, homomorphism_mul (f i) (f' i)) := begin apply dirsum_homotopy, intro i y, exact sorry end definition dirsum_functor_homotopy (f f' : Πi, Y i →g Y' i) (p : f ~2 f') : dirsum_functor f ~ dirsum_functor f' := begin apply dirsum_homotopy, intro i y, exact sorry end definition dirsum_functor_left [constructor] (f : J → I) : dirsum (Y ∘ f) →g dirsum Y := dirsum_elim (λj, dirsum_incl Y (f j)) definition dirsum_isomorphism [constructor] (f : Πi, Y i ≃g Y' i) : dirsum Y ≃g dirsum Y' := let to_hom := dirsum_functor (λ i, f i) in let from_hom := dirsum_functor (λ i, (f i)⁻¹ᵍ) in begin fapply isomorphism.mk, exact dirsum_functor (λ i, f i), fapply is_equiv.adjointify, exact dirsum_functor (λ i, (f i)⁻¹ᵍ), { intro ds, refine (homomorphism_comp_compute (dirsum_functor (λ i, f i)) (dirsum_functor (λ i, (f i)⁻¹ᵍ)) _)⁻¹ ⬝ _, refine dirsum_functor_compose (λ i, f i) (λ i, (f i)⁻¹ᵍ) ds ⬝ _, refine dirsum_functor_homotopy _ (λ i, !gid) (λ i, to_right_inv (equiv_of_isomorphism (f i))) ds ⬝ _, exact !dirsum_functor_gid }, { intro ds, refine (homomorphism_comp_compute (dirsum_functor (λ i, (f i)⁻¹ᵍ)) (dirsum_functor (λ i, f i)) _)⁻¹ ⬝ _, refine dirsum_functor_compose (λ i, (f i)⁻¹ᵍ) (λ i, f i) ds ⬝ _, refine dirsum_functor_homotopy _ (λ i, !gid) (λ i x, proof to_left_inv (equiv_of_isomorphism (f i)) x qed ) ds ⬝ _, exact !dirsum_functor_gid } end end group namespace group definition dirsum_down_left.{u v w} {I : Type.{u}} [is_set I] (Y : I → AbGroup.{w}) : dirsum (Y ∘ down.{u v}) ≃g dirsum Y := proof let to_hom := @dirsum_functor_left _ _ _ _ Y down.{u v} in let from_hom := dirsum_elim (λi, dirsum_incl (Y ∘ down.{u v}) (up.{u v} i)) in begin fapply isomorphism.mk, { exact to_hom }, fapply adjointify, { exact from_hom }, { intro ds, refine (homomorphism_comp_compute to_hom from_hom ds)⁻¹ ⬝ _, refine @dirsum_homotopy I _ Y (dirsum Y) (to_hom ∘g from_hom) !gid _ ds, intro i y, refine homomorphism_comp_compute to_hom from_hom _ ⬝ _, refine ap to_hom (dirsum_elim_compute (λi, dirsum_incl (Y ∘ down.{u v}) (up.{u v} i)) i y) ⬝ _, refine dirsum_elim_compute _ (up.{u v} i) y ⬝ _, reflexivity }, { intro ds, refine (homomorphism_comp_compute from_hom to_hom ds)⁻¹ ⬝ _, refine @dirsum_homotopy _ _ (Y ∘ down.{u v}) (dirsum (Y ∘ down.{u v})) (from_hom ∘g to_hom) !gid _ ds, intro i y, induction i with i, refine homomorphism_comp_compute from_hom to_hom _ ⬝ _, refine ap from_hom (dirsum_elim_compute (λi, dirsum_incl Y (down.{u v} i)) (up.{u v} i) y) ⬝ _, refine dirsum_elim_compute _ i y ⬝ _, reflexivity } end qed end group
ab654c7d56d5704116b2e794893d445f15a2fcba
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/independent_events.lean
7713a35bacea19c0d52a335c6e5804c72e06cedd
[ "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
18,117
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 import measure_theory.lebesgue_measure import measure_theory.integration import measure_theory.borel_space import data.set.countable import formal_ml.nnreal import formal_ml.sum import formal_ml.lattice import formal_ml.measurable_space import formal_ml.classical import data.equiv.list import formal_ml.probability_space /-! This file gives various ways to produce independent events. -/ --- Find a different place for these lemmas ---------- lemma disjoint_exists_and {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (x y:finset α):set.pairwise_on (↑(x∪ y)) (disjoint on (λ s, (E s).val)) → ((∃ᵣ a in x, E a) ∧ (∃ᵣ a in y, E a)) = (∃ᵣ a in (x ∩ y), E a) := begin classical, intros h_disj, apply event.eq, ext1 ω, split; intros h1; simp at h1; simp, { cases h1 with h1 h2, cases h1 with a h1, cases h2 with a' h2, have h3:a = a', { apply by_contradiction, intros h_contra, have h3_1:= h_disj a _ a' _ h_contra, rw [function.on_fun, disjoint_iff, subtype.val_eq_coe, set.inf_eq_inter, set.bot_eq_empty, ← set.subset_compl_iff_disjoint, set.subset_def] at h3_1, apply h3_1 ω h1.right h2.right, simp [h1], simp [h2] }, subst a', apply exists.intro a, simp [h1, h2] }, { cases h1 with a h1, split; apply exists.intro a; simp [h1] }, end lemma disjoint_exists_diff {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (x y:finset α):set.pairwise_on (↑(x∪ y)) (disjoint on (λ s, (E s).val)) → ((∃ᵣ a in x, E a) \ (∃ᵣ a in y, E a)) = (∃ᵣ a in (x \ y), E a) := begin classical, intros h_disj, apply event.eq, ext1 ω, split; intros h1; simp at h1; simp, { cases h1 with h1 h2, cases h1 with i h1, apply exists.intro i, split, split, { apply h1.left }, { intros contra, apply h2 i contra, apply h1.right }, apply h1.right }, { cases h1 with i h1, split, { apply exists.intro i, simp [h1] }, { intros a' h_a'_in_y h_contra, have h2:a' = i, { apply by_contradiction, intros h_contra2, have h2_disj := h_disj a' _ i _ h_contra2, rw [function.on_fun, set.disjoint_left] at h2_disj, simp at h2_disj, apply h2_disj h_contra, apply h1.right, simp, right, apply h_a'_in_y, simp, left, apply h1.left.left }, subst a', apply h1.left.right, apply h_a'_in_y } }, end lemma exists_or {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (x y:finset α): ((∃ᵣ a in x, E a) ∨ (∃ᵣ a in y, E a)) = (∃ᵣ a in (x ∪ y), E a) := begin classical, apply event.eq, ext1 ω, split; intros h1; simp at h1; simp, { cases h1 with h1 h1; { cases h1 with a h1, apply exists.intro a, simp [h1] } }, { cases h1 with a h1, cases h1 with h1 h2, cases h1 with h1 h1, { left, apply exists.intro a, simp [h1,h2] }, { right, apply exists.intro a, simp [h1,h2] } }, end lemma forall_and {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (x y:finset α): ((∀ᵣ a in x, E a) ∧ (∀ᵣ a in y, E a)) = (∀ᵣ a in (x ∪ y), E a) := begin classical, apply event.eq, ext1 ω, split; intros h1; simp at h1; simp [h1], { cases h1 with h1 h2, intros a h3, cases h3 with h3 h3, { apply h1 a h3 }, { apply h2 a h3 } }, { split; intros a h2; apply h1; { simp [h2] } }, end ----------------------------------------- lemma independent_event_pair_exists {Ω α:Type*} {P:probability_space Ω} {S:finset α} {E:event P} {F:α → event P} [decidable_eq (event P)]: (∀ (s∈ S), independent_event_pair E (F s)) → (set.pairwise_on (↑S) (disjoint on (λ a, (F a).val))) → independent_event_pair E (∃ᵣ a in S, F a) := begin classical, intros h1 h2, simp [independent_event_pair], --rw eany_in_finset_def, rw Pr_sum_disjoint_eq', rw ← finset.sum_distrib_left, rw ← distrib_exists_and, rw Pr_sum_disjoint_eq', apply finset.sum_congr, { refl }, { intros x h_x, have h4 := h1 x h_x, simp [independent_event_pair] at h4, apply h4 }, { intros i h_i j h_j h_ne, simp only [function.on_fun], rw disjoint_iff, simp, rw ← set.subset_empty_iff, apply set.subset.trans, apply set.inter_subset_inter, apply set.inter_subset_right, apply set.inter_subset_right, have h5 := h2 i _ j _ h_ne, simp only [function.on_fun] at h5, rw disjoint_iff at h5, simp at h5, rw h5, apply h_i, apply h_j }, apply h2, end lemma independent_events_induction {Ω:Type*} {α:Type*} {P:probability_space Ω} {E:α → event P}:(∀ (a:α) (S:finset α), (a ∉ S) → independent_event_pair (E a) (∀ᵣ a' in S, E a')) → (independent_events E) := begin classical, intros h1 T, apply finset.induction_on T, { simp }, { intros a s h2 h3, rw finset.prod_insert, rw eall_finset_insert, have h4 := h1 a s h2, unfold independent_event_pair at h4, rw h4, rw ← h3, apply h2 }, end @[simp] lemma event_univ_and {Ω:Type*} {P:probability_space Ω} {A:event P}: (event_univ ∧ A) = A := begin apply event.eq, simp, end lemma Pr_and_or_not_and {Ω:Type*} {P:probability_space Ω} {A B:event P}: Pr[(A ∧ B)] + Pr[(¬ₑ A) ∧ B] = Pr[B] := begin have h1:((A ∧ B) ∨ ((¬ₑ A)) ∧ B) = B, { apply event.eq, ext ω, split; intros h1; simp at h1; simp [h1], cases h1 with h1 h1; simp [h1], apply (classical.em (ω ∈ ↑(A))), }, rw ← Pr_disjoint_eor, rw h1, rw disjoint_iff, ext1 ω, split; intros h2; simp at h2; simp [h2], apply h2.right.left h2.left.left, apply false.elim h2, end lemma Pr_not_and_eq {Ω:Type*} {P:probability_space Ω} {A B:event P}: Pr[(¬ₑ A)∧ B] = Pr[B] - Pr[A ∧ B] := begin rw ← @Pr_and_or_not_and _ _ A B, rw add_comm, rw nnreal.add_sub_cancel, end lemma nnreal.sub_mul_eq {a b c:nnreal}:(a - b) * c = (a * c) - (b * c) := begin cases (le_total a b) with h h, { have h2:(a * c) ≤ (b * c), { apply mul_le_mul', apply h, apply le_refl _ }, rw nnreal.sub_eq_zero h, rw nnreal.sub_eq_zero h2, simp }, have h2:(b * c) ≤ (a * c), { apply mul_le_mul', apply h, apply le_refl _ }, rw ← nnreal.coe_eq, rw nnreal.coe_mul, rw nnreal.coe_sub h, rw nnreal.coe_sub h2, rw nnreal.coe_mul, rw nnreal.coe_mul, linarith, end lemma independent_events_rel {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (f:α → event P) (h_ind:independent_events f) (T_not:finset α) (T_same:finset α) (h_disj:disjoint T_not T_same): Pr[(∀ᵣ a in T_not, ¬ₑ (f a)) ∧ (∀ᵣ a in T_same, (f a))] = (T_not.prod (λ a, Pr[¬ₑ (f a)])) * (T_same.prod (λ a, Pr[f a])) := begin revert T_same, apply finset.induction_on T_not, { intros T_same h_disj, simp, rw h_ind, }, { intros a s h_a_notin_s h_ind T_same T_disj, rw has_eall_in_insert, rw eand_assoc, rw Pr_not_and_eq, rw h_ind T_same _, have h1:∀ (A B C:event P), (A ∧ (B ∧ C)) = (B ∧ (A ∧ C)), { intros A B C, apply event.eq, ext1 ω; split; intros h1; simp at h1; simp [h1] }, rw ← eand_assoc, rw eand_comm (f a), rw eand_assoc, rw ← has_eall_in_insert, rw h_ind (insert a T_same) _, rw finset.prod_insert, rw finset.prod_insert, rw ← Pr_one_minus_eq_not, rw nnreal.sub_mul_eq, rw nnreal.sub_mul_eq, rw ← mul_assoc, rw mul_comm _ (Pr[f a]), simp, { apply h_a_notin_s }, { rw finset.disjoint_left at T_disj, apply T_disj, simp }, { rw finset.disjoint_left, intros a' h_a'_in_s, rw finset.disjoint_left at T_disj, intros contra, simp at contra, cases contra with contra contra, { subst a', apply h_a_notin_s h_a'_in_s }, { apply @T_disj a', simp [h_a'_in_s], apply contra, } }, { rw finset.disjoint_left, intros a' h_a'_in_s, rw finset.disjoint_left at T_disj, apply T_disj, simp [h_a'_in_s] } }, end /-- This represents a function of a finite number of events in a tabular way. -/ def function_of_events {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F:event P):Prop := ∃ (T:finset (finset α)), T ⊆ S.powerset ∧ (∃ᵣ s in T, (∀ᵣ a in s, E a) ∧ (∀ᵣ a in (S \ s), ¬ₑ(E a))) = F lemma function_of_events_event {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (a:α) (h_a:a ∈ S):function_of_events E S (E a) := begin classical, apply exists.intro (S.powerset.filter (λ s, a ∈ s)), split, { simp }, apply event.eq, ext1 ω, split; intros h1; simp [h1]; simp at h1, { cases h1 with s h1, cases h1 with h1 h2, cases h2 with h2 h3, apply h2 a h1.right, }, { apply exists.intro (S.filter (λ a', ω ∈ E a')), simp [h_a, h1],split, { apply h1 }, split, { intros i h4 h5, apply h5 }, { intros i h4 h5, apply h5 h4 } }, end lemma disjoint_union {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α):set.pairwise_on ↑(S.powerset) (λ s t, disjoint ((∀ᵣ a in s, E a) ∧ (∀ᵣ a in (S \ s), ¬ₑ(E a))).val ((∀ᵣ a in t, E a) ∧ (∀ᵣ a in (S \ t), ¬ₑ(E a))).val) := begin classical, intros i h_i j h_j h_ne, have h_ne_exists:∃ a, ((a ∈ i) ∧ (a ∉ j)) ∨ ((a∉ i) ∧ (a ∈ j)), { rw ← not_forall_not, intros contra, apply h_ne, ext a, have contra_a := contra a, split; intros h_1; apply by_contradiction; intros h_2; apply contra_a; simp [contra_a, h_1, h_2] }, have h_i_subset_S:i ⊆ S, { rw [finset.mem_coe, finset.mem_powerset] at h_i, apply h_i }, have h_j_subset_S:j ⊆ S, { rw [finset.mem_coe, finset.mem_powerset] at h_j, apply h_j }, rw disjoint_iff, simp, rw ← set.subset_compl_iff_disjoint, rw set.subset_def, intros ω h_ω, simp at h_ω, simp, intros h_j, cases h_ne_exists with a h_ne_exists, cases h_ne_exists with h_a_in_i h_a_in_j, { have h_ω_2 := h_ω.left a h_a_in_i.left, apply exists.intro a, simp [h_ω_2, h_a_in_i], apply h_i_subset_S, apply h_a_in_i.left }, { exfalso, apply h_ω.right a _ h_a_in_j.left, apply h_j, apply h_a_in_j.right, apply h_j_subset_S, apply h_a_in_j.right }, end lemma disjoint_union_sub {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F:finset (finset α)) (h_sub:F⊆ S.powerset):set.pairwise_on ↑(F) (λ s t, disjoint ((∀ᵣ a in s, E a) ∧ (∀ᵣ a in (S \ s), ¬ₑ(E a))).val ((∀ᵣ a in t, E a) ∧ (∀ᵣ a in (S \ t), ¬ₑ(E a))).val) := begin apply @set.pairwise_on.mono (finset α) (↑S.powerset) ↑F (λ (s t : finset α), disjoint ((∀ᵣ (a : α) in s,E a)∧∀ᵣ (a : α) in S \ s,¬ₑ E a).val ((∀ᵣ (a : α) in t,E a)∧∀ᵣ (a : α) in S \ t,¬ₑ E a).val) _ _, { simp [h_sub] }, apply disjoint_union, end #print instances has_sdiff lemma function_of_events_diff {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F G:event P) (h_F:function_of_events E S F) (h_G:function_of_events E S G):function_of_events E S (F \ G) := begin cases h_F with F_T h_F, cases h_G with G_T h_G, apply exists.intro (F_T \ G_T), split, { apply finset.subset.trans, apply finset.sdiff_subset, apply h_F.left }, rw ← disjoint_exists_diff, rw h_F.right, rw h_G.right, apply disjoint_union_sub, apply finset.union_subset, apply h_F.left, apply h_G.left, end @[simp] lemma function_of_events_univ {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α): (function_of_events E S event_univ) := begin classical, apply exists.intro (S.powerset), split, apply finset.subset.refl, apply event.eq, ext1 ω, split; intros h1; simp at h1, simp, apply exists.intro (S.filter (λ a, ω ∈ (E a))), split, simp, split, { intros i h_i, simp at h_i, apply h_i.right }, { intros i h_1 h_2 h_3, apply h_2, simp, apply and.intro h_1, apply h_3 }, end lemma function_of_events_compl {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F:event P) (h_F:function_of_events E S F):function_of_events E S (Fᶜ) := begin have h1:event_univ \ F = Fᶜ, { apply event.eq, ext1 ω, split; intros h1; simp at h1; simp [h1], }, rw ← h1, apply function_of_events_diff, simp, apply h_F, end lemma function_of_events_and {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F G:event P) (h_F:function_of_events E S F) (h_G:function_of_events E S G):function_of_events E S (F ∧ G) := begin have h1:(F ∧ G) = F \ Gᶜ, { apply event.eq, ext1 ω, split; intros h1; simp at h1; simp [h1], }, rw h1, apply function_of_events_diff, apply h_F, apply function_of_events_compl, apply h_G, end lemma function_of_events_or {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F G:event P) (h_F:function_of_events E S F) (h_G:function_of_events E S G):function_of_events E S (F ∨ G) := begin cases h_F with F_T h_F, cases h_G with G_T h_G, apply exists.intro (F_T ∪ G_T), split, { apply finset.union_subset; simp [h_F, h_G], }, rw ← exists_or, rw h_F.right, rw h_G.right, end lemma function_of_events_not {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (F:event P) (h_F:function_of_events E S F):function_of_events E S (¬ₑ F) := begin have h1:(¬ₑ F) = Fᶜ, { apply event.eq, simp }, rw h1, apply function_of_events_compl, apply h_F, end lemma function_of_events_empty {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α):function_of_events E S ∅ := begin have h1:(¬ₑ event_univ) = (∅:event P), { apply event.eq, simp }, rw ← h1, apply function_of_events_compl, apply function_of_events_univ, end lemma function_of_events_forall {α β Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (S:finset α) (T:finset β) (F:β → event P) (h_F:∀ b∈ T, function_of_events E S (F b)) :function_of_events E S (∀ᵣ b in T, F b) := begin classical, revert h_F, apply finset.induction_on T, { intros, simp }, { intros b T' h_b_notin_T' h2 h3, rw has_eall_in_insert, apply function_of_events_and, { apply h3, simp }, { apply h2, intros b h_b, apply h3, simp [h_b] } }, end lemma function_of_events_ind {α Ω:Type*} {P:probability_space Ω} [decidable_eq α] (E:α → event P) (h_ind:independent_events E) (S T:finset α) (F G:event P) (h_disj: disjoint S T) (h_F:function_of_events E S F) (h_G:function_of_events E T G): independent_event_pair F G := begin classical, have h_disj_diff:∀ (s t:finset α), disjoint (s \ t) t, { intros s t, rw finset.disjoint_left, intros a h_a, simp at h_a, apply h_a.right }, have h_disj_subset:∀ (s t:finset α), (s ⊆ S) → (t ⊆ T) → (disjoint s t), { intros s t h_s h_t, rw finset.disjoint_left, rw finset.disjoint_left at h_disj, intros a h_a h_a', apply h_disj, apply h_s h_a, apply h_t h_a' }, cases h_G with T_G h_G, have h_subset_T:∀ t ∈ T_G, t ⊆ T, { intros t h_t, apply finset.mem_powerset.1 (h_G.left h_t) }, cases h_F with T_F h_F, have h_subset_S:∀ s ∈ T_F, s ⊆ S, { intros s h_s, apply finset.mem_powerset.1 (h_F.left h_s) }, rw ← h_G.right, apply independent_event_pair_exists, intros s h_s, rw ← h_F.right, apply independent_event_pair.symm, apply independent_event_pair_exists, intros t h_t, apply independent_event_pair.symm, rw eand_comm, rw eand_comm (∀ᵣ (a : α) in s,E a), unfold independent_event_pair, have h1:∀ (H1 H2 H3 H4:event P), ((H1 ∧ H2) ∧ (H3 ∧ H4)) = ((H1 ∧ H3) ∧ (H2 ∧ H4)), { intros H1 H2 H3 H4, apply event.eq, ext1 ω, split; intros h1_1; simp at h1_1; simp [h1_1] }, rw h1, rw forall_and, rw forall_and, rw independent_events_rel, rw independent_events_rel, rw independent_events_rel, rw finset.prod_union, rw finset.prod_union, have h2:∀ (a b c d:nnreal), a * b * (c * d) = a * c * (b * d), { intros a b c d, rw ← nnreal.coe_eq, repeat { rw nnreal.coe_mul }, linarith }, rw h2, { apply h_disj_subset, apply h_subset_S _ h_t, apply h_subset_T _ h_s }, { apply h_disj_subset, simp, simp }, apply h_ind, { rw finset.disjoint_left, intros a h_a, simp at h_a, apply h_a.right }, apply h_ind, { rw finset.disjoint_left, intros a h_a, simp at h_a, apply h_a.right }, apply h_ind, { rw finset.disjoint_left, intros a h_a h_a', simp at h_a', simp [h_a'] at h_a, cases h_a with h_a h_a; cases h_a' with h_a' h_a', { apply h_a.right h_a' }, { rw finset.disjoint_left at h_disj, apply h_disj h_a.left, apply h_subset_T s h_s h_a' }, { rw finset.disjoint_right at h_disj, apply h_disj h_a.left, apply h_subset_S t h_t h_a' }, { apply h_a.right h_a' } }, { apply disjoint_union_sub, apply h_F.left }, { apply disjoint_union_sub, apply h_G.left }, end
a50fbba2c7f661545afa91b3c6ee5beb8280adb5
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/smt/congruence_closure.lean
5e03494dedd64a10f66809976a7d029eccaddbc0
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,372
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.set_get_option_tactics structure cc_config := /- If tt, congruence closure will treat implicit instance arguments as constants. -/ (ignore_instances : bool := tt) /- If tt, congruence closure modulo AC. -/ (ac : bool := tt) /- If ho_fns is (some fns), then full (and more expensive) support for higher-order functions is *only* considered for the functions in fns and local functions. The performance overhead is described in the paper "Congruence Closure in Intensional Type Theory". If ho_fns is none, then full support is provided for *all* constants. -/ (ho_fns : option (list name) := none) /- If true, then use excluded middle -/ (em : bool := tt) /- Congruence closure state -/ meta constant cc_state : Type meta constant cc_state.mk_core : cc_config → cc_state /- Create a congruence closure state object using the hypotheses in the current goal. -/ meta constant cc_state.mk_using_hs_core : cc_config → tactic cc_state meta constant cc_state.next : cc_state → expr → expr meta constant cc_state.roots_core : cc_state → bool → list expr meta constant cc_state.root : cc_state → expr → expr meta constant cc_state.mt : cc_state → expr → nat meta constant cc_state.gmt : cc_state → nat meta constant cc_state.inc_gmt : cc_state → cc_state meta constant cc_state.is_cg_root : cc_state → expr → bool meta constant cc_state.pp_eqc : cc_state → expr → tactic format meta constant cc_state.pp_core : cc_state → bool → tactic format meta constant cc_state.internalize : cc_state → expr → tactic cc_state meta constant cc_state.add : cc_state → expr → tactic cc_state meta constant cc_state.is_eqv : cc_state → expr → expr → tactic bool meta constant cc_state.is_not_eqv : cc_state → expr → expr → tactic bool meta constant cc_state.eqv_proof : cc_state → expr → expr → tactic expr meta constant cc_state.inconsistent : cc_state → bool /- (proof_for cc e) constructs a proof for e if it is equivalent to true in cc_state -/ meta constant cc_state.proof_for : cc_state → expr → tactic expr /- (refutation_for cc e) constructs a proof for (not e) if it is equivalent to false in cc_state -/ meta constant cc_state.refutation_for : cc_state → expr → tactic expr /- If the given state is inconsistent, return a proof for false. Otherwise fail. -/ meta constant cc_state.proof_for_false : cc_state → tactic expr namespace cc_state meta def mk : cc_state := cc_state.mk_core {} meta def mk_using_hs : tactic cc_state := cc_state.mk_using_hs_core {} meta def roots (s : cc_state) : list expr := cc_state.roots_core s tt meta instance : has_to_tactic_format cc_state := ⟨λ s, cc_state.pp_core s tt⟩ meta def eqc_of_core (s : cc_state) : expr → expr → list expr → list expr | e f r := let n := s.next e in if n = f then e::r else eqc_of_core n f (e::r) meta def eqc_of (s : cc_state) (e : expr) : list expr := s.eqc_of_core e e [] meta def in_singlenton_eqc (s : cc_state) (e : expr) : bool := s.next e = e meta def eqc_size (s : cc_state) (e : expr) : nat := (s.eqc_of e).length meta def fold_eqc_core {α} (s : cc_state) (f : α → expr → α) (first : expr) : expr → α → α | c a := let new_a := f a c, next := s.next c in if next =ₐ first then new_a else fold_eqc_core next new_a meta def fold_eqc {α} (s : cc_state) (e : expr) (a : α) (f : α → expr → α) : α := fold_eqc_core s f e e a meta def mfold_eqc {α} {m : Type → Type} [monad m] (s : cc_state) (e : expr) (a : α) (f : α → expr → m α) : m α := fold_eqc s e (return a) (λ act e, do a ← act, f a e) end cc_state open tactic meta def tactic.cc_core (cfg : cc_config) : tactic unit := do intros, s ← cc_state.mk_using_hs_core cfg, t ← target, s ← s.internalize t, if s.inconsistent then do { pr ← s.proof_for_false, mk_app `false.elim [t, pr] >>= exact} else do { tr ← return $ expr.const `true [], b ← s.is_eqv t tr, if b then do { pr ← s.eqv_proof t tr, mk_app `of_eq_true [pr] >>= exact } else do { dbg ← get_bool_option `trace.cc.failure ff, if dbg then do { ccf ← pp s, msg ← return $ to_fmt "cc tactic failed, equivalence classes: " ++ format.line ++ ccf, fail msg } else do { fail "cc tactic failed" } } } meta def tactic.cc : tactic unit := tactic.cc_core {} meta def tactic.cc_dbg_core (cfg : cc_config) : tactic unit := save_options $ set_bool_option `trace.cc.failure tt >> tactic.cc_core cfg meta def tactic.cc_dbg : tactic unit := tactic.cc_dbg_core {} meta def tactic.ac_refl : tactic unit := do (lhs, rhs) ← target >>= match_eq, s ← return $ cc_state.mk, s ← s.internalize lhs, s ← s.internalize rhs, b ← s.is_eqv lhs rhs, if b then do { s.eqv_proof lhs rhs >>= exact } else do { fail "ac_refl failed" }
7820e822438bc799008a0dd6383040a750a11c07
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/doc_string3.lean
0789671623fb0405ee5135429a619c5486ac4172
[ "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
299
lean
/-! Documentation header for test module -/ /-- Documentation for x -/ def x := 10 namespace foo /-! Another block of documentation for this example. -/ /-- Documentation for y -/ def y := 20 end foo /-! Documentation footer testing -/ open tactic run_cmd module_doc_strings >>= trace
202f1072335ff316656f9f1ff946723195a4d127
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/frontend/Frontend.lean
211aebc82b5cdf00f15d83729df84f53fb39c543
[ "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
79
lean
import Frontend.RegisterOption import Frontend.Import1 import Frontend.Import2
e5ef673cb03189f4e003dece2cffb62fcf532a10
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/shapes/kernel_pair.lean
d4a5048b72e99aadd6a72b1ebc3ff6af5ead4a11
[ "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
6,401
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.pullbacks import category_theory.limits.shapes.regular_mono /-! # Kernel pairs This file defines what it means for a parallel pair of morphisms `a b : R ⟶ X` to be the kernel pair for a morphism `f`. Some properties of kernel pairs are given, namely allowing one to transfer between the kernel pair of `f₁ ≫ f₂` to the kernel pair of `f₁`. It is also proved that if `f` is a coequalizer of some pair, and `a`,`b` is a kernel pair for `f` then it is a coequalizer of `a`,`b`. ## Implementation The definition is essentially just a wrapper for `is_limit (pullback_cone.mk _ _ _)`, but the constructions given here are useful, yet awkward to present in that language, so a basic API is developed here. ## TODO - Internal equivalence relations (or congruences) and the fact that every kernel pair induces one, and the converse in an effective regular category (WIP by b-mehta). -/ universes v u u₂ namespace category_theory open category_theory category_theory.category category_theory.limits variables {C : Type u} [category.{v} C] variables {R X Y Z : C} (f : X ⟶ Y) (a b : R ⟶ X) /-- `is_kernel_pair f a b` expresses that `(a, b)` is a kernel pair for `f`, i.e. `a ≫ f = b ≫ f` and the square R → X ↓ ↓ X → Y is a pullback square. This is essentially just a convenience wrapper over `is_limit (pullback_cone.mk _ _ _)`. -/ structure is_kernel_pair := (comm : a ≫ f = b ≫ f) (is_limit : is_limit (pullback_cone.mk _ _ comm)) attribute [reassoc] is_kernel_pair.comm namespace is_kernel_pair /-- The data expressing that `(a, b)` is a kernel pair is subsingleton. -/ instance : subsingleton (is_kernel_pair f a b) := ⟨λ P Q, by { cases P, cases Q, congr, }⟩ /-- If `f` is a monomorphism, then `(𝟙 _, 𝟙 _)` is a kernel pair for `f`. -/ def id_of_mono [mono f] : is_kernel_pair f (𝟙 _) (𝟙 _) := { comm := rfl, is_limit := pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨s.snd, _, comp_id _, λ m m₁ m₂, _⟩, { rw [← cancel_mono f, s.condition, pullback_cone.mk_fst, cancel_mono f], apply comp_id }, rw [← m₂], apply (comp_id _).symm, end } instance [mono f] : inhabited (is_kernel_pair f (𝟙 _) (𝟙 _)) := ⟨id_of_mono f⟩ variables {f a b} /-- Given a pair of morphisms `p`, `q` to `X` which factor through `f`, they factor through any kernel pair of `f`. -/ def lift' {S : C} (k : is_kernel_pair f a b) (p q : S ⟶ X) (w : p ≫ f = q ≫ f) : { t : S ⟶ R // t ≫ a = p ∧ t ≫ b = q } := pullback_cone.is_limit.lift' k.is_limit _ _ w /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `a ≫ f₁ = b ≫ f₁`, then `(a,b)` is a kernel pair for just `f₁`. That is, to show that `(a,b)` is a kernel pair for `f₁` it suffices to only show the square commutes, rather than to additionally show it's a pullback. -/ def cancel_right {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} (comm : a ≫ f₁ = b ≫ f₁) (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := { comm := comm, is_limit := pullback_cone.is_limit_aux' _ $ λ s, begin let s' : pullback_cone (f₁ ≫ f₂) (f₁ ≫ f₂) := pullback_cone.mk s.fst s.snd (s.condition_assoc _), refine ⟨big_k.is_limit.lift s', big_k.is_limit.fac _ walking_cospan.left, big_k.is_limit.fac _ walking_cospan.right, λ m m₁ m₂, _⟩, apply big_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone (f₁ ≫ f₂) _).equalizer_ext _ _, apply m₁.trans (big_k.is_limit.fac s' walking_cospan.left).symm, apply m₂.trans (big_k.is_limit.fac s' walking_cospan.right).symm, end } /-- If `(a,b)` is a kernel pair for `f₁ ≫ f₂` and `f₂` is mono, then `(a,b)` is a kernel pair for just `f₁`. The converse of `comp_of_mono`. -/ def cancel_right_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (big_k : is_kernel_pair (f₁ ≫ f₂) a b) : is_kernel_pair f₁ a b := cancel_right (begin rw [← cancel_mono f₂, assoc, assoc, big_k.comm] end) big_k /-- If `(a,b)` is a kernel pair for `f₁` and `f₂` is mono, then `(a,b)` is a kernel pair for `f₁ ≫ f₂`. The converse of `cancel_right_of_mono`. -/ def comp_of_mono {f₁ : X ⟶ Y} {f₂ : Y ⟶ Z} [mono f₂] (small_k : is_kernel_pair f₁ a b) : is_kernel_pair (f₁ ≫ f₂) a b := { comm := by rw [small_k.comm_assoc], is_limit := pullback_cone.is_limit_aux' _ $ λ s, begin refine ⟨_, _, _, _⟩, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).1, rw [← cancel_mono f₂, assoc, s.condition, assoc], apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1, apply (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2, intros m m₁ m₂, apply small_k.is_limit.hom_ext, refine ((pullback_cone.mk a b _) : pullback_cone f₁ _).equalizer_ext _ _, rwa (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.1, rwa (pullback_cone.is_limit.lift' small_k.is_limit s.fst s.snd _).2.2, end } /-- If `(a,b)` is the kernel pair of `f`, and `f` is a coequalizer morphism for some parallel pair, then `f` is a coequalizer morphism of `a` and `b`. -/ def to_coequalizer (k : is_kernel_pair f a b) [r : regular_epi f] : is_colimit (cofork.of_π f k.comm) := begin let t := k.is_limit.lift (pullback_cone.mk _ _ r.w), have ht : t ≫ a = r.left := k.is_limit.fac _ walking_cospan.left, have kt : t ≫ b = r.right := k.is_limit.fac _ walking_cospan.right, apply cofork.is_colimit.mk _ _ _ _, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).1, rw [← ht, assoc, s.condition, reassoc_of kt] }, { intro s, apply (cofork.is_colimit.desc' r.is_colimit s.π _).2 }, { intros s m w, apply r.is_colimit.hom_ext, rintro ⟨⟩, change (r.left ≫ f) ≫ m = (r.left ≫ f) ≫ _, rw [assoc, assoc], congr' 1, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w walking_parallel_pair.one, erw (cofork.is_colimit.desc' r.is_colimit s.π _).2, apply w walking_parallel_pair.one } end end is_kernel_pair end category_theory
2b1e9f7839635cc9c6aefbec1807ccc3c10e2bdf
c9e78e68dc955b2325401aec3a6d3240cd8b83f4
/src/pumpold.lean
b74f98067303769d6498422571c198e5d2ff77a6
[]
no_license
loganrjmurphy/lean-strategies
4b8dd54771bb421c929a8bcb93a528ce6c1a70f1
832ea28077701b977b4fc59ed9a8ce6911654e59
refs/heads/master
1,682,732,168,860
1,621,444,295,000
1,621,444,295,000
278,458,841
3
0
null
1,613,755,728,000
1,594,324,763,000
Lean
UTF-8
Lean
false
false
4,967
lean
import justification common_meta property_catalogue.LTL import pump1 open interactive S A variable {α : Type} set_option pp.structure_instances_qualifier true def local_input_name : string := "pump1_input_1" def local_strat_name : string := "pump1_strat_1" def local_prf_name : string := "pump1_prf_1" def preamble : string := "import justification pump1 common_meta property_catalogue.LTL \n open S A" meta def proof_template (p₁ p₂ : string) : string := "\n\n theorem " ++ local_prf_name ++ " : " ++ p₁ ++ " := \nbegin \n" ++ p₂ ++ "\nend" ++ "\n\n\n" meta def evidence_file_template (ps : PROOF_STATE α) : string := preamble ++ "\n\n @[reducible] def " ++ local_input_name ++ " : property.input (path pump1) := "++ ps.input_string ++ "\n\n @[reducible] def "++ local_strat_name ++ " : Strategy (path pump1) := property.strategy " ++ local_input_name ++ proof_template ("deductive (path pump1) " ++ local_strat_name) (tscript_string ps.tscript) ++ ps.unused ++ hints_string ps.hints meta def output (s : string) : io unit := do of ← io.mk_file_handle "src/evidence.lean" io.mode.write, io.fs.write of s.to_char_buffer meta def driver (input : pexpr) : tactic unit := let α := path pump1 in let ps : PROOF_STATE α := {} in do STRAT ← tactic.to_expr input, match STRAT with | `(property.input.mk %%CLAIM %%PROPS) := do inpt ← tactic.eval_expr (property.input α) STRAT, input_fmt ← tactic_format_expr STRAT, let input_s := input_fmt.to_string, let ps := { input := inpt, input_string := input_s, strat_expr := STRAT , PROPS := PROPS, -- TODO : Clean this init_goal := `(deductive (path pump1) (property.strategy %%STRAT)), ..ps}, -- And this let ps := get_originals ps, let goal_str := "deductive (path pump1) " ++ local_strat_name, set_goal ps.init_goal, ps ← SOLVE (ps), str ← get_unused ps, match ps.solved with | tt := tactic.trace "True" | ff := tactic.trace "False" end, tactic.unsafe_run_io $ output $ evidence_file_template {unused := str ..ps} | _ := return () end @[user_command] meta def main (meta_info : decl_meta_info) (_ : parse (lean.parser.tk "main")) : lean.parser unit := do F ← read "src/input/pumpExample1.txt" types.texpr, lean.parser.of_tactic $ driver F . main -- OLD version, will integrate -- def foobar : property.input (path fcs) := {} -- variable {α : Type} -- set_option pp.structure_instances_qualifier true -- def local_input_name : string := "fcs_input_1" -- def local_strat_name : string := "fcs_strat_1" -- def local_prf_name : string := "fcs_prf_1" -- def preamble : string := "import justification fcs common_meta property_catalogue.LTL \n open S A" -- meta def proof_template (p₁ p₂ : string) : string := -- "\n\n -- theorem " ++ local_prf_name ++ " : " ++ p₁ ++ " := \nbegin \n" ++ p₂ ++ "\nend" ++ "\n\n\n" -- meta def evidence_file_template (ps : PROOF_STATE α) : string := -- preamble -- ++ "\n\n @[reducible] def " ++ local_input_name -- ++ " : property.input (path fcs) := "++ ps.input_string -- ++ "\n\n @[reducible] def "++ local_strat_name -- ++ " : Strategy (path fcs) := property.strategy " ++ local_input_name -- ++ proof_template ("deductive (path fcs) " ++ local_strat_name) (tscript_string ps.tscript) -- ++ ps.unused ++ hints_string ps.hints -- meta def output (s : string) : io unit := do -- of ← io.mk_file_handle "src/evidence.lean" io.mode.write, -- io.fs.write of s.to_char_buffer -- meta def driver (input : pexpr) : tactic unit := -- let α := path fcs in -- let ps : PROOF_STATE α := {} in -- do -- STRAT ← tactic.to_expr input, -- match STRAT with -- | `(property.input.mk %%CLAIM %%PROPS) := -- do -- inpt ← tactic.eval_expr (property.input α) STRAT, -- input_fmt ← tactic_format_expr STRAT, -- let input_s := input_fmt.to_string, -- let ps := { input := inpt, -- input_string := input_s, -- strat_expr := STRAT , -- PROPS := PROPS, -- -- TODO : Clean this -- init_goal := `(deductive (path fcs) (property.strategy %%STRAT)), -- ..ps}, -- -- And this -- let ps := get_originals ps, -- let goal_str := "deductive (path fcs) " ++ local_strat_name, -- set_goal ps.init_goal, -- ps ← solve_inductive (ps), -- str ← get_unused ps, -- match ps.solved with -- | tt := tactic.trace "True" -- | ff := tactic.trace "False" -- end, -- tactic.unsafe_run_io $ output $ evidence_file_template {unused := str ..ps} -- | _ := return () -- end -- @[user_command] -- meta def main -- (meta_info : decl_meta_info) -- (_ : parse (lean.parser.tk "main")) : lean.parser unit := -- do -- F ← read "src/input/Inductive_Example.txt" types.texpr, -- lean.parser.of_tactic $ driver F -- .
6afe41ca48924150e5769220390b9304e059e28b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/natural_transformation.lean
2b9405dee4f9eb10d28e18928d2a88c99d0e2d49
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,782
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn Defines natural transformations between functors. Introduces notations `τ.app X` for the components of natural transformations, `F ⟶ G` for the type of natural transformations between functors `F` and `G`, `σ ≫ τ` for vertical compositions, and `σ ◫ τ` for horizontal compositions. -/ import category_theory.functor namespace category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `nat_trans F G` represents a natural transformation between functors `F` and `G`. The field `app` provides the components of the natural transformation. Naturality is expressed by `α.naturality_lemma`. -/ @[ext] structure nat_trans (F G : C ⥤ D) : Type (max u₁ v₂) := (app : Π X : C, (F.obj X) ⟶ (G.obj X)) (naturality' : ∀ {{X Y : C}} (f : X ⟶ Y), (F.map f) ≫ (app Y) = (app X) ≫ (G.map f) . obviously) restate_axiom nat_trans.naturality' -- Rather arbitrarily, we say that the 'simpler' form is -- components of natural transfomations moving earlier. attribute [simp, reassoc] nat_trans.naturality namespace nat_trans /-- `nat_trans.id F` is the identity natural transformation on a functor `F`. -/ protected def id (F : C ⥤ D) : nat_trans F F := { app := λ X, 𝟙 (F.obj X) } @[simp] lemma id_app' (F : C ⥤ D) (X : C) : (nat_trans.id F).app X = 𝟙 (F.obj X) := rfl open category open category_theory.functor section variables {F G H I : C ⥤ D} /-- `vcomp α β` is the vertical compositions of natural transformations. -/ def vcomp (α : nat_trans F G) (β : nat_trans G H) : nat_trans F H := { app := λ X, (α.app X) ≫ (β.app X) } -- functor_category will rewrite (vcomp α β) to (α ≫ β), so this is not a -- suitable simp lemma. We will declare the variant vcomp_app' there. lemma vcomp_app (α : nat_trans F G) (β : nat_trans G H) (X : C) : (vcomp α β).app X = (α.app X) ≫ (β.app X) := rfl end /-- The diagram F(f) F(g) F(h) F X ----> F Y ----> F U ----> F U | | | | | α(X) | α(Y) | α(U) | α(V) v v v v G X ----> G Y ----> G U ----> G V G(f) G(g) G(h) commutes. -/ example {F G : C ⥤ D} (α : nat_trans F G) {X Y U V : C} (f : X ⟶ Y) (g : Y ⟶ U) (h : U ⟶ V) : α.app X ≫ G.map f ≫ G.map g ≫ G.map h = F.map f ≫ F.map g ≫ F.map h ≫ α.app V := by simp end nat_trans end category_theory
95c5413ce5afe255fc6eb9df22db1c9d101c6661
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/unification_hints1.lean
6e4ce71ba03f27ddda70e232c74184abc0dd1587
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
1,652
lean
import data.list data.nat open list nat structure unification_constraint := {A : Type} (lhs : A) (rhs : A) structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) namespace toy constants (A : Type.{1}) (f h : A → A) (x y z : A) definition g [irreducible] (x y : A) : A := f z #unify (g x y), (f z) definition toy_hint [unify] (x y : A) : unification_hint := unification_hint.mk (unification_constraint.mk (g x y) (f z)) [] #unify (g x y), (f z) print [unify] end toy namespace add constants (n : ℕ) #unify (n + 1), succ n definition add_zero_hint [unify] (m n : ℕ) [has_add ℕ] [has_one ℕ] [has_zero ℕ] : unification_hint := unification_hint.mk (unification_constraint.mk (m + 1) (succ n)) [unification_constraint.mk m n] #unify (n + 1), (succ n) print [unify] end add namespace canonical structure Canonical := (carrier : Type) (op : carrier → carrier) attribute Canonical.carrier [irreducible] constants (A : Type.{1}) (f : A → A) (x : A) definition A_canonical : Canonical := Canonical.mk A f #unify (Canonical.carrier A_canonical), A definition Canonical_hint [unify] (C : Canonical) : unification_hint := unification_hint.mk (unification_constraint.mk (Canonical.carrier C) A) [unification_constraint.mk C A_canonical] -- TODO(dhs): we mark carrier as irreducible and prove A_canonical explicitly to work around the fact that -- the default_type_context does not recognize the elaborator metavariables as metavariables, -- and so cannot perform the assignment. #unify (Canonical.carrier A_canonical), A print [unify] end canonical print [unify] canonical
5ef2542c128205dac5d3176eae606b9d10c5b663
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Server/Snapshots.lean
c6e875d1f489adc3bd5f0ae800a5a3147308538b
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,331
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 | headerData : Environment → MessageLog → Options → SnapshotData | cmdData : Command.State → SnapshotData /-- What Lean knows about the world after the header and each command. -/ structure Snapshot := /- 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) (mpState : Parser.ModuleParserState) (data : SnapshotData) namespace Snapshot def endPos (s : Snapshot) : String.Pos := s.mpState.pos def env : Snapshot → Environment | ⟨_, _, SnapshotData.headerData env_ _ _⟩ => env_ | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState.env def msgLog : Snapshot → MessageLog | ⟨_, _, SnapshotData.headerData _ msgLog_ _⟩ => msgLog_ | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState.messages def toCmdState : Snapshot → Command.State | ⟨_, _, SnapshotData.headerData env msgLog opts⟩ => Command.mkState env msgLog opts | ⟨_, _, SnapshotData.cmdData cmdState⟩ => cmdState end Snapshot -- TODO(WN): fns here should probably take inputCtx and live -- in some SnapshotsM := ReaderT Context (EIO Empty) def compileHeader (contents : String) (opts : Options := {}) : IO Snapshot := do let inputCtx := Parser.mkInputContext contents "<input>"; emptyEnv ← mkEmptyEnvironment; let (headerStx, headerParserState, msgLog) := Parser.parseHeader emptyEnv inputCtx; (headerEnv, msgLog) ← Elab.processHeader headerStx msgLog inputCtx; pure { beginPos := 0, mpState := headerParserState, data := SnapshotData.headerData headerEnv msgLog opts } private def ioErrorFromEmpty (ex : Empty) : IO.Error := Empty.rec _ ex /-- 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 (cmdStx, cmdParserState, msgLog) := Parser.parseCommand snap.env inputCtx snap.mpState snap.msgLog; let cmdPos := cmdStx.getHeadInfo.get!.pos.get!; -- TODO(WN): always `some`? if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then pure $ Sum.inr msgLog else do cmdStateRef ← IO.mkRef { snap.toCmdState with messages := msgLog }; let cmdCtx : Elab.Command.Context := { cmdPos := snap.endPos, fileName := inputCtx.fileName, fileMap := inputCtx.fileMap }; adaptExcept ioErrorFromEmpty (Elab.Command.catchExceptions (Elab.Command.elabCommand cmdStx) cmdCtx cmdStateRef); postCmdState ← cmdStateRef.get; let postCmdSnap : Snapshot := { beginPos := cmdPos, mpState := cmdParserState, data := SnapshotData.cmdData postCmdState }; pure $ 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) : Snapshot → IO (List Snapshot × MessageLog) | snap => do cmdOut ← compileNextCmd contents snap; match cmdOut with | Sum.inl snap => do (snaps, msgLog) ← compileCmdsAfter snap; pure $ (snap :: snaps, msgLog) | Sum.inr msgLog => pure ([], msgLog) end Snapshots end Server end Lean
b269e2d94f0488de797cb0308a38e6fc52f0d73b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/monoid_algebra/basic.lean
9c3fb1b94437408b741395d67270a2a262f4769e
[ "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
58,641
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 G. Kudryashov, Scott Morrison -/ import algebra.big_operators.finsupp import linear_algebra.finsupp import algebra.non_unital_alg_hom /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In fact the construction of the "monoid algebra" makes sense when `G` is not even a monoid, but merely a magma, i.e., when `G` carries a multiplication which is not required to satisfy any conditions at all. In this case the construction yields a not-necessarily-unital, not-necessarily-associative algebra but it is still adjoint to the forgetful functor from such algebras to magmas, and we prove this as `monoid_algebra.lift_magma`. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) /-! ### Multiplicative monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k instance : has_coe_to_fun (monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace monoid_algebra variables {k G} section has_mul variables [semiring k] [has_mul G] /-- The product of `f g : monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x * y = a`. (Think of the group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], .. finsupp.add_comm_monoid } end has_mul section semigroup variables [semiring k] [semigroup G] instance : non_unital_semiring (monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. monoid_algebra.non_unital_non_assoc_semiring} end semigroup section has_one variables [semiring k] [has_one G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl end has_one section mul_one_class variables [semiring k] [mul_one_class G] instance : non_assoc_semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], ..monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : G →* R`, returns the additive homomorphism from `monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : G →* R) : monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g a := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : G →* R) : lift_nc (f : k →+ R) g 1 = 1 := by simp [one_def] lemma lift_nc_mul (f : k →+* R) (g : G →* R) (a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := begin conv_rhs { rw [← sum_single a, ← sum_single b] }, simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul, finsupp.mul_sum], refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)), simp [mul_assoc, (h_comm hy).left_comm] end end mul_one_class /-! #### Semiring structure -/ section semiring variables [semiring k] [monoid G] instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. monoid_algebra.non_unital_semiring, .. monoid_algebra.non_assoc_semiring } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G]: nontrivial (monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_comm_group (monoid_algebra k G) := finsupp.add_comm_group instance [ring k] [has_mul G] : non_unital_non_assoc_ring (monoid_algebra k G) := { .. monoid_algebra.add_comm_group, .. monoid_algebra.non_unital_non_assoc_semiring } instance [ring k] [monoid G] : ring (monoid_algebra k G) := { .. monoid_algebra.non_unital_non_assoc_ring, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (monoid_algebra k G) := finsupp.has_scalar instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (monoid_algebra k G) := finsupp.distrib_mul_action G k instance [semiring R] [semiring k] [module R k] : module R (monoid_algebra k G) := finsupp.module G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (monoid_algebra k G) := finsupp.has_faithful_scalar instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (monoid_algebra k G) := finsupp.smul_comm_class G k instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k] [is_central_scalar R k] : is_central_scalar R (monoid_algebra k G) := finsupp.is_central_scalar G k instance comap_distrib_mul_action_self [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self end derived_instances section misc_theorems variables [semiring k] local attribute [reducible] monoid_algebra lemma mul_apply [has_mul G] (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal [has_mul G] (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end lemma support_mul [has_mul G] (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset @[simp] lemma single_mul_single [has_mul G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow [monoid G] {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := by { simp only [pow_zero], refl } | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_mul α] [has_mul α₂] {x y : monoid_algebra β α} (f : mul_hom α α₂) : (map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) = (map_domain f x * map_domain f y : monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_mul], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end variables (k G) /-- The embedding of a magma into its magma algebra. -/ @[simps] def of_magma [has_mul G] : mul_hom G (monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simp only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- The embedding of a unital magma into its magma algebra. -/ @[simps] def of [mul_one_class G] : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } end lemma of_injective [mul_one_class G] [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : by simp only [mul_apply, A, H] ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma support_mul_single [right_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r).support = f.support.map (mul_right_embedding x) := begin ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_right_embedding_apply], by_cases H : ∃ a, a * x = y, { rcases H with ⟨a, rfl⟩, rw [mul_single_apply_aux f (λ _, mul_left_inj x)], simp [hr] }, { push_neg at H, simp [mul_apply, H] } end lemma single_mul_apply_aux [has_mul G] (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by simp only [H] ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply [mul_one_class G] (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] lemma support_single_mul [left_cancel_semigroup G] (f : monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f).support = f.support.map (mul_left_embedding x) := begin ext y, simp only [mem_support_iff, mem_map, exists_prop, mul_left_embedding_apply], by_cases H : ∃ a, x * a = y, { rcases H with ⟨a, rfl⟩, rw [single_mul_apply_aux f (λ _, mul_right_inj x)], simp [hr] }, { push_neg at H, simp [mul_apply, H] } end lemma lift_nc_smul [mul_one_class G] {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := begin suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) = (add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g), from add_monoid_hom.congr_fun this φ, ext a b, simp [mul_assoc] end end misc_theorems /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_mul G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.smul_sum, smul_ite, smul_mul_assoc, sum_smul_index', zero_mul, if_t_t, implies_true_iff, eq_self_iff_true, sum_zero, coe_smul, smul_eq_mul, pi.smul_apply, smul_zero], end⟩ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (monoid_algebra k G) (monoid_algebra k G) := ⟨λ t a b, begin ext m, simp only [mul_apply, finsupp.sum, finset.smul_sum, smul_ite, mul_smul_comm, sum_smul_index', implies_true_iff, eq_self_iff_true, coe_smul, ite_eq_right_iff, smul_eq_mul, pi.smul_apply, mul_zero, smul_zero], end⟩ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (monoid_algebra k G) R (monoid_algebra k G) := ⟨λ t a b, by { haveI := smul_comm_class.symm k R k, rw ← smul_comm, } ⟩ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := non_unital_alg_hom.to_distrib_mul_action_hom_injective $ finsupp.distrib_mul_action_hom_ext' $ λ a, distrib_mul_action_hom.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := non_unital_alg_hom_ext k $ mul_hom.congr_fun h /-- The functor `G ↦ monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom G A ≃ non_unital_alg_hom k (monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, a.sum (λ m t, t • f m), map_smul' := λ t' a, begin rw [finsupp.smul_sum, sum_smul_index'], { simp_rw smul_assoc, }, { intros m, exact zero_smul k (f m), }, end, map_mul' := λ a₁ a₂, begin let g : G → k → A := λ m t, t • f m, have h₁ : ∀ m, g m 0 = 0, { intros, exact zero_smul k (f m), }, have h₂ : ∀ m (t₁ t₂ : k), g m (t₁ + t₂) = g m t₁ + g m t₂, { intros, rw ← add_smul, }, simp_rw [finsupp.mul_sum, finsupp.sum_mul, smul_mul_smul, ← f.map_mul, mul_def, sum_comm a₂ a₁, sum_sum_index h₁ h₂, sum_single_index (h₁ _)], end, .. lift_add_hom (λ x, (smul_add_hom k A).flip (f x)) }, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), left_inv := λ f, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, right_inv := λ F, by { ext m, simp only [non_unital_alg_hom.coe_mk, of_magma_apply, non_unital_alg_hom.to_mul_hom_eq_coe, sum_single_index, function.comp_app, one_smul, zero_smul, mul_hom.coe_comp, non_unital_alg_hom.coe_to_mul_hom], }, } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra local attribute [reducible] monoid_algebra lemma single_one_comm [comm_semiring k] [mul_one_class G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- `finsupp.single 1` as a `ring_hom` -/ @[simps] def single_one_ring_hom [semiring k] [monoid G] : k →+* monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul], ..finsupp.single_add_hom 1} /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b, by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom, g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of] /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom) (h_of : (f : monoid_algebra k G →* R).comp (of k G) = (g : monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..single_one_ring_hom.comp (algebra_map k A) } /-- `finsupp.single 1` as a `alg_hom` -/ @[simps] def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : A →ₐ[k] monoid_algebra A G := { commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom} @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = algebra_map k (monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a := by simp lemma induction_on [semiring k] [monoid G] {p : monoid_algebra k G → Prop} (f : monoid_algebra k G) (hM : ∀ g, p (of k G g)) (hadd : ∀ f g : monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G 1) (hM 1) }, { convert hsmul r (of k G g) (hM g), simp only [mul_one, smul_single', of_apply] }, end end algebra section lift variables {k G} [comm_semiring k] [monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := alg_hom.to_linear_map_injective $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : monoid_algebra k G →* A).comp (of k G) = (φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] }, right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } } variables {k G A} lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } end lift section local attribute [reducible] monoid_algebra variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : V →ₗ[k] V := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, smul_algebra_smul_comm _ _ _ } @[simp] lemma group_smul.linear_map_apply [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [monoid G] [comm_semiring k] {V W : Type u₃} [add_comm_monoid V] [module k V] [module (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [module k W] [module (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : V →ₗ[k] W) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, dsimp at *, simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul], erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r, f.map_smul, h g v, of_apply], all_goals { apply_instance } } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end section universe ui variable {ι : Type ui} local attribute [reducible] monoid_algebra lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] end section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] local attribute [reducible] monoid_algebra @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end section span variables [semiring k] [mul_one_class G] /-- An element of `monoid_algebra R M` is in the subalgebra generated by its support. -/ lemma mem_span_support (f : monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span section opposite open finsupp mul_opposite variables [semiring k] /-- The opposite of an `monoid_algebra R I` equivalent as a ring to the `monoid_algebra Rᵐᵒᵖ Iᵐᵒᵖ` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [monoid G] : (monoid_algebra k G)ᵐᵒᵖ ≃+* monoid_algebra kᵐᵒᵖ Gᵐᵒᵖ := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i₁ r₁ i₂ r₂ : 6, simp end, ..op_add_equiv.symm.trans $ (finsupp.map_range.add_equiv (op_add_equiv : k ≃+ kᵐᵒᵖ)).trans $ finsupp.dom_congr op_equiv } @[simp] lemma op_ring_equiv_single [monoid G] (r : k) (x : G) : monoid_algebra.op_ring_equiv (op (single x r)) = single (op x) (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) : monoid_algebra.op_ring_equiv.symm (single x r) = op (single x.unop r.unop) := by simp end opposite end monoid_algebra /-! ### Additive monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid]] def add_monoid_algebra := G →₀ k instance : has_coe_to_fun (add_monoid_algebra k G) (λ _, G → k) := finsupp.has_coe_to_fun end namespace add_monoid_algebra variables {k G} section has_mul variables [semiring k] [has_add G] /-- The product of `f g : add_monoid_algebra k G` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl instance : non_unital_non_assoc_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_zero], nsmul := λ n f, n • f, nsmul_zero' := by { intros, ext, simp [-nsmul_eq_mul, add_smul] }, nsmul_succ' := by { intros, ext, simp [-nsmul_eq_mul, nat.succ_eq_one_add, add_smul] }, .. finsupp.add_comm_monoid } end has_mul section has_one variables [semiring k] [has_zero G] /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl end has_one section semigroup variables [semiring k] [add_semigroup G] instance : non_unital_semiring (add_monoid_algebra k G) := { zero := 0, mul := (*), add := (+), mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], .. add_monoid_algebra.non_unital_non_assoc_semiring } end semigroup section mul_one_class variables [semiring k] [add_zero_class G] instance : non_assoc_semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], .. add_monoid_algebra.non_unital_non_assoc_semiring } variables {R : Type*} [semiring R] /-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : multiplicative G →* R`, returns the additive homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `add_monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : multiplicative G →* R) : add_monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g (multiplicative.of_add a) := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : multiplicative G →* R) : lift_nc (f : k →+ R) g 1 = 1 := @monoid_algebra.lift_nc_one k (multiplicative G) _ _ _ _ f g lemma lift_nc_mul (f : k →+* R) (g : multiplicative G →* R) (a b : add_monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := @monoid_algebra.lift_nc_mul k (multiplicative G) _ _ _ _ f g a b @h_comm end mul_one_class /-! #### Semiring structure -/ section semiring instance {R : Type*} [monoid R] [semiring k] [distrib_mul_action R k] : has_scalar R (add_monoid_algebra k G) := finsupp.has_scalar variables [semiring k] [add_monoid G] instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), .. add_monoid_algebra.non_unital_semiring, .. add_monoid_algebra.non_assoc_semiring, } variables {R : Type*} [semiring R] /-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _, .. add_monoid_algebra.semiring } instance [semiring k] [nontrivial k] [nonempty G] : nontrivial (add_monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_comm_group (add_monoid_algebra k G) := finsupp.add_comm_group instance [ring k] [has_add G] : non_unital_non_assoc_ring (add_monoid_algebra k G) := { .. add_monoid_algebra.add_comm_group, .. add_monoid_algebra.non_unital_non_assoc_semiring } instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { .. add_monoid_algebra.non_unital_non_assoc_ring, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} variables {R S : Type*} instance [monoid R] [semiring k] [distrib_mul_action R k] : distrib_mul_action R (add_monoid_algebra k G) := finsupp.distrib_mul_action G k instance [monoid R] [semiring k] [distrib_mul_action R k] [has_faithful_scalar R k] [nonempty G] : has_faithful_scalar R (add_monoid_algebra k G) := finsupp.has_faithful_scalar instance [semiring R] [semiring k] [module R k] : module R (add_monoid_algebra k G) := finsupp.module G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [has_scalar R S] [is_scalar_tower R S k] : is_scalar_tower R S (add_monoid_algebra k G) := finsupp.is_scalar_tower G k instance [monoid R] [monoid S] [semiring k] [distrib_mul_action R k] [distrib_mul_action S k] [smul_comm_class R S k] : smul_comm_class R S (add_monoid_algebra k G) := finsupp.smul_comm_class G k instance [monoid R] [semiring k] [distrib_mul_action R k] [distrib_mul_action Rᵐᵒᵖ k] [is_central_scalar R k] : is_central_scalar R (add_monoid_algebra k G) := finsupp.is_central_scalar G k /-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)` because we've never discussed actions of additive groups. -/ end derived_instances section misc_theorems variables [semiring k] lemma mul_apply [has_add G] (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := @monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ lemma mul_apply_antidiagonal [has_add G] (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := @monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs lemma support_mul [has_add G] (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ lemma single_mul_single [has_add G] {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ * single a₂ b₂ : add_monoid_algebra k G) = single (a₁ + a₂) (b₁ * b₂) := @monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _ -- This should be a `@[simp]` lemma, but the simp_nf linter times out if we add this. -- Probably the correct fix is to make a `[add_]monoid_algebra.single` with the correct type, -- instead of relying on `finsupp.single`. lemma single_pow [add_monoid G] {a : G} {b : k} : ∀ n : ℕ, ((single a b)^n : add_monoid_algebra k G) = single (n • a) (b ^ n) | 0 := by { simp only [pow_zero, zero_nsmul], refl } | (n+1) := by rw [pow_succ, pow_succ, single_pow n, single_mul_single, add_comm, add_nsmul, one_nsmul] /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [has_add α] [has_add α₂] {x y : add_monoid_algebra β α} (f : add_hom α α₂) : (map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (map_domain f x * map_domain f y : add_monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_add], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end section variables (k G) /-- The embedding of an additive magma into its additive magma algebra. -/ @[simps] def of_magma [has_add G] : mul_hom (multiplicative G) (add_monoid_algebra k G) := { to_fun := λ a, single a 1, map_mul' := λ a b, by simpa only [mul_def, mul_one, sum_single_index, single_eq_zero, mul_zero], } /-- Embedding of a magma with zero into its magma algebra. -/ def of [add_zero_class G] : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, .. of_magma k G } /-- Embedding of a magma with zero `G`, into its magma algebra, having `G` as source. -/ def of' : G → add_monoid_algebra k G := λ a, single a 1 end @[simp] lemma of_apply [add_zero_class G] (a : multiplicative G) : of k G a = single a.to_add 1 := rfl @[simp] lemma of'_apply (a : G) : of' k G a = single a 1 := rfl lemma of'_eq_of [add_zero_class G] (a : G) : of' k G a = of k G a := rfl lemma of_injective [nontrivial k] [add_zero_class G] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := @monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma mul_single_zero_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux [has_add G] (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f : add_monoid_algebra k G) y = r * f z := @monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma single_zero_mul_apply [add_zero_class G] (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f : add_monoid_algebra k G) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] lemma mul_single_apply [add_group G] (f : add_monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y - x) * r := (sub_eq_add_neg y x).symm ▸ @monoid_algebra.mul_single_apply k (multiplicative G) _ _ _ _ _ _ lemma single_mul_apply [add_group G] (r : k) (x : G) (f : add_monoid_algebra k G) (y : G) : (single x r * f : add_monoid_algebra k G) y = r * f (- x + y) := @monoid_algebra.single_mul_apply k (multiplicative G) _ _ _ _ _ _ lemma support_mul_single [add_right_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, y * r = 0 ↔ y = 0) (x : G) : (f * single x r : add_monoid_algebra k G).support = f.support.map (add_right_embedding x) := @monoid_algebra.support_mul_single k (multiplicative G) _ _ _ _ hr _ lemma support_single_mul [add_left_cancel_semigroup G] (f : add_monoid_algebra k G) (r : k) (hr : ∀ y, r * y = 0 ↔ y = 0) (x : G) : (single x r * f : add_monoid_algebra k G).support = f.support.map (add_left_embedding x) := @monoid_algebra.support_single_mul k (multiplicative G) _ _ _ _ hr _ lemma lift_nc_smul {R : Type*} [add_zero_class G] [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := @monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ variables {k G} lemma induction_on [add_monoid G] {p : add_monoid_algebra k G → Prop} (f : add_monoid_algebra k G) (hM : ∀ g, p (of k G (multiplicative.of_add g))) (hadd : ∀ f g : add_monoid_algebra k G, p f → p g → p (f + g)) (hsmul : ∀ (r : k) f, p f → p (r • f)) : p f := begin refine finsupp.induction_linear f _ (λ f g hf hg, hadd f g hf hg) (λ g r, _), { simpa using hsmul 0 (of k G (multiplicative.of_add 0)) (hM 0) }, { convert hsmul r (of k G (multiplicative.of_add g)) (hM g), simp only [mul_one, to_add_of_add, smul_single', of_apply] }, end end misc_theorems section span variables [semiring k] /-- An element of `add_monoid_algebra R M` is in the submodule generated by its support. -/ lemma mem_span_support [add_zero_class G] (f : add_monoid_algebra k G) : f ∈ submodule.span k (of k G '' (f.support : set G)) := by rw [of, monoid_hom.coe_mk, ← finsupp.supported_eq_span_single, finsupp.mem_supported] /-- An element of `add_monoid_algebra R M` is in the subalgebra generated by its support, using unbundled inclusion. -/ lemma mem_span_support' (f : add_monoid_algebra k G) : f ∈ submodule.span k (of' k G '' (f.support : set G)) := by rw [of', ← finsupp.supported_eq_span_single, finsupp.mem_supported] end span end add_monoid_algebra /-! #### Conversions between `add_monoid_algebra` and `monoid_algebra` We have not defined `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` because historically this caused problems; since the changes that have made `nsmul` definitional, this would be possible, but for now we just contruct the ring isomorphisms using `ring_equiv.refl _`. -/ /-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative` -/ protected def add_monoid_algebra.to_multiplicative [semiring k] [has_add G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) := { to_fun := equiv_map_domain multiplicative.of_add, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [multiplicative.of_add], convert monoid_algebra.map_domain_mul (mul_hom.id (multiplicative G)), end, ..finsupp.dom_congr multiplicative.of_add } /-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/ protected def monoid_algebra.to_additive [semiring k] [has_mul G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) := { to_fun := equiv_map_domain additive.of_mul, map_mul' := λ x y, begin repeat {rw equiv_map_domain_eq_map_domain}, dsimp [additive.of_mul], convert monoid_algebra.map_domain_mul (mul_hom.id G), end, ..finsupp.dom_congr additive.of_mul } namespace add_monoid_algebra variables {k G} /-! #### Non-unital, non-associative algebra structure -/ section non_unital_non_assoc_algebra variables {R : Type*} (k) [monoid R] [semiring k] [distrib_mul_action R k] [has_add G] instance is_scalar_tower_self [is_scalar_tower R k k] : is_scalar_tower R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.is_scalar_tower_self k (multiplicative G) R _ _ _ _ _ /-- Note that if `k` is a `comm_semiring` then we have `smul_comm_class k k k` and so we can take `R = k` in the below. In other words, if the coefficients are commutative amongst themselves, they also commute with the algebra multiplication. -/ instance smul_comm_class_self [smul_comm_class R k k] : smul_comm_class R (add_monoid_algebra k G) (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_self k (multiplicative G) R _ _ _ _ _ instance smul_comm_class_symm_self [smul_comm_class k R k] : smul_comm_class (add_monoid_algebra k G) R (add_monoid_algebra k G) := @monoid_algebra.smul_comm_class_symm_self k (multiplicative G) R _ _ _ _ _ variables {A : Type u₃} [non_unital_non_assoc_semiring A] /-- A non_unital `k`-algebra homomorphism from `add_monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma non_unital_alg_hom_ext [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma non_unital_alg_hom_ext' [distrib_mul_action k A] {φ₁ φ₂ : non_unital_alg_hom k (add_monoid_algebra k G) A} (h : φ₁.to_mul_hom.comp (of_magma k G) = φ₂.to_mul_hom.comp (of_magma k G)) : φ₁ = φ₂ := @monoid_algebra.non_unital_alg_hom_ext' k (multiplicative G) _ _ _ _ _ φ₁ φ₂ h /-- The functor `G ↦ add_monoid_algebra k G`, from the category of magmas to the category of non-unital, non-associative algebras over `k` is adjoint to the forgetful functor in the other direction. -/ @[simps] def lift_magma [module k A] [is_scalar_tower k A A] [smul_comm_class k A A] : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k (add_monoid_algebra k G) A := { to_fun := λ f, { to_fun := λ a, sum a (λ m t, t • f (multiplicative.of_add m)), .. (monoid_algebra.lift_magma k f : _)}, inv_fun := λ F, F.to_mul_hom.comp (of_magma k G), .. (monoid_algebra.lift_magma k : mul_hom (multiplicative G) A ≃ non_unital_alg_hom k _ A) } end non_unital_non_assoc_algebra /-! #### Algebra structure -/ section algebra variables {R : Type*} local attribute [reducible] add_monoid_algebra /-- `finsupp.single 0` as a `ring_hom` -/ @[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add], ..finsupp.single_add_hom 0} /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := @monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom) (h_of : (f : add_monoid_algebra k G →* R).comp (of k G) = (g : add_monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) section opposite open finsupp mul_opposite variables [semiring k] /-- The opposite of an `add_monoid_algebra R I` is ring equivalent to the `add_monoid_algebra Rᵐᵒᵖ I` over the opposite ring, taking elements to their opposite. -/ @[simps {simp_rhs := tt}] protected noncomputable def op_ring_equiv [add_comm_monoid G] : (add_monoid_algebra k G)ᵐᵒᵖ ≃+* add_monoid_algebra kᵐᵒᵖ G := { map_mul' := begin dsimp only [add_equiv.to_fun_eq_coe, ←add_equiv.coe_to_add_monoid_hom], rw add_monoid_hom.map_mul_iff, ext i r i' r' : 6, dsimp, simp only [map_range_single, single_mul_single, ←op_mul, add_comm] end, ..mul_opposite.op_add_equiv.symm.trans (finsupp.map_range.add_equiv (mul_opposite.op_add_equiv : k ≃+ kᵐᵒᵖ))} @[simp] lemma op_ring_equiv_single [add_comm_monoid G] (r : k) (x : G) : add_monoid_algebra.op_ring_equiv (op (single x r)) = single x (op r) := by simp @[simp] lemma op_ring_equiv_symm_single [add_comm_monoid G] (r : kᵐᵒᵖ) (x : Gᵐᵒᵖ) : add_monoid_algebra.op_ring_equiv.symm (single x r) = op (single x r.unop) := by simp end opposite /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def, pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..single_zero_ring_hom.comp (algebra_map R k) } /-- `finsupp.single 0` as a `alg_hom` -/ @[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : k →ₐ[R] add_monoid_algebra k G := { commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom} @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl end algebra section lift variables {k G} [comm_semiring k] [add_monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) = (φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F}, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ } variables {k G A} lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : multiplicative G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) : (lift k G A).symm F x = F (single x.to_add 1) := rfl lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : multiplicative G →* A) (a b) : lift k G A F (single a b) = b • F (multiplicative.of_add a) := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ end lift section local attribute [reducible] add_monoid_algebra universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end end add_monoid_algebra variables {R : Type*} [comm_semiring R] (k G) /-- The algebra equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative`. -/ def add_monoid_algebra.to_multiplicative_alg_equiv [semiring k] [algebra R k] [add_monoid G] : add_monoid_algebra k G ≃ₐ[R] monoid_algebra k (multiplicative G) := { commutes' := λ r, by simp [add_monoid_algebra.to_multiplicative], ..add_monoid_algebra.to_multiplicative k G } /-- The algebra equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive`. -/ def monoid_algebra.to_additive_alg_equiv [semiring k] [algebra R k] [monoid G] : monoid_algebra k G ≃ₐ[R] add_monoid_algebra k (additive G) := { commutes' := λ r, by simp [monoid_algebra.to_additive], ..monoid_algebra.to_additive k G }
58fa5bb8e88dd3d04f7b0d5e1709793edb61f6b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/adjoin.lean
24cc89792d68f277ea926484a0e15cc231485f9b
[ "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
46,289
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.separable import field_theory.splitting_field.is_splitting_field import ring_theory.tensor_product /-! # Adjoining Elements to Fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_rank_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical polynomial namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ s hs, (adjoin F s).copy s $ le_antisymm (gc.le_u_l s) hs, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_rfl, choice_eq := λ _ _, copy_eq _ _ _ } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma coe_bot : ↑(⊥ : intermediate_field F E) = set.range (algebra_map F E) := begin change ↑(subfield.closure (set.range (algebra_map F E) ∪ ∅)) = set.range (algebra_map F E), simp [←set.image_univ, ←ring_hom.map_field_closure] end lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := set.ext_iff.mp coe_bot x @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma coe_top : ↑(⊤ : intermediate_field F E) = (set.univ : set E) := rfl @[simp] lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := trivial @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := rfl @[simp] lemma top_to_subfield : (⊤ : intermediate_field F E).to_subfield = ⊤ := rfl @[simp, norm_cast] lemma coe_inf (S T : intermediate_field F E) : (↑(S ⊓ T) : set E) = S ∩ T := rfl @[simp] lemma mem_inf {S T : intermediate_field F E} {x : E} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl @[simp] lemma inf_to_subalgebra (S T : intermediate_field F E) : (S ⊓ T).to_subalgebra = S.to_subalgebra ⊓ T.to_subalgebra := rfl @[simp] lemma inf_to_subfield (S T : intermediate_field F E) : (S ⊓ T).to_subfield = S.to_subfield ⊓ T.to_subfield := rfl @[simp, norm_cast] lemma coe_Inf (S : set (intermediate_field F E)) : (↑(Inf S) : set E) = Inf (coe '' S) := rfl @[simp] lemma Inf_to_subalgebra (S : set (intermediate_field F E)) : (Inf S).to_subalgebra = Inf (to_subalgebra '' S) := set_like.coe_injective $ by simp [set.sUnion_image] @[simp] lemma Inf_to_subfield (S : set (intermediate_field F E)) : (Inf S).to_subfield = Inf (to_subfield '' S) := set_like.coe_injective $ by simp [set.sUnion_image] @[simp, norm_cast] lemma coe_infi {ι : Sort*} (S : ι → intermediate_field F E) : (↑(infi S) : set E) = ⋂ i, (S i) := by simp [infi] @[simp] lemma infi_to_subalgebra {ι : Sort*} (S : ι → intermediate_field F E) : (infi S).to_subalgebra = ⨅ i, (S i).to_subalgebra := set_like.coe_injective $ by simp [infi] @[simp] lemma infi_to_subfield {ι : Sort*} (S : ι → intermediate_field F E) : (infi S).to_subfield = ⨅ i, (S i).to_subfield := set_like.coe_injective $ by simp [infi] /-- Construct an algebra isomorphism from an equality of intermediate fields -/ @[simps apply] def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy @[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) : (equiv_of_eq h).symm = equiv_of_eq h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) : equiv_of_eq (rfl : S = S) = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) : (equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) := rfl variables (F E) /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E) variables {F E} @[simp] lemma bot_equiv_def (x : F) : bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes (bot_equiv F E) x @[simp] lemma bot_equiv_symm (x : F) : (bot_equiv F E).symm x = algebra_map F _ x := rfl noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := (intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra lemma coe_algebra_map_over_bot : (algebra_map (⊥ : intermediate_field F E) F : (⊥ : intermediate_field F E) → F) = (intermediate_field.bot_equiv F E) := rfl instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, obtain ⟨y, rfl⟩ := (bot_equiv F E).symm.surjective x, rw [coe_algebra_map_over_bot, (bot_equiv F E).apply_symm_apply, bot_equiv_symm, is_scalar_tower.algebra_map_apply F (⊥ : intermediate_field F E) E] end /-- The top intermediate_field is isomorphic to the field. This is the intermediate field version of `subalgebra.top_equiv`. -/ @[simps apply] def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans subalgebra.top_equiv @[simp] lemma top_equiv_symm_apply_coe (a : E) : ↑((top_equiv.symm) a : (⊤ : intermediate_field F E)) = a := rfl @[simp] lemma restrict_scalars_bot_eq_self (K : intermediate_field F E) : (⊥ : intermediate_field K E).restrict_scalars _ = K := by { ext, rw [mem_restrict_scalars, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma restrict_scalars_top {K : Type*} [field K] [algebra K E] [algebra K F] [is_scalar_tower K F E] : (⊤ : intermediate_field F E).restrict_scalars K = ⊤ := rfl lemma _root_.alg_hom.field_range_eq_map {K : Type*} [field K] [algebra F K] (f : E →ₐ[F] K) : f.field_range = intermediate_field.map f ⊤ := set_like.ext' set.image_univ.symm lemma _root_.alg_hom.map_field_range {K L : Type*} [field K] [field L] [algebra F K] [algebra F L] (f : E →ₐ[F] K) (g : K →ₐ[F] L) : f.field_range.map g = (g.comp f).field_range := set_like.ext' (set.range_comp g f).symm lemma _root_.alg_hom.field_range_eq_top {K : Type*} [field K] [algebra F K] {f : E →ₐ[F] K} : f.field_range = ⊤ ↔ function.surjective f := set_like.ext'_iff.trans set.range_iff_surjective @[simp] lemma _root_.alg_equiv.field_range_eq_top {K : Type*} [field K] [algebra F K] (f : E ≃ₐ[F] K) : (f : E →ₐ[F] K).field_range = ⊤ := alg_hom.field_range_eq_top.mpr f.surjective end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) @[simp] lemma adjoin_univ (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (set.univ : set E) = ⊤ := eq_top_iff.mpr $ subset_adjoin _ _ /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : (adjoin (adjoin F S) T).restrict_scalars _ = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : (adjoin (adjoin F S) T).restrict_scalars F = (adjoin (adjoin F T) S).restrict_scalars F := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, has_insert.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl @[simp] lemma adjoin_simple.is_integral_gen : is_integral F (adjoin_simple.gen F α) ↔ is_integral F α := by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α }, rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective, apply_instance } lemma adjoin_simple_adjoin_simple (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : F⟮α⟯⟮β⟯.restrict_scalars F = F⟮β⟯⟮α⟯.restrict_scalars F := adjoin_adjoin_comm _ _ _ variables {F} {α} lemma adjoin_algebraic_to_subalgebra {S : set E} (hS : ∀ x ∈ S, is_algebraic F x) : (intermediate_field.adjoin F S).to_subalgebra = algebra.adjoin F S := begin simp only [is_algebraic_iff_is_integral] at hS, have : algebra.is_integral F (algebra.adjoin F S) := by rwa [←le_integral_closure_iff_is_integral, algebra.adjoin_le_iff], have := is_field_of_is_integral_of_is_field' this (field.to_is_field F), rw ← ((algebra.adjoin F S).to_intermediate_field' this).eq_adjoin_of_eq_algebra_adjoin F S; refl, end lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_algebraic_to_subalgebra, rintro x (rfl : x = α), rwa is_algebraic_iff_is_integral, end lemma is_splitting_field_iff {p : F[X]} {K : intermediate_field F E} : p.is_splitting_field F K ↔ p.splits (algebra_map F K) ∧ K = adjoin F (p.root_set E) := begin suffices : _ → ((algebra.adjoin F (p.root_set K) = ⊤ ↔ K = adjoin F (p.root_set E))), { exact ⟨λ h, ⟨h.1, (this h.1).mp h.2⟩, λ h, ⟨h.1, (this h.1).mpr h.2⟩⟩ }, simp_rw [set_like.ext_iff, ←mem_to_subalgebra, ←set_like.ext_iff], rw [←K.range_val, adjoin_algebraic_to_subalgebra (λ x, is_algebraic_of_mem_root_set)], exact λ hp, (adjoin_root_set_eq_range hp K.val).symm.trans eq_comm, end lemma adjoin_root_set_is_splitting_field {p : F[X]} (hp : p.splits (algebra_map F E)) : p.is_splitting_field F (adjoin F (p.root_set E)) := is_splitting_field_iff.mpr ⟨splits_of_splits hp (λ x hx, subset_adjoin F (p.root_set E) hx), rfl⟩ open_locale big_operators /-- A compositum of splitting fields is a splitting field -/ lemma is_splitting_field_supr {ι : Type*} {t : ι → intermediate_field F E} {p : ι → F[X]} {s : finset ι} (h0 : ∏ i in s, p i ≠ 0) (h : ∀ i ∈ s, (p i).is_splitting_field F (t i)) : (∏ i in s, p i).is_splitting_field F (⨆ i ∈ s, t i : intermediate_field F E) := begin let K : intermediate_field F E := ⨆ i ∈ s, t i, have hK : ∀ i ∈ s, t i ≤ K := λ i hi, le_supr_of_le i (le_supr (λ _, t i) hi), simp only [is_splitting_field_iff] at h ⊢, refine ⟨splits_prod (algebra_map F K) (λ i hi, polynomial.splits_comp_of_splits (algebra_map F (t i)) (inclusion (hK i hi)).to_ring_hom (h i hi).1), _⟩, simp only [root_set_prod p s h0, ←set.supr_eq_Union, (@gc F _ E _ _).l_supr₂], exact supr_congr (λ i, supr_congr (λ hi, (h i hi).2)), end open set complete_lattice @[simp] lemma adjoin_simple_le_iff {K : intermediate_field F E} : F⟮α⟯ ≤ K ↔ α ∈ K := adjoin_le_iff.trans singleton_subset_iff /-- Adjoining a single element is compact in the lattice of intermediate fields. -/ lemma adjoin_simple_is_compact_element (x : E) : is_compact_element F⟮x⟯ := begin rw is_compact_element_iff_le_of_directed_Sup_le, rintros s ⟨F₀, hF₀⟩ hs hx, simp only [adjoin_simple_le_iff] at hx ⊢, let F : intermediate_field F E := { carrier := ⋃ E ∈ s, ↑E, add_mem' := by { rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩, obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂, exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.add_mem (h₁₃ hx₁) (h₂₃ hx₂))) }, neg_mem' := by { rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩, exact mem_Union_of_mem E (mem_Union_of_mem hE (E.neg_mem hx)) }, mul_mem' := by { rintros x₁ x₂ ⟨-, ⟨F₁, rfl⟩, ⟨-, ⟨hF₁, rfl⟩, hx₁⟩⟩ ⟨-, ⟨F₂, rfl⟩, ⟨-, ⟨hF₂, rfl⟩, hx₂⟩⟩, obtain ⟨F₃, hF₃, h₁₃, h₂₃⟩ := hs F₁ hF₁ F₂ hF₂, exact mem_Union_of_mem F₃ (mem_Union_of_mem hF₃ (F₃.mul_mem (h₁₃ hx₁) (h₂₃ hx₂))) }, inv_mem' := by { rintros x ⟨-, ⟨E, rfl⟩, ⟨-, ⟨hE, rfl⟩, hx⟩⟩, exact mem_Union_of_mem E (mem_Union_of_mem hE (E.inv_mem hx)) }, algebra_map_mem' := λ x, mem_Union_of_mem F₀ (mem_Union_of_mem hF₀ (F₀.algebra_map_mem x)) }, have key : Sup s ≤ F := Sup_le (λ E hE, subset_Union_of_subset E (subset_Union _ hE)), obtain ⟨-, ⟨E, rfl⟩, -, ⟨hE, rfl⟩, hx⟩ := key hx, exact ⟨E, hE, hx⟩, end /-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/ lemma adjoin_finset_is_compact_element (S : finset E) : is_compact_element (adjoin F S : intermediate_field F E) := begin have key : adjoin F ↑S = ⨆ x ∈ S, F⟮x⟯ := le_antisymm (adjoin_le_iff.mpr (λ x hx, set_like.mem_coe.mpr (adjoin_simple_le_iff.mp (le_supr_of_le x (le_supr_of_le hx le_rfl))))) (supr_le (λ x, supr_le (λ hx, adjoin_simple_le_iff.mpr (subset_adjoin F S hx)))), rw [key, ←finset.sup_eq_supr], exact finset_sup_compact_of_compact S (λ x hx, adjoin_simple_is_compact_element x), end /-- Adjoining a finite subset is compact in the lattice of intermediate fields. -/ lemma adjoin_finite_is_compact_element {S : set E} (h : S.finite) : is_compact_element (adjoin F S) := finite.coe_to_finset h ▸ (adjoin_finset_is_compact_element h.to_finset) /-- The lattice of intermediate fields is compactly generated. -/ instance : is_compactly_generated (intermediate_field F E) := ⟨λ s, ⟨(λ x, F⟮x⟯) '' s, ⟨by rintros t ⟨x, hx, rfl⟩; exact adjoin_simple_is_compact_element x, Sup_image.trans (le_antisymm (supr_le (λ i, supr_le (λ hi, adjoin_simple_le_iff.mpr hi))) (λ x hx, adjoin_simple_le_iff.mp (le_supr_of_le x (le_supr_of_le hx le_rfl))))⟩⟩⟩ lemma exists_finset_of_mem_supr {ι : Type*} {f : ι → intermediate_field F E} {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset ι, x ∈ ⨆ i ∈ s, f i := begin have := (adjoin_simple_is_compact_element x).exists_finset_of_le_supr (intermediate_field F E) f, simp only [adjoin_simple_le_iff] at this, exact this hx, end lemma exists_finset_of_mem_supr' {ι : Type*} {f : ι → intermediate_field F E} {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, F⟮(i.2 : E)⟯ := exists_finset_of_mem_supr (set_like.le_def.mp (supr_le (λ i x h, set_like.le_def.mp (le_supr_of_le ⟨i, x, h⟩ le_rfl) (mem_adjoin_simple_self F x))) hx) lemma exists_finset_of_mem_supr'' {ι : Type*} {f : ι → intermediate_field F E} (h : ∀ i, algebra.is_algebraic F (f i)) {x : E} (hx : x ∈ ⨆ i, f i) : ∃ s : finset (Σ i, f i), x ∈ ⨆ i ∈ s, adjoin F ((minpoly F (i.2 : _)).root_set E) := begin refine exists_finset_of_mem_supr (set_like.le_def.mp (supr_le (λ i x hx, set_like.le_def.mp (le_supr_of_le ⟨i, x, hx⟩ le_rfl) (subset_adjoin F _ _))) hx), rw [intermediate_field.minpoly_eq, subtype.coe_mk, mem_root_set_of_ne, minpoly.aeval], exact minpoly.ne_zero (is_integral_iff.mp (is_algebraic_iff_is_integral.mp (h i ⟨x, hx⟩))) end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_nat_mem ⊥ n) section adjoin_rank open finite_dimensional module variables {K L : intermediate_field F E} @[simp] lemma rank_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← rank_eq_rank_subalgebra, subalgebra.rank_eq_one_iff, bot_to_subalgebra] @[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra, subalgebra.finrank_eq_one_iff, bot_to_subalgebra] @[simp] lemma rank_bot : module.rank F (⊥ : intermediate_field F E) = 1 := by rw rank_eq_one_iff @[simp] lemma finrank_bot : finrank F (⊥ : intermediate_field F E) = 1 := by rw finrank_eq_one_iff lemma rank_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans rank_eq_one_iff adjoin_eq_bot_iff lemma rank_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw rank_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans finrank_eq_one_iff adjoin_eq_bot_iff lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_rank_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact rank_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact finrank_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_rank_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_rank_adjoin_eq_one h) lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_finrank_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos], end lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h) end adjoin_rank end adjoin_intermediate_field_lattice section adjoin_integral_element variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma minpoly_gen {α : E} (h : is_integral F α) : minpoly F (adjoin_simple.gen F α) = minpoly F α := begin rw ← adjoin_simple.algebra_map_gen F α at h, have inj := (algebra_map F⟮α⟯ E).injective, exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h) (adjoin_simple.algebra_map_gen _ _).symm end variables (F) lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact (aeval_algebra_map_apply E (adjoin_simple.gen F α) _).symm end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (adjoin_root.lift_hom (minpoly F α) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _), haveI := fact.mk (minpoly.irreducible h), split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := adjoin_root.lift_root (aeval_gen_minpoly F α) section power_basis variables {L : Type*} [field L] [algebra K L] /-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def power_basis_aux {x : L} (hx : is_integral K x) : basis (fin (minpoly K x).nat_degree) K K⟮x⟯ := (adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map (adjoin_root_equiv_adjoin K hx).to_linear_equiv /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ @[simps] noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, basis := power_basis_aux hx, basis_eq_pow := λ i, by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen, adjoin_root_equiv_adjoin_apply_root] } lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.finrank {x : L} (hx : is_integral K x) : finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.finrank (adjoin.power_basis hx : _), refl end lemma _root_.minpoly.nat_degree_le {x : L} [finite_dimensional K L] (hx : is_integral K x) : (minpoly K x).nat_degree ≤ finrank K L := le_of_eq_of_le (intermediate_field.adjoin.finrank hx).symm K⟮x⟯.to_submodule.finrank_le lemma _root_.minpoly.degree_le {x : L} [finite_dimensional K L] (hx : is_integral K x) : (minpoly K x).degree ≤ finrank K L := degree_le_of_nat_degree_le (minpoly.nat_degree_le hx) end power_basis /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := (adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply])) /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := power_basis.alg_hom.fintype (adjoin.power_basis h) lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := begin rw alg_hom.card_of_power_basis; simp only [adjoin.power_basis_dim, adjoin.power_basis_gen, minpoly_gen h, h_sep, h_splits], end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := iff.symm set.exists_finite_iff_finset theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P (K⟮x⟯.restrict_scalars F)) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F)) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P (K⟮x⟯.restrict_scalars F)) (K : intermediate_field F E) : P K := begin letI : is_noetherian F E := is_noetherian.iff_fg.2 infer_instance, exact induction_on_adjoin_fg P base ih K K.fg_of_noetherian end end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} instance : partial_order (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, obtain rfl : x1 = y1 := le_antisymm hxy1 hyx1, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end } noncomputable instance : order_bot (lifts F E K) := { bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : is_chain (≤) c) (hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c) : ∃ z : lifts F E K, z ∈ has_insert.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (hc.insert $ λ _ _ _, or.inl bot_le).total hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : is_chain (≤) c) (hx : x ∈ has_insert.insert ⊥ c) (hy : y ∈ has_insert.insert ⊥ c) (hz : z ∈ has_insert.insert ⊥ c) : ∃ w : lifts F E K, w ∈ has_insert.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : is_chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ has_insert.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : is_chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : is_chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : is_chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨x.1⟮s⟯.restrict_scalars F, (@alg_hom_equiv_sigma F x.1 (x.1⟮s⟯.restrict_scalars F) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits section supremum variables {K L : Type*} [field K] [field L] [algebra K L] (E1 E2 : intermediate_field K L) lemma le_sup_to_subalgebra : E1.to_subalgebra ⊔ E2.to_subalgebra ≤ (E1 ⊔ E2).to_subalgebra := sup_le (show E1 ≤ E1 ⊔ E2, from le_sup_left) (show E2 ≤ E1 ⊔ E2, from le_sup_right) lemma sup_to_subalgebra [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] : (E1 ⊔ E2).to_subalgebra = E1.to_subalgebra ⊔ E2.to_subalgebra := begin let S1 := E1.to_subalgebra, let S2 := E2.to_subalgebra, refine le_antisymm (show _ ≤ (S1 ⊔ S2).to_intermediate_field _, from (sup_le (show S1 ≤ _, from le_sup_left) (show S2 ≤ _, from le_sup_right))) (le_sup_to_subalgebra E1 E2), suffices : is_field ↥(S1 ⊔ S2), { intros x hx, by_cases hx' : (⟨x, hx⟩ : S1 ⊔ S2) = 0, { rw [←subtype.coe_mk x hx, hx', subalgebra.coe_zero, inv_zero], exact (S1 ⊔ S2).zero_mem }, { obtain ⟨y, h⟩ := this.mul_inv_cancel hx', exact (congr_arg (∈ S1 ⊔ S2) $ eq_inv_of_mul_eq_one_right $ subtype.ext_iff.mp h).mp y.2 } }, exact is_field_of_is_integral_of_is_field' (is_integral_sup.mpr ⟨algebra.is_integral_of_finite K E1, algebra.is_integral_of_finite K E2⟩) (field.to_is_field K), end instance finite_dimensional_sup [h1 : finite_dimensional K E1] [h2 : finite_dimensional K E2] : finite_dimensional K ↥(E1 ⊔ E2) := begin let g := algebra.tensor_product.product_map E1.val E2.val, suffices : g.range = (E1 ⊔ E2).to_subalgebra, { have h : finite_dimensional K g.range.to_submodule := g.to_linear_map.finite_dimensional_range, rwa this at h }, rw [algebra.tensor_product.product_map_range, E1.range_val, E2.range_val, sup_to_subalgebra], end instance finite_dimensional_supr_of_finite {ι : Type*} {t : ι → intermediate_field K L} [h : finite ι] [Π i, finite_dimensional K (t i)] : finite_dimensional K (⨆ i, t i : intermediate_field K L) := begin rw ← supr_univ, let P : set ι → Prop := λ s, finite_dimensional K (⨆ i ∈ s, t i : intermediate_field K L), change P set.univ, apply set.finite.induction_on, { exact set.finite_univ }, all_goals { dsimp only [P] }, { rw supr_emptyset, exact (bot_equiv K L).symm.to_linear_equiv.finite_dimensional }, { intros _ s _ _ hs, rw supr_insert, exactI intermediate_field.finite_dimensional_sup _ _ }, end instance finite_dimensional_supr_of_finset {ι : Type*} {f : ι → intermediate_field K L} {s : finset ι} [h : Π i ∈ s, finite_dimensional K (f i)] : finite_dimensional K (⨆ i ∈ s, f i : intermediate_field K L) := begin haveI : Π i : {i // i ∈ s}, finite_dimensional K (f i) := λ i, h i i.2, have : (⨆ i ∈ s, f i) = ⨆ i : {i // i ∈ s}, f i := le_antisymm (supr_le (λ i, supr_le (λ h, le_supr (λ i : {i // i ∈ s}, f i) ⟨i, h⟩))) (supr_le (λ i, le_supr_of_le i (le_supr_of_le i.2 le_rfl))), exact this.symm ▸ intermediate_field.finite_dimensional_supr_of_finite, end /-- A compositum of algebraic extensions is algebraic -/ lemma is_algebraic_supr {ι : Type*} {f : ι → intermediate_field K L} (h : ∀ i, algebra.is_algebraic K (f i)) : algebra.is_algebraic K (⨆ i, f i : intermediate_field K L) := begin rintros ⟨x, hx⟩, obtain ⟨s, hx⟩ := exists_finset_of_mem_supr' hx, rw [is_algebraic_iff, subtype.coe_mk, ←subtype.coe_mk x hx, ←is_algebraic_iff], haveI : ∀ i : (Σ i, f i), finite_dimensional K K⟮(i.2 : L)⟯ := λ ⟨i, x⟩, adjoin.finite_dimensional (is_integral_iff.1 (is_algebraic_iff_is_integral.1 (h i x))), apply algebra.is_algebraic_of_finite, end end supremum end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv_of_minpoly pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : K[X]) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_of_minpoly_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_of_minpoly_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : K[X]) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_aeval, adjoin.power_basis_gen] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_of_minpoly_symm, equiv_of_minpoly_gen, adjoin.power_basis_gen] end power_basis end power_basis
9d6d994e09997f1b9fb9ceb3a703034bea4890f5
2a2864136cf8f2871e86f5fd14e624e3daa8fd24
/Monads/Functor.lean
382a7fb4c31d101f6c3ec5fc5226c7b4436e4782
[ "MIT" ]
permissive
hargoniX/lean-monads
d054ac71a351b7c86f318a477977cc166117b8ec
2e87ca7ddf394641ea1b16bcbd8c384026d68e2f
refs/heads/main
1,693,530,528,286
1,633,100,386,000
1,633,100,386,000
412,509,769
1
0
null
null
null
null
UTF-8
Lean
false
false
2,069
lean
namespace Monads /- Functors capture the notion of a regular computation being executed on values that are within another type. This type usually captures either the notion of a container, such as a list, or a context for a computation, such as receiving data from IO.-/ class Functor (f : Type u → Type v) : Type (max (u+1) v) where fmap : (α → β) → f α → f β map_const : α → f β → f α := fmap ∘ (Function.const β) export Functor (fmap map_const) infixr:100 " <$> " => Monads.Functor.fmap infixr:90 " <$ " => Monads.Functor.map_const namespace Functor def const_map {α β : Type u} {f : Type u → Type v} [Functor f] : f β → α → f α := flip map_const infixr:90 " $> " => Monads.Functor.const_map def void {α : Type} {f : Type → Type} [Functor f] : f α → f Unit := map_const () end Functor /- LawfulFunctor ensures the Functor is in fact only applying the function to the values and not performing additional computation or modification See Maybe.lean for an example why we need both laws to hold for a sensible functor. -/ class LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where /- If the function maps values to themselves the values in the functor shall remain unchanged -/ fmap_id : ∀ (x : f α), id <$> x = x /- Applying two functions via fmap is the same as applying one composed function at once via fmap -/ fmap_comp : ∀ (g : α → β) (h : β → γ) (x : f α), (h ∘ g) <$> x = h <$> g <$> x /- If there is a custom map_const implementation it has to behave like the default one. -/ map_const_behaved: ∀ (x : α) (y : f β), x <$ y = (fmap ∘ (Function.const β)) x y namespace LawfulFunctor variable {f : Type u → Type v} [Functor f] [LawfulFunctor f] example {g : α → β} {x : f α} : g <$> (id <$> x) = g <$> x := by rw [fmap_id] example {g : α → β} {x : f α} : id <$> (g <$> x) = g <$> x := by rw [fmap_id] end LawfulFunctor end Monads
80245ffc16fa859c6c7cb5b06b12c2aa13219a76
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/int/gcd.lean
bf25fdddb0cc0445b947153c1f237c942827250d
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
5,134
lean
/- Copyright (c) 2018 Guy Leroy. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sangwoo Jo (aka Jason), Guy Leroy, Johannes Hölzl, Mario Carneiro -/ import data.nat.prime /-! # Extended GCD and divisibility over ℤ ## Main definitions * Given `x y : ℕ`, `xgcd x y` computes the pair of integers `(a, b)` such that `gcd x y = x * a + y * b`. `gcd_a x y` and `gcd_b x y` are defined to be `a` and `b`, respectively. ## Main statements * `gcd_eq_gcd_ab`: Bézout's lemma, given `x y : ℕ`, `gcd x y = x * gcd_a x y + y * gcd_b x y`. -/ /-! ### Extended Euclidean algorithm -/ namespace nat /-- Helper function for the extended GCD algorithm (`nat.xgcd`). -/ def xgcd_aux : ℕ → ℤ → ℤ → ℕ → ℤ → ℤ → ℕ × ℤ × ℤ | 0 s t r' s' t' := (r', s', t') | r@(succ _) s t r' s' t' := have r' % r < r, from mod_lt _ $ succ_pos _, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t @[simp] theorem xgcd_zero_left {s t r' s' t'} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by simp [xgcd_aux] @[simp] theorem xgcd_aux_rec {r s t r' s' t'} (h : 0 < r) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by cases r; [exact absurd h (lt_irrefl _), {simp only [xgcd_aux], refl}] /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : ℕ) : ℤ × ℤ := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : ℕ) : ℤ := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : ℕ) : ℤ := (xgcd x y).2 @[simp] theorem xgcd_aux_fst (x y) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by simp) (λ x y h IH s t s' t', by simp [h, IH]; rw ← gcd_rec) theorem xgcd_aux_val (x y) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1]; cases xgcd_aux x 1 0 y 0 1; refl theorem xgcd_val (x y) : xgcd x y = (gcd_a x y, gcd_b x y) := by unfold gcd_a gcd_b; cases xgcd x y; refl section parameters (x y : ℕ) private def P : ℕ × ℤ × ℤ → Prop | (r, s, t) := (r : ℤ) = x * s + y * t theorem xgcd_aux_P {r r'} : ∀ {s t s' t'}, P (r, s, t) → P (r', s', t') → P (xgcd_aux r s t r' s' t') := gcd.induction r r' (by simp) $ λ a b h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, dsimp [P] at *, rw [int.mod_def], generalize : (b / a : ℤ) = k, rw [p, p'], simp [mul_add, mul_comm, mul_left_comm, add_comm, add_left_comm, sub_eq_neg_add] end /-- Bézout's lemma: given `x y : ℕ`, `gcd x y = x * a + y * b`, where `a = gcd_a x y` and `b = gcd_b x y` are computed by the extended Euclidean algorithm. -/ theorem gcd_eq_gcd_ab : (gcd x y : ℤ) = x * gcd_a x y + y * gcd_b x y := by have := @xgcd_aux_P x y x y 1 0 0 1 (by simp [P]) (by simp [P]); rwa [xgcd_aux_val, xgcd_val] at this end end nat /-! ### Divisibility over ℤ -/ namespace int theorem nat_abs_div (a b : ℤ) (H : b ∣ a) : nat_abs (a / b) = (nat_abs a) / (nat_abs b) := begin cases (nat.eq_zero_or_pos (nat_abs b)), {rw eq_zero_of_nat_abs_eq_zero h, simp [int.div_zero]}, calc nat_abs (a / b) = nat_abs (a / b) * 1 : by rw mul_one ... = nat_abs (a / b) * (nat_abs b / nat_abs b) : by rw nat.div_self h ... = nat_abs (a / b) * nat_abs b / nat_abs b : by rw (nat.mul_div_assoc _ (dvd_refl _)) ... = nat_abs (a / b * b) / nat_abs b : by rw (nat_abs_mul (a / b) b) ... = nat_abs a / nat_abs b : by rw int.div_mul_cancel H, end theorem nat_abs_dvd_abs_iff {i j : ℤ} : i.nat_abs ∣ j.nat_abs ↔ i ∣ j := ⟨assume (H : i.nat_abs ∣ j.nat_abs), dvd_nat_abs.mp (nat_abs_dvd.mp (coe_nat_dvd.mpr H)), assume H : (i ∣ j), coe_nat_dvd.mp (dvd_nat_abs.mpr (nat_abs_dvd.mpr H))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) theorem dvd_of_mul_dvd_mul_left {i j k : ℤ} (k_non_zero : k ≠ 0) (H : k * i ∣ k * j) : i ∣ j := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left k_non_zero H1⟩) theorem dvd_of_mul_dvd_mul_right {i j k : ℤ} (k_non_zero : k ≠ 0) (H : i * k ∣ j * k) : i ∣ j := by rw [mul_comm i k, mul_comm j k] at H; exact dvd_of_mul_dvd_mul_left k_non_zero H end int
489f2ac0f853896cd1fb7a958cd2282e58c5e559
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/rel_tac1.lean
c562fd82e3e4a9bc67de1ce4dc826b8e80323581
[ "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
409
lean
open tactic example (a b : nat) : a = a := by reflexivity example (a : nat) (b : bool) : a == b → b == a := by do intros, symmetry, trace_state, assumption #print "-----------" example (a : nat) (b : bool) (c : string) : a == b → b == c → a == c := by do intro_lst [`H1, `H2], transitivity, trace_state, get_local `H1 >>= exact, assumption example (a b : bool) : a == a := by reflexivity
35ed89357c89af340eae816643e3b5be841cdec5
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/category/Module/subobject.lean
ddc4a791fc6a28d424509626333205c7923ce8cc
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,164
lean
/- Copyright (c) 2021 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Module.basic import category_theory.subobject.well_powered /-! # Subobjects in the category of `R`-modules We construct an explicit order isomorphism between the categorical subobjects of an `R`-module `M` and its submodules. This immediately implies that the category of `R`-modules is well-powered. -/ open category_theory open category_theory.subobject open_locale Module universes v u namespace Module variables {R : Type u} [ring R] (M : Module.{v} R) /-- The categorical subobjects of a module `M` are in one-to-one correspondence with its submodules.-/ noncomputable def subobject_Module : subobject M ≃o submodule R M := order_iso.symm ({ inv_fun := λ S, S.arrow.range, to_fun := λ N, subobject.mk ↾N.subtype, right_inv := λ S, eq.symm begin fapply eq_mk_of_comm, { apply linear_equiv.to_Module_iso'_left, apply linear_equiv.of_bijective (linear_map.cod_restrict S.arrow.range S.arrow _), { simpa only [linear_map.ker_cod_restrict] using ker_eq_bot_of_mono _ }, { rw [linear_map.range_cod_restrict, submodule.comap_subtype_self] }, { exact linear_map.mem_range_self _ } }, { ext, refl } end, left_inv := λ N, begin convert congr_arg linear_map.range (underlying_iso_arrow ↾N.subtype) using 1, { have : (underlying_iso ↾N.subtype).inv = (underlying_iso ↾N.subtype).symm.to_linear_equiv, { ext, refl }, rw [this, comp_def, linear_equiv.range_comp] }, { exact (submodule.range_subtype _).symm } end, map_rel_iff' := λ S T, begin refine ⟨λ h, _, λ h, mk_le_mk_of_comm ↟(submodule.of_le h) (by { ext, refl })⟩, convert linear_map.range_comp_le_range (of_mk_le_mk h) ↾T.subtype, { simpa only [←comp_def, of_mk_le_mk_comp] using (submodule.range_subtype _).symm }, { exact (submodule.range_subtype _).symm } end }) instance well_powered_Module : well_powered (Module.{v} R) := ⟨λ M, ⟨⟨_, ⟨(subobject_Module M).to_equiv⟩⟩⟩⟩ end Module
ee4af3a1ebbf225f3353c7b02e14b2ab023f7c42
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/metric_space/gromov_hausdorff_realized.lean
6ee112e853d03aa674ac2193df690723b0b254fb
[ "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
26,581
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 Construction of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces -/ import topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.continuous_function.bounded noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union α ⊕ β of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] @[reducible] private def prod_space_fun : Type* := ((α ⊕ β) × (α ⊕ β)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((α ⊕ β) × (α ⊕ β)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set α), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set β), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var α β := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on α ⊕ β that are candidates distances to realize the minimum of the Hausdorff distances between α and β in a coupling -/ def candidates : set (prod_space_fun α β) := {f | (((((∀x y : α, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀x y : β, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀x y, f (x, y) = f (y, x))) ∧ (∀x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀x, f (x, x) = 0)) ∧ (∀x y, f (x, y) ≤ max_var α β) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb α β) := {f : Cb α β | f.to_fun ∈ candidates α β} end definitions --section section constructions variables {α : Type u} {β : Type v} [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] {f : prod_space_fun α β} {x y z t : α ⊕ β} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var α β := calc dist x y ≤ diam (univ : set (α ⊕ β)) : dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set α) ∪ inr '' (univ : set β)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set α)) + dist (inl (default α)) (inr (default β)) + diam (inr '' (univ : set β)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set α) + (dist (default α) (default α) + 1 + dist (default β) (default β)) + diam (univ : set β) : by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl } ... = 1 * diam (univ : set α) + 1 + 1 * diam (univ : set β) : by simp ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates α β) : f (x, y) = f (y ,x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates α β) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates α β) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates α β) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates α β) (x y: α) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates α β) (x y : β) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates α β) : f (x, y) ≤ max_var α β := fA.2 x y /-- candidates are bounded by max_var α β -/ private lemma candidates_dist_bound (fA : f ∈ candidates α β) : ∀ {x y : α ⊕ β}, f (x, y) ≤ max_var α β * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var α β * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var α β : candidates_le_max_var fA ... = max_var α β * 1 : by simp ... ≤ max_var α β * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var α β)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq α β, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var α β * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var α β) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates α β) : f (x, y) - f (z, t) ≤ 2 * max_var α β * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var α β * dist x z + max_var α β * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var α β * max (dist x z) (dist t y) + max_var α β * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var α β)), end ... = 2 * max_var α β * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var α β * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates α β) : lipschitz_with (2 * max_var α β) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun α β) (fA : f ∈ candidates α β) : Cb α β := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun α β) (fA : f ∈ candidates α β) : candidates_b_of_candidates f fA ∈ candidates_b α β := fA /-- The distance on α ⊕ β is a candidate -/ private lemma dist_mem_candidates : (λp : (α ⊕ β) × (α ⊕ β), dist p.1 p.2) ∈ candidates α β := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end def candidates_b_dist (α : Type u) (β : Type v) [metric_space α] [compact_space α] [inhabited α] [metric_space β] [compact_space β] [inhabited β] : Cb α β := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist α β ∈ candidates_b α β := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b α β).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b α β) := begin have I1 : ∀x y, is_closed {f : Cb α β | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_evalx continuous_const, have I2 : ∀x y, is_closed {f : Cb α β | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_evalx continuous_const, have I3 : ∀x y, is_closed {f : Cb α β | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_evalx continuous_evalx, have I4 : ∀x y z, is_closed {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx), have I5 : ∀x, is_closed {f : Cb α β | f (x, x) = 0} := λx, is_closed_eq continuous_evalx continuous_const, have I6 : ∀x y, is_closed {f : Cb α β | f (x, y) ≤ max_var α β} := λx y, is_closed_le continuous_evalx continuous_const, have : candidates_b α β = (⋂x y, {f : Cb α β | f ((@inl α β x), (@inl α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f ((@inr α β x), (@inr α β y)) = dist x y}) ∩ (⋂x y, {f : Cb α β | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb α β | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb α β | f (x, x) = 0}) ∩ (⋂x y, {f : Cb α β | f (x, y) ≤ max_var α β}) := begin ext, unfold candidates_b, unfold candidates, simp [-sum.forall], refl end, rw this, repeat { apply is_closed.inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma compact_candidates_b : is_compact (candidates_b α β) := begin refine arzela_ascoli₂ (Icc 0 (max_var α β)) compact_Icc (candidates_b α β) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var α β * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var α β : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var α β * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb α β) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on ℝ, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb α β} (C : ℝ) {x : α} : bdd_below (range (λ (y : β), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (x : α), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default β)) + C : cinfi_le (HD_below_aux1 C) (default β) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end lemma HD_below_aux2 {f : Cb α β} (C : ℝ) {y : β} : bdd_below (range (λ (x : α), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb α β) (C : ℝ) : bdd_above (range (λ (y : β), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default α), inr y) + C : cinfi_le (HD_below_aux2 C) (default α) ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _) end /-- Explicit bound on HD (dist). This means that when looking for minimizers it will be sufficient to look for functions with HD(f) bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist α β) ≤ diam (univ : set α) + 1 + diam (univ : set β) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl x, inr (default β)) := cinfi_le (by simpa using HD_below_aux1 0) (default β), have B : dist (inl x) (inr (default β)) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl x) (inr (default β)) = dist x (default α) + 1 + dist (default β) (default β) : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist α β (inl x, inr y)) ≤ candidates_b_dist α β (inl (default α), inr y) := cinfi_le (by simpa using HD_below_aux2 0) (default α), have B : dist (inl (default α)) (inr y) ≤ diam (univ : set α) + 1 + diam (univ : set β) := calc dist (inl (default α)) (inr y) = dist (default α) (default α) + 1 + dist (default β) y : rfl ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : begin apply add_le_add (add_le_add _ (le_refl _)), exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem (bounded_of_compact (compact_univ)) (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb α β) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux1 _ (dist f g)) (λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : β), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb α β) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_le_csupr (HD_bound_aux2 _ (dist f g)) (λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:α, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { by simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb α β) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb α β → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (α : Type u) (β : Type v) [metric_space α] [compact_space α] [nonempty α] [metric_space β] [compact_space β] [nonempty β] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃f ∈ candidates_b α β, ∀g ∈ candidates_b α β, HD f ≤ HD g := compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb α β := classical.some (exists_minimizer α β) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist α β ∈ candidates_b α β := by cases (classical.some_spec (exists_minimizer α β)); assumption private lemma HD_optimal_GH_dist_le (g : Cb α β) (hg : g ∈ candidates_b α β) : HD (optimal_GH_dist α β) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer α β) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on α ⊕ β, on which the predistance is given by the candidate. Then, we will identify points at 0 predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (α ⊕ β) := { dist := λp q, optimal_GH_dist α β (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b α β), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b α β), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b α β) } local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid /-- A metric space which realizes the optimal coupling between α and β -/ @[derive [metric_space]] definition optimal_GH_coupling : Type* := pseudo_metric_quot (α ⊕ β) /-- Injection of α in the optimal coupling between α and β -/ def optimal_GH_injl (x : α) : optimal_GH_coupling α β := ⟦inl x⟧ /-- The injection of α in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- Injection of β in the optimal coupling between α and β -/ def optimal_GH_injr (y : β) : optimal_GH_coupling α β := ⟦inr y⟧ /-- The injection of β in the optimal coupling between α and β is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr α β) := begin refine isometry_emetric_iff_metric.2 (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b α β) _ _, end /-- The optimal coupling between two compact spaces α and β is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling α β) := ⟨begin have : (univ : set (optimal_GH_coupling α β)) = (optimal_GH_injl α β '' univ) ∪ (optimal_GH_injr α β '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl α β x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr α β x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (compact_univ.image (isometry_optimal_GH_injl α β).continuous).union (compact_univ.image (isometry_optimal_GH_injr α β).continuous) end⟩ /-- For any candidate f, HD(f) is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b α β) : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le α β f h), have A : ∀ x ∈ range (optimal_GH_injl α β), ∃ y ∈ range (optimal_GH_injr α β), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist α β (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist α β (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z, inr z') ≤ r := begin rw hz', exact le_of_lt hr' end, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : optimal_GH_injl α β xα ∈ range (optimal_GH_injl α β) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist α β (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist α β (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist α β (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl α β z', mem_range_self _], have : (optimal_GH_dist α β) (inl z', inr z) ≤ r := begin rw hz', exact le_of_lt hr' end, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
a048782e21876010eb96ff400eb42cfc1d4c9709
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/dense_embedding.lean
af0d11c6b63c5476aceec07b111949786938e677
[ "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
15,657
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation import topology.bases /-! # Dense embeddings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`, namely it induces the topology on its codomain; * `dense_embedding e` means `e` is further an `embedding`, namely it is injective and `inducing`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a T₃ space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter open_locale classical topology filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ @[protect_proj] structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range protected lemma preconnected_space [preconnected_space α] (di : dense_inducing i) : preconnected_space β := di.dense.preconnected_space di.continuous lemma closure_image_mem_nhds {s : set α} {a : α} (di : dense_inducing i) (hs : s ∈ 𝓝 a) : closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, ((nhds_basis_opens _).comap _).mem_iff] at hs, rcases hs with ⟨U, ⟨haU, hUo⟩, sub : i ⁻¹' U ⊆ s⟩, refine mem_of_superset (hUo.mem_nhds haU) _, calc U ⊆ closure (i '' (i ⁻¹' U)) : di.dense.subset_closure_image_preimage_of_is_open hUo ... ⊆ closure (i '' s) : closure_mono (image_subset i sub) end lemma dense_image (di : dense_inducing i) {s : set α} : dense (i '' s) ↔ dense s := begin refine ⟨λ H x, _, di.dense.dense_image di.continuous⟩, rw [di.to_inducing.closure_eq_preimage_closure_image, H.closure_eq, preimage_univ], trivial end /-- If `i : α → β` is a dense embedding with dense complement of the range, then any compact set in `α` has empty interior. -/ lemma interior_compact_eq_empty [t2_space β] (di : dense_inducing i) (hd : dense (range i)ᶜ) {s : set α} (hs : is_compact s) : interior s = ∅ := begin refine eq_empty_iff_forall_not_mem.2 (λ x hx, _), rw [mem_interior_iff_mem_nhds] at hx, have := di.closure_image_mem_nhds hx, rw (hs.image di.continuous).is_closed.closure_eq at this, rcases hd.inter_nhds_nonempty this with ⟨y, hyi, hys⟩, exact hyi (image_subset_range _ _ hys) end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod_map de₂.dense } open topological_space /-- If the domain of a `dense_inducing` map is a separable space, then so is the codomain. -/ protected lemma separable_space [separable_space α] : separable_space β := di.dense.separable_space di.continuous variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- ``` γ -f→ α g↓ ↓e δ -h→ β ``` -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_within_ne_bot (di : dense_inducing i) (b : β) : ne_bot (𝓝[range i] b) := di.dense.nhds_within_ne_bot b lemma comap_nhds_ne_bot (di : dense_inducing i) (b : β) : ne_bot (comap i (𝓝 b)) := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @@lim _ ⟨f (di.dense.some b)⟩ (comap i (𝓝 b)) f lemma extend_eq_of_tendsto [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) : di.extend f b = c := by haveI := di.comap_nhds_ne_bot; exact hf.lim_eq lemma extend_eq_at [t2_space γ] {f : α → γ} {a : α} (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq_of_tendsto _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq_at' [t2_space γ] {f : α → γ} {a : α} (c : γ) (hf : tendsto f (𝓝 a) (𝓝 c)) : di.extend f (i a) = f a := di.extend_eq_at (continuous_at_of_tendsto_nhds hf) lemma extend_eq [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_eq_at hf.continuous_at /-- Variation of `extend_eq` where we ask that `f` has a limit along `comap i (𝓝 b)` for each `b : β`. This is a strictly stronger assumption than continuity of `f`, but in a lot of cases you'd have to prove it anyway to use `continuous_extend`, so this avoids doing the work twice. -/ lemma extend_eq' [t2_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀ b, ∃ c, tendsto f (comap i (𝓝 b)) (𝓝 c)) (a : α) : di.extend f (i a) = f a := begin rcases hf (i a) with ⟨b, hb⟩, refine di.extend_eq_at' b _, rwa ← di.to_inducing.nhds_eq_comap at hb, end lemma extend_unique_at [t2_space γ] {b : β} {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ᶠ x in comap i (𝓝 b), g (i x) = f x) (hg : continuous_at g b) : di.extend f b = g b := begin refine di.extend_eq_of_tendsto (λ s hs, mem_map.2 _), suffices : ∀ᶠ (x : α) in comap i (𝓝 b), g (i x) ∈ s, from hf.mp (this.mono $ λ x hgx hfx, hfx ▸ hgx), clear hf f, refine eventually_comap.2 ((hg.eventually hs).mono _), rintros _ hxs x rfl, exact hxs end lemma extend_unique [t2_space γ] {f : α → γ} {g : β → γ} (di : dense_inducing i) (hf : ∀ x, g (i x) = f x) (hg : continuous g) : di.extend f = g := funext $ λ b, extend_unique_at di (eventually_of_forall hf) hg.continuous_at lemma continuous_at_extend [t3_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : ∀ᶠ x in 𝓝 b, ∃c, tendsto f (comap i $ 𝓝 x) (𝓝 c)) : continuous_at (di.extend f) b := begin set φ := di.extend f, haveI := di.comap_nhds_ne_bot, suffices : ∀ V' ∈ 𝓝 (φ b), is_closed V' → φ ⁻¹' V' ∈ 𝓝 b, by simpa [continuous_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, set V₁ := {x | tendsto f (comap i $ 𝓝 x) (𝓝 $ φ x)}, have V₁_in : V₁ ∈ 𝓝 b, { filter_upwards [hf], rintros x ⟨c, hc⟩, dsimp [V₁, φ], rwa di.extend_eq_of_tendsto hc }, obtain ⟨V₂, V₂_in, V₂_op, hV₂⟩ : ∃ V₂ ∈ 𝓝 b, is_open V₂ ∧ ∀ x ∈ i ⁻¹' V₂, f x ∈ V', { simpa [and_assoc] using ((nhds_basis_opens' b).comap i).tendsto_left_iff.mp (mem_of_mem_nhds V₁_in : b ∈ V₁) V' V'_in }, suffices : ∀ x ∈ V₁ ∩ V₂, φ x ∈ V', { filter_upwards [inter_mem V₁_in V₂_in] using this, }, rintros x ⟨x_in₁, x_in₂⟩, have hV₂x : V₂ ∈ 𝓝 x := is_open.mem_nhds V₂_op x_in₂, apply V'_closed.mem_of_tendsto x_in₁, use V₂, tauto, end lemma continuous_extend [t3_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.continuous_at_extend $ univ_mem' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [filter.le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : dense_range e) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- If the domain of a `dense_embedding` is a separable space, then so is its codomain. -/ protected lemma separable_space [separable_space α] : separable_space β := de.to_dense_inducing.separable_space /-- The product of two dense embeddings is a dense embedding. -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ @[simps] def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x, subset_closure $ mem_image_of_mem e x.prop⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense := dense_iff_closure_eq.2 $ begin ext ⟨x, hx⟩, rw image_eq_range at hx, simpa [closure_subtype, ← range_comp, (∘)], end, inj := (de.inj.comp subtype.coe_injective).cod_restrict _, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap, (∘)]) } lemma dense_image {s : set α} : dense (e '' s) ↔ dense s := de.to_dense_inducing.dense_image end dense_embedding lemma dense_embedding_id {α : Type*} [topological_space α] : dense_embedding (id : α → α) := { dense := dense_range_id, .. embedding_id } lemma dense.dense_embedding_coe [topological_space α] {s : set α} (hs : dense s) : dense_embedding (coe : s → α) := { dense := hs.dense_range_coe, .. embedding_subtype_coe } lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : hp.closure_eq, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod_map he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod_map $ he.prod_map he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end -- Bourbaki GT III §3 no.4 Proposition 7 (generalised to any dense-inducing map to a T₃ space) lemma filter.has_basis.has_basis_of_dense_inducing [topological_space α] [topological_space β] [t3_space β] {ι : Type*} {s : ι → set α} {p : ι → Prop} {x : α} (h : (𝓝 x).has_basis p s) {f : α → β} (hf : dense_inducing f) : (𝓝 (f x)).has_basis p $ λ i, closure $ f '' (s i) := begin rw filter.has_basis_iff at h ⊢, intros T, refine ⟨λ hT, _, λ hT, _⟩, { obtain ⟨T', hT₁, hT₂, hT₃⟩ := exists_mem_nhds_is_closed_subset hT, have hT₄ : f⁻¹' T' ∈ 𝓝 x, { rw hf.to_inducing.nhds_eq_comap x, exact ⟨T', hT₁, subset.rfl⟩, }, obtain ⟨i, hi, hi'⟩ := (h _).mp hT₄, exact ⟨i, hi, (closure_mono (image_subset f hi')).trans (subset.trans (closure_minimal (image_subset_iff.mpr subset.rfl) hT₂) hT₃)⟩, }, { obtain ⟨i, hi, hi'⟩ := hT, suffices : closure (f '' s i) ∈ 𝓝 (f x), { filter_upwards [this] using hi', }, replace h := (h (s i)).mpr ⟨i, hi, subset.rfl⟩, exact hf.closure_image_mem_nhds h, }, end
1729d73e81e8f5d00098efa06f8b663346aba9ff
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/not_bug1.lean
ca36c686e6db943376c49acdda2cb5340f721ef2
[ "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
368
lean
import logic open bool constant list : Type.{1} constant nil : list constant cons : bool → list → list infixr `::` := cons notation `[` l:(foldr `,` (h t, cons h t) nil `]`) := l check [] check [tt] check [tt, ff] check [tt, ff, ff] check tt :: ff :: [tt, ff, ff] check tt :: [] constants a b c : bool check a :: b :: nil check [a, b] check [a, b, c] check []
bc3bc161ac9e12df21ae5604b43f6a2c7c3d4967
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/control/monadfail.lean
dbd74d0bfd5ed88fbe344f2c6fbe9e3a4271a078
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
594
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.control.lift init.data.string.basic universes u v class MonadFail (m : Type u → Type v) := (fail {} : ∀ {a}, String → m a) def matchFailed {α : Type u} {m : Type u → Type v} [MonadFail m] : m α := MonadFail.fail "match failed" instance monadFailLift (m n : Type u → Type v) [HasMonadLift m n] [MonadFail m] [Monad n] : MonadFail n := { fail := fun α s => monadLift (MonadFail.fail s : m α) }
16c388e445487fef0a8cdd36258bcc10dd720be1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/100-theorems-list/70_perfect_numbers.lean
bed8801c9aa47abfe986591b6f00f7d74e45f204
[ "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
4,927
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import number_theory.arithmetic_function import number_theory.lucas_lehmer import algebra.geom_sum import ring_theory.multiplicity /-! # Perfect Numbers This file proves Theorem 70 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem characterizes even perfect numbers. Euclid proved that if `2 ^ (k + 1) - 1` is prime (these primes are known as Mersenne primes), then `2 ^ k * 2 ^ (k + 1) - 1` is perfect. Euler proved the converse, that if `n` is even and perfect, then there exists `k` such that `n = 2 ^ k * 2 ^ (k + 1) - 1` and `2 ^ (k + 1) - 1` is prime. ## References https://en.wikipedia.org/wiki/Euclid%E2%80%93Euler_theorem -/ lemma odd_mersenne_succ (k : ℕ) : ¬ 2 ∣ mersenne (k + 1) := by simp [← even_iff_two_dvd, ← nat.even_succ, nat.succ_eq_add_one] with parity_simps namespace nat open arithmetic_function finset open_locale arithmetic_function lemma sigma_two_pow_eq_mersenne_succ (k : ℕ) : σ 1 (2 ^ k) = mersenne (k + 1) := by simpa [mersenne, prime_two, ← geom_sum_mul_add 1 (k+1)] /-- Euclid's theorem that Mersenne primes induce perfect numbers -/ theorem perfect_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : perfect ((2 ^ k) * mersenne (k + 1)) := begin rw [perfect_iff_sum_divisors_eq_two_mul, ← mul_assoc, ← pow_succ, ← sigma_one_apply, mul_comm, is_multiplicative_sigma.map_mul_of_coprime (nat.prime_two.coprime_pow_of_not_dvd (odd_mersenne_succ _)), sigma_two_pow_eq_mersenne_succ], { simp [pr, nat.prime_two] }, { apply mul_pos (pow_pos _ k) (mersenne_pos (nat.succ_pos k)), norm_num } end lemma ne_zero_of_prime_mersenne (k : ℕ) (pr : (mersenne (k + 1)).prime) : k ≠ 0 := begin rintro rfl, simpa [mersenne, not_prime_one] using pr, end theorem even_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : even ((2 ^ k) * mersenne (k + 1)) := by simp [ne_zero_of_prime_mersenne k pr] with parity_simps lemma eq_two_pow_mul_odd {n : ℕ} (hpos : 0 < n) : ∃ (k m : ℕ), n = 2 ^ k * m ∧ ¬ even m := begin have h := (multiplicity.finite_nat_iff.2 ⟨nat.prime_two.ne_one, hpos⟩), cases multiplicity.pow_multiplicity_dvd h with m hm, use [(multiplicity 2 n).get h, m], refine ⟨hm, _⟩, rw even_iff_two_dvd, have hg := multiplicity.is_greatest' h (nat.lt_succ_self _), contrapose! hg, rcases hg with ⟨k, rfl⟩, apply dvd.intro k, rw [pow_succ', mul_assoc, ← hm], end /-- Euler's theorem that even perfect numbers can be factored as a power of two times a Mersenne prime. -/ theorem eq_two_pow_mul_prime_mersenne_of_even_perfect {n : ℕ} (ev : even n) (perf : perfect n) : ∃ (k : ℕ), prime (mersenne (k + 1)) ∧ n = 2 ^ k * mersenne (k + 1) := begin have hpos := perf.2, rcases eq_two_pow_mul_odd hpos with ⟨k, m, rfl, hm⟩, use k, rw [perfect_iff_sum_divisors_eq_two_mul hpos, ← sigma_one_apply, is_multiplicative_sigma.map_mul_of_coprime (nat.prime_two.coprime_pow_of_not_dvd hm).symm, sigma_two_pow_eq_mersenne_succ, ← mul_assoc, ← pow_succ] at perf, rcases nat.coprime.dvd_of_dvd_mul_left (nat.prime_two.coprime_pow_of_not_dvd (odd_mersenne_succ _)) (dvd.intro _ perf) with ⟨j, rfl⟩, rw [← mul_assoc, mul_comm _ (mersenne _), mul_assoc] at perf, have h := mul_left_cancel' (ne_of_gt (mersenne_pos (nat.succ_pos _))) perf, rw [sigma_one_apply, sum_divisors_eq_sum_proper_divisors_add_self, ← succ_mersenne, add_mul, one_mul, add_comm] at h, have hj := add_left_cancel h, cases sum_proper_divisors_dvd (by { rw hj, apply dvd.intro_left (mersenne (k + 1)) rfl }), { have j1 : j = 1 := eq.trans hj.symm h_1, rw [j1, mul_one, sum_proper_divisors_eq_one_iff_prime] at h_1, simp [h_1, j1] }, { have jcon := eq.trans hj.symm h_1, rw [← one_mul j, ← mul_assoc, mul_one] at jcon, have jcon2 := mul_right_cancel' _ jcon, { exfalso, cases k, { apply hm, rw [← jcon2, pow_zero, one_mul, one_mul] at ev, rw [← jcon2, one_mul], exact ev }, apply ne_of_lt _ jcon2, rw [mersenne, ← nat.pred_eq_sub_one, lt_pred_iff, ← pow_one (nat.succ 1)], apply pow_lt_pow (nat.lt_succ_self 1) (nat.succ_lt_succ (nat.succ_pos k)) }, contrapose! hm, simp [hm] } end /-- The Euclid-Euler theorem characterizing even perfect numbers -/ theorem even_and_perfect_iff {n : ℕ} : (even n ∧ perfect n) ↔ ∃ (k : ℕ), prime (mersenne (k + 1)) ∧ n = 2 ^ k * mersenne (k + 1) := begin split, { rintro ⟨ev, perf⟩, exact eq_two_pow_mul_prime_mersenne_of_even_perfect ev perf }, { rintro ⟨k, pr, rfl⟩, exact ⟨even_two_pow_mul_mersenne_of_prime k pr, perfect_two_pow_mul_mersenne_of_prime k pr⟩ } end end nat
fee7a56cb05df99c310308fc515af2d67941cb21
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/non_unital_subsemiring/basic.lean
2368f132629a98aabb619edd25485b26b5ba624d
[ "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
34,150
lean
/- Copyright (c) 2022 Jireh Loreaux All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.ring.equiv import algebra.ring.prod import data.set.finite import group_theory.submonoid.membership import group_theory.subsemigroup.membership import group_theory.subsemigroup.centralizer /-! # Bundled non-unital subsemirings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define bundled non-unital subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, non-unital subsemiring `map`, `comap` and range (`srange`) of a `non_unital_ring_hom` etc. -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [non_unital_non_assoc_semiring R] (M : subsemigroup R) /-- `non_unital_subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that are both an additive submonoid and also a multiplicative subsemigroup. -/ class non_unital_subsemiring_class (S : Type*) (R : Type u) [non_unital_non_assoc_semiring R] [set_like S R] extends add_submonoid_class S R := (mul_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a * b ∈ s) @[priority 100] -- See note [lower instance priority] instance non_unital_subsemiring_class.mul_mem_class (S : Type*) (R : Type u) [non_unital_non_assoc_semiring R] [set_like S R] [h : non_unital_subsemiring_class S R] : mul_mem_class S R := { .. h } namespace non_unital_subsemiring_class variables [set_like S R] [non_unital_subsemiring_class S R] (s : S) include R S open add_submonoid_class /-- A non-unital subsemiring of a `non_unital_non_assoc_semiring` inherits a `non_unital_non_assoc_semiring` structure -/ @[priority 75] /- Prefer subclasses of `non_unital_non_assoc_semiring` over subclasses of `non_unital_subsemiring_class`. -/ instance to_non_unital_non_assoc_semiring : non_unital_non_assoc_semiring s := subtype.coe_injective.non_unital_non_assoc_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := subtype.coe_injective.no_zero_divisors coe rfl (λ x y, rfl) /-- The natural non-unital ring hom from a non-unital subsemiring of a non-unital semiring `R` to `R`. -/ def subtype : s →ₙ+* R := { to_fun := coe, .. add_submonoid_class.subtype s, .. mul_mem_class.subtype s } @[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl omit R S /-- A non-unital subsemiring of a `non_unital_semiring` is a `non_unital_semiring`. -/ instance to_non_unital_semiring {R} [non_unital_semiring R] [set_like S R] [non_unital_subsemiring_class S R] : non_unital_semiring s := subtype.coe_injective.non_unital_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) /-- A non-unital subsemiring of a `non_unital_comm_semiring` is a `non_unital_comm_semiring`. -/ instance to_non_unital_comm_semiring {R} [non_unital_comm_semiring R] [set_like S R] [non_unital_subsemiring_class S R] : non_unital_comm_semiring s := subtype.coe_injective.non_unital_comm_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) /-! Note: currently, there are no ordered versions of non-unital rings. -/ end non_unital_subsemiring_class variables [non_unital_non_assoc_semiring S] [non_unital_non_assoc_semiring T] set_option old_structure_cmd true /-- A non-unital subsemiring of a non-unital semiring `R` is a subset `s` that is both an additive submonoid and a semigroup. -/ structure non_unital_subsemiring (R : Type u) [non_unital_non_assoc_semiring R] extends add_submonoid R, subsemigroup R /-- Reinterpret a `non_unital_subsemiring` as a `subsemigroup`. -/ add_decl_doc non_unital_subsemiring.to_subsemigroup /-- Reinterpret a `non_unital_subsemiring` as an `add_submonoid`. -/ add_decl_doc non_unital_subsemiring.to_add_submonoid namespace non_unital_subsemiring instance : set_like (non_unital_subsemiring R) R := { coe := non_unital_subsemiring.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : non_unital_subsemiring_class (non_unital_subsemiring R) R := { zero_mem := zero_mem', add_mem := add_mem', mul_mem := mul_mem' } @[simp] lemma mem_carrier {s : non_unital_subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two non-unital subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : non_unital_subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a non-unital subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : non_unital_subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_subsemigroup.copy s hs } @[simp] lemma coe_copy (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_subsemigroup_injective : function.injective (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_subsemigroup_strict_mono : strict_mono (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) := λ _ _, id @[mono] lemma to_subsemigroup_mono : monotone (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) := to_subsemigroup_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `non_unital_subsemiring R` from a set `s`, a subsemigroup `sg`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sg ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sg : subsemigroup R) (hg : ↑sg = s) (sa : add_submonoid R) (ha : ↑sa = s) : non_unital_subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hg] using sg.mul_mem } @[simp] lemma coe_mk' {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) : (non_unital_subsemiring.mk' s sg hg sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ non_unital_subsemiring.mk' s sg hg sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_subsemigroup {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) : (non_unital_subsemiring.mk' s sg hg sa ha).to_subsemigroup = sg := set_like.coe_injective hg.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa =s) : (non_unital_subsemiring.mk' s sg hg sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end non_unital_subsemiring namespace non_unital_subsemiring variables {F G : Type*} [non_unital_ring_hom_class F R S] [non_unital_ring_hom_class G S T] (s : non_unital_subsemiring R) @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl /-! Note: currently, there are no ordered versions of non-unital rings. -/ @[simp] lemma mem_to_subsemigroup {s : non_unital_subsemiring R} {x : R} : x ∈ s.to_subsemigroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_subsemigroup (s : non_unital_subsemiring R) : (s.to_subsemigroup : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : non_unital_subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : non_unital_subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The non-unital subsemiring `R` of the non-unital semiring `R`. -/ instance : has_top (non_unital_subsemiring R) := ⟨{ .. (⊤ : subsemigroup R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : non_unital_subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : non_unital_subsemiring R) : set R) = set.univ := rfl /-- The preimage of a non-unital subsemiring along a non-unital ring homomorphism is a non-unital subsemiring. -/ def comap (f : F) (s : non_unital_subsemiring S) : non_unital_subsemiring R := { carrier := f ⁻¹' s, .. s.to_subsemigroup.comap (f : mul_hom R S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : non_unital_subsemiring S) (f : F) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : non_unital_subsemiring S} {f : F} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl -- this has some nasty coercions, how to deal with it? lemma comap_comap (s : non_unital_subsemiring T) (g : G) (f : F) : ((s.comap g : non_unital_subsemiring S).comap f : non_unital_subsemiring R) = s.comap ((g : S →ₙ+* T).comp (f : R →ₙ+* S)) := rfl /-- The image of a non-unital subsemiring along a ring homomorphism is a non-unital subsemiring. -/ def map (f : F) (s : non_unital_subsemiring R) : non_unital_subsemiring S := { carrier := f '' s, .. s.to_subsemigroup.map (f : R →ₙ* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : F) (s : non_unital_subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : F} {s : non_unital_subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (non_unital_ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ -- unavoidable coercions? lemma map_map (g : G) (f : F) : (s.map (f : R →ₙ+* S)).map (g : S →ₙ+* T) = s.map ((g : S →ₙ+* T).comp (f : R →ₙ+* S)) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : F} {s : non_unital_subsemiring R} {t : non_unital_subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : F) : @galois_connection (non_unital_subsemiring R) (non_unital_subsemiring S) _ _ (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A non-unital subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : F) (hf : function.injective (f : R → S)) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (map_mul f _ _), map_add' := λ _ _, subtype.ext (map_add f _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : F) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end non_unital_subsemiring namespace non_unital_ring_hom open non_unital_subsemiring variables {F G : Type*} [non_unital_ring_hom_class F R S] [non_unital_ring_hom_class G S T] (f : F) (g : G) /-- The range of a non-unital ring homomorphism is a non-unital subsemiring. See note [range copy pattern]. -/ def srange : non_unital_subsemiring S := ((⊤ : non_unital_subsemiring R).map (f : R →ₙ+* S)).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (@srange R S _ _ _ _ f : set S) = set.range f := rfl @[simp] lemma mem_srange {f : F} {y : S} : y ∈ (@srange R S _ _ _ _ f) ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map : @srange R S _ _ _ _ f = (⊤ : non_unital_subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : F) (x : R) : f x ∈ @srange R S _ _ _ _ f := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange (g : S →ₙ+* T) (f : R →ₙ+* S) : map g (srange f) = srange (g.comp f) := by simpa only [srange_eq_map] using (⊤ : non_unital_subsemiring R).map_map g f /-- The range of a morphism of non-unital semirings is finite if the domain is a finite. -/ instance finite_srange [finite R] (f : F) : finite (srange f : non_unital_subsemiring S) := (set.finite_range f).to_subtype end non_unital_ring_hom namespace non_unital_subsemiring -- should we define this as the range of the zero homomorphism? instance : has_bot (non_unital_subsemiring R) := ⟨{ carrier := {0}, add_mem' := λ _ _ _ _, by simp * at *, zero_mem' := set.mem_singleton 0, mul_mem' := λ _ _ _ _, by simp * at *}⟩ instance : inhabited (non_unital_subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : non_unital_subsemiring R) : set R) = {0} := rfl lemma mem_bot {x : R} : x ∈ (⊥ : non_unital_subsemiring R) ↔ x = 0 := set.mem_singleton_iff /-- The inf of two non-unital subsemirings is their intersection. -/ instance : has_inf (non_unital_subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_subsemigroup ⊓ t.to_subsemigroup, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : non_unital_subsemiring R) : ((p ⊓ p' : non_unital_subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : non_unital_subsemiring R} {x : R} :x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (non_unital_subsemiring R) := ⟨λ s, non_unital_subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, non_unital_subsemiring.to_subsemigroup t) (by simp) (⨅ t ∈ s, non_unital_subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (non_unital_subsemiring R)) : ((Inf S : non_unital_subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (non_unital_subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_subsemigroup (s : set (non_unital_subsemiring R)) : (Inf s).to_subsemigroup = ⨅ t ∈ s, non_unital_subsemiring.to_subsemigroup t := mk'_to_subsemigroup _ _ @[simp] lemma Inf_to_add_submonoid (s : set (non_unital_subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, non_unital_subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Non-unital subsemirings of a non-unital semiring form a complete lattice. -/ instance : complete_lattice (non_unital_subsemiring R) := { bot := (⊥), bot_le := λ s x hx, (mem_bot.mp hx).symm ▸ zero_mem s, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (non_unital_subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : non_unital_subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ section center /-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/ def center (R) [non_unital_semiring R] : non_unital_subsemiring R := { carrier := set.center R, zero_mem' := set.zero_mem_center R, add_mem' := λ a b, set.add_mem_center, .. subsemigroup.center R } lemma coe_center (R) [non_unital_semiring R] : ↑(center R) = set.center R := rfl @[simp] lemma center_to_subsemigroup (R) [non_unital_semiring R] : (center R).to_subsemigroup = subsemigroup.center R := rfl lemma mem_center_iff {R} [non_unital_semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center {R} [non_unital_semiring R] [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [non_unital_comm_semiring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance {R} [non_unital_semiring R] : non_unital_comm_semiring (center R) := { ..subsemigroup.center.comm_semigroup, ..(non_unital_subsemiring_class.to_non_unital_semiring (center R)) } end center section centralizer /-- The centralizer of a set as non-unital subsemiring. -/ def centralizer {R} [non_unital_semiring R] (s : set R) : non_unital_subsemiring R := { carrier := s.centralizer, zero_mem' := set.zero_mem_centralizer _, add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy, ..subsemigroup.centralizer s } @[simp, norm_cast] lemma coe_centralizer {R} [non_unital_semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl lemma centralizer_to_subsemigroup {R} [non_unital_semiring R] (s : set R) : (centralizer s).to_subsemigroup = subsemigroup.centralizer s := rfl lemma mem_centralizer_iff {R} [non_unital_semiring R] {s : set R} {z : R} : z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma centralizer_le {R} [non_unital_semiring R] (s t : set R) (h : s ⊆ t) : centralizer t ≤ centralizer s := set.centralizer_subset h @[simp] lemma centralizer_univ {R} [non_unital_semiring R] : centralizer set.univ = center R := set_like.ext' (set.centralizer_univ R) end centralizer /-- The `non_unital_subsemiring` generated by a set. -/ def closure (s : set R) : non_unital_subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : non_unital_subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The non-unital subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A non-unital subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : non_unital_subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : non_unital_subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : non_unital_subsemiring R} {x : S} : x ∈ K.map (f : R →ₙ+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : non_unital_subsemiring R) : K.map (f : R →ₙ+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : non_unital_subsemiring S) : K.comap (f : R →ₙ+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end non_unital_subsemiring namespace subsemigroup /-- The additive closure of a non-unital subsemigroup is a non-unital subsemiring. -/ def non_unital_subsemiring_closure (M : subsemigroup R) : non_unital_subsemiring R := { mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma non_unital_subsemiring_closure_coe : (M.non_unital_subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma non_unital_subsemiring_closure_to_add_submonoid : M.non_unital_subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `non_unital_subsemiring` generated by a multiplicative subsemigroup coincides with the `non_unital_subsemiring.closure` of the subsemigroup itself . -/ lemma non_unital_subsemiring_closure_eq_closure : M.non_unital_subsemiring_closure = non_unital_subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (non_unital_subsemiring.mem_closure.mp hx) M.non_unital_subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end subsemigroup namespace non_unital_subsemiring @[simp] lemma closure_subsemigroup_closure (s : set R) : closure ↑(subsemigroup.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (subsemigroup.mem_closure.mp hy) (closure s).to_subsemigroup subset_closure)) (closure_mono (subsemigroup.subset_closure)) /-- The elements of the non-unital subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative subsemigroup `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (subsemigroup.closure s : set R) := by simp [← subsemigroup.non_unital_subsemiring_closure_to_add_submonoid, subsemigroup.non_unital_subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (subsemigroup.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (subsemigroup.mem_closure.mp hy) H.to_subsemigroup (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hadd, H0, Hmul⟩).2 Hs h /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator] lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H0_left : ∀ x, p 0 x) (H0_right : ∀ x, p x 0) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p x y := closure_induction hx (λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (Hadd_right x₁) (Hmul_right x₁)) (H0_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variables {R} {F : Type*} [non_unital_ring_hom_class F R S] /-- Closure of a non-unital subsemiring `S` equals `S`. -/ lemma closure_eq (s : non_unital_subsemiring R) : closure (s : set R) = s := (non_unital_subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (non_unital_subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (non_unital_subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (non_unital_subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (non_unital_subsemiring.gi R).gc.l_Sup lemma map_sup (s t : non_unital_subsemiring R) (f : F) : (map f (s ⊔ t) : non_unital_subsemiring S) = map f s ⊔ map f t := @galois_connection.l_sup _ _ s t _ _ _ _ (gc_map_comap f) lemma map_supr {ι : Sort*} (f : F) (s : ι → non_unital_subsemiring R) : (map f (supr s) : non_unital_subsemiring S) = ⨆ i, map f (s i) := @galois_connection.l_supr _ _ _ _ _ _ _ (gc_map_comap f) s lemma comap_inf (s t : non_unital_subsemiring S) (f : F) : (comap f (s ⊓ t) : non_unital_subsemiring R) = comap f s ⊓ comap f t := @galois_connection.u_inf _ _ s t _ _ _ _ (gc_map_comap f) lemma comap_infi {ι : Sort*} (f : F) (s : ι → non_unital_subsemiring S) : (comap f (infi s) : non_unital_subsemiring R) = ⨅ i, comap f (s i) := @galois_connection.u_infi _ _ _ _ _ _ _ (gc_map_comap f) s @[simp] lemma map_bot (f : F) : map f (⊥ : non_unital_subsemiring R) = (⊥ : non_unital_subsemiring S) := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : F) : comap f (⊤ : non_unital_subsemiring S) = (⊤ : non_unital_subsemiring R) := (gc_map_comap f).u_top /-- Given `non_unital_subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a non-unital subsemiring of `R × S`. -/ def prod (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : non_unital_subsemiring (R × S) := { carrier := (s : set R) ×ˢ (t : set S), .. s.to_subsemigroup.prod t.to_subsemigroup, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : (s.prod t : set (R × S)) = (s : set R) ×ˢ (t : set S) := rfl lemma mem_prod {s : non_unital_subsemiring R} {t : non_unital_subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : non_unital_subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : non_unital_subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : non_unital_subsemiring R) : monotone (λ t : non_unital_subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : non_unital_subsemiring S) : monotone (λ s : non_unital_subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : non_unital_subsemiring R) : s.prod (⊤ : non_unital_subsemiring S) = s.comap (non_unital_ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : non_unital_subsemiring S) : (⊤ : non_unital_subsemiring R).prod s = s.comap (non_unital_ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : non_unital_subsemiring R).prod (⊤ : non_unital_subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of non-unital subsemirings is isomorphic to their product as semigroups. -/ def prod_equiv (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → non_unital_subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : non_unital_subsemiring R := non_unital_subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_subsemigroup) (subsemigroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → non_unital_subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : non_unital_subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (non_unital_subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (non_unital_subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end non_unital_subsemiring namespace non_unital_ring_hom variables {F : Type*} [non_unital_non_assoc_semiring T] [non_unital_ring_hom_class F R S] {s : non_unital_subsemiring R} open non_unital_subsemiring_class non_unital_subsemiring /-- Restriction of a non-unital ring homomorphism to a non-unital subsemiring of the codomain. -/ def cod_restrict (f : F) (s : non_unital_subsemiring S) (h : ∀ x, f x ∈ s) : R →ₙ+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →ₙ* S).cod_restrict s.to_subsemigroup h, .. (f : R →+ S).cod_restrict s.to_add_submonoid h } /-- Restriction of a non-unital ring homomorphism to its range interpreted as a non-unital subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : F) : R →ₙ+* (srange f : non_unital_subsemiring S) := cod_restrict f (srange f) (mem_srange_self f) @[simp] lemma coe_srange_restrict (f : F) (x : R) : (srange_restrict f x : S) = f x := rfl lemma srange_restrict_surjective (f : F) : function.surjective (srange_restrict f : R → (srange f : non_unital_subsemiring S)) := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : F} : srange f = (⊤ : non_unital_subsemiring S) ↔ function.surjective (f : R → S):= set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective non-unital ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : F) (hf : function.surjective (f : R → S)) : srange f = (⊤ : non_unital_subsemiring S) := srange_top_iff_surjective.2 hf /-- The non-unital subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : F) : non_unital_subsemiring R := { carrier := {x | f x = g x}, .. (f : R →ₙ* S).eq_mlocus (g : R →ₙ* S), .. (f : R →+ S).eq_mlocus g } /-- If two non-unital ring homomorphisms are equal on a set, then they are equal on its non-unital subsemiring closure. -/ lemma eq_on_sclosure {f g : F} {s : set R} (h : set.eq_on (f : R → S) (g : R → S) s) : set.eq_on f g (closure s) := show closure s ≤ eq_slocus f g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : F} (h : set.eq_on (f : R → S) (g : R → S) (⊤ : non_unital_subsemiring R)) : f = g := fun_like.ext _ _ (λ x, h trivial) lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : F} (h : s.eq_on (f : R → S) (g : R → S)) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : F) (s : set S) : closure ((f : R → S) ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : F) (s : set R) : (closure s).map f = closure ((f : R → S) '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end non_unital_ring_hom namespace non_unital_subsemiring open non_unital_ring_hom non_unital_subsemiring_class /-- The non-unital ring homomorphism associated to an inclusion of non-unital subsemirings. -/ def inclusion {S T : non_unital_subsemiring R} (h : S ≤ T) : S →ₙ+* T := cod_restrict (subtype S) _ (λ x, h x.2) @[simp] lemma srange_subtype (s : non_unital_subsemiring R) : (subtype s).srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := non_unital_ring_hom.srange_top_of_surjective (fst R S) prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := non_unital_ring_hom.srange_top_of_surjective (snd R S) $ prod.snd_surjective end non_unital_subsemiring namespace ring_equiv open non_unital_ring_hom non_unital_subsemiring_class variables {s t : non_unital_subsemiring R} variables {F : Type*} [non_unital_ring_hom_class F R S] /-- Makes the identity isomorphism from a proof two non-unital subsemirings of a multiplicative monoid are equal. -/ def non_unital_subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a non-unital ring homomorphism with a left inverse to a ring isomorphism to its `non_unital_ring_hom.srange`. -/ def sof_left_inverse' {g : S → R} {f : F} (h : function.left_inverse g f) : R ≃+* srange f := { to_fun := srange_restrict f, inv_fun := λ x, g (subtype (srange f) x), left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := non_unital_ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..(srange_restrict f) } @[simp] lemma sof_left_inverse'_apply {g : S → R} {f : F} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse' h x) = f x := rfl @[simp] lemma sof_left_inverse'_symm_apply {g : S → R} {f : F} (h : function.left_inverse g f) (x : srange f) : (sof_left_inverse' h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of non-unital semirings and a non-unital subsemiring `s` of `R`, `non_unital_subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def non_unital_subsemiring_map (e : R ≃+* S) (s : non_unital_subsemiring R) : s ≃+* non_unital_subsemiring.map e.to_non_unital_ring_hom s := { ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid, ..e.to_mul_equiv.subsemigroup_map s.to_subsemigroup } end ring_equiv
9f2dedb69eab014be2adcbc551b3a052fc10ad86
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/native/config.lean
ab22bea2495b4cd11e0af01606fe7b87b2cfb16f
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
294
lean
/- Copyright (c) 2016 Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch -/ prelude import init.data.bool.basic namespace native -- eventually expose all the options here structure config := (debug : bool) end native
8cf5409dbf7c368b72c589a7771c2831af9106b3
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/offsetIssue.lean
7bbc89a73d919ba0dce8f7364ea50d4292253465
[ "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
438
lean
def BV (n : Nat) := { a : Array Bool // a.size = n } axiom foo {n m : Nat} (a : BV n) (b : BV m) : BV (n - m) def test (x1 : BV 30002) (x2 : BV 30001) (y1 : BV 60004) (y2 : BV 60003) : Prop := foo x1 x2 = without_expected_type foo y1 y2 @[elabWithoutExpectedType] axiom foo2 {n m : Nat} (a : BV n) (b : BV m) : BV (n - m) def test2 (x1 : BV 30002) (x2 : BV 30001) (y1 : BV 60004) (y2 : BV 60003) : Prop := foo2 x1 x2 = foo2 y1 y2
8774dc630b196e41af7e0ebcd6976d6112b682de
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/mul_zero.lean
a6c4e71a472e973b7b5d84e2568b397ec74ba73b
[ "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
89
lean
import data.nat open nat example (x : ℕ) : 0 = x * 0 := calc 0 = x * 0 : nat.mul_zero
679521cc902b19286a7f285ffcb4cf22c4d4bf1c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/list/chain.lean
286d204d5765653492fe5564bea3f26e740e3205
[ "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
10,578
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Yury Kudryashov -/ import data.list.pairwise import logic.relation universes u v open nat variables {α : Type u} {β : Type v} namespace list /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ mk_iff_of_inductive_prop list.chain list.chain_iff variable {R : α → α → Prop} 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} (HRS : ∀ ⦃a b⦄, R a b → S a b) {a b : α} (Hab : ∀ ⦃c⦄, R a c → S b c) {l : list α} (p : chain R a l) : chain S b l := by induction p with _ a c l r p IH generalizing b; constructor; [exact Hab r, exact IH (@HRS _)] 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 := p.imp' H (H a) 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 {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 only [chain_cons, chain.nil, and_true] 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 only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, 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 only [map, chain.nil, chain_cons, *] 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, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, 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, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain_iff_nth_le {R} : ∀ {a : α} {l : list α}, chain R a l ↔ (∀ h : 0 < length l, R a (nth_le l 0 h)) ∧ (∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h))) | a [] := by simp | a (b :: t) := begin rw [chain_cons, chain_iff_nth_le], split, { rintros ⟨R, ⟨h0, h⟩⟩, split, { intro w, exact R, }, { intros i w, cases i, { apply h0, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, exact lt_pred_iff.mpr w, } } }, { rintros ⟨h0, h⟩, split, { apply h0, simp, }, { split, { apply h 0, }, { intros i w, convert h (i+1) _, exact lt_pred_iff.mp w, } } }, end theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ @[simp] theorem chain'_nil : chain' R [] := trivial @[simp] theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R 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)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem pairwise.chain' : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr @[simp] theorem chain'_cons {x y l} : chain' R (x :: y :: l) ↔ R x y ∧ chain' R (y :: l) := chain_cons theorem chain'.cons {x y l} (h₁ : R x y) (h₂ : chain' R (y :: l)) : chain' R (x :: y :: l) := chain'_cons.2 ⟨h₁, h₂⟩ theorem chain'.tail : ∀ {l} (h : chain' R l), chain' R l.tail | [] _ := trivial | [x] _ := trivial | (x :: y :: l) h := (chain'_cons.mp h).right theorem chain'.rel_head {x y l} (h : chain' R (x :: y :: l)) : R x y := rel_of_chain_cons h theorem chain'.rel_head' {x l} (h : chain' R (x :: l)) ⦃y⦄ (hy : y ∈ head' l) : R x y := by { rw ← cons_head'_tail hy at h, exact h.rel_head } theorem chain'.cons' {x} : ∀ {l : list α}, chain' R l → (∀ y ∈ l.head', R x y) → chain' R (x :: l) | [] _ _ := chain'_singleton x | (a :: l) hl H := hl.cons $ H _ rfl theorem chain'_cons' {x l} : chain' R (x :: l) ↔ (∀ y ∈ head' l, R x y) ∧ chain' R l := ⟨λ h, ⟨h.rel_head', h.tail⟩, λ ⟨h₁, h₂⟩, h₂.cons' h₁⟩ theorem chain'.append : ∀ {l₁ l₂ : list α} (h₁ : chain' R l₁) (h₂ : chain' R l₂) (h : ∀ (x ∈ l₁.last') (y ∈ l₂.head'), R x y), chain' R (l₁ ++ l₂) | [] l₂ h₁ h₂ h := h₂ | [a] l₂ h₁ h₂ h := h₂.cons' $ h _ rfl | (a::b::l) l₂ h₁ h₂ h := begin simp only [last'] at h, have : chain' R (b::l) := h₁.tail, exact (this.append h₂ h).cons h₁.rel_head end theorem chain'_pair {x y} : chain' R [x, y] ↔ R x y := by simp only [chain'_singleton, chain'_cons, and_true] theorem chain'.imp_head {x y} (h : ∀ {z}, R x z → R y z) {l} (hl : chain' R (x :: l)) : chain' R (y :: l) := hl.tail.cons' $ λ z hz, h $ hl.rel_head' hz theorem chain'_reverse : ∀ {l}, chain' R (reverse l) ↔ chain' (flip R) l | [] := iff.rfl | [a] := by simp only [chain'_singleton, reverse_singleton] | (a :: b :: l) := by rw [chain'_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, chain'_split, ← reverse_cons, @chain'_reverse (b :: l), and_comm, chain'_pair, flip] theorem chain'_iff_nth_le {R} : ∀ {l : list α}, chain' R l ↔ ∀ i (h : i < length l - 1), R (nth_le l i (lt_of_lt_pred h)) (nth_le l (i+1) (lt_pred_iff.mp h)) | [] := by simp | (a :: nil) := by simp | (a :: b :: t) := begin rw [chain'_cons, chain'_iff_nth_le], split, { rintros ⟨R, h⟩ i w, cases i, { exact R, }, { convert h i _ using 1, simp only [succ_eq_add_one, add_succ_sub_one, add_zero, length, add_lt_add_iff_right] at w, simpa using w, }, }, { rintros h, split, { apply h 0, simp, }, { intros i w, convert h (i+1) _, simp only [add_zero, length, add_succ_sub_one] at w, simpa using w, } }, end /-- If `l₁ l₂` and `l₃` are lists and `l₁ ++ l₂` and `l₂ ++ l₃` both satisfy `chain' R`, then so does `l₁ ++ l₂ ++ l₃` provided `l₂ ≠ []` -/ lemma chain'.append_overlap : ∀ {l₁ l₂ l₃ : list α} (h₁ : chain' R (l₁ ++ l₂)) (h₂ : chain' R (l₂ ++ l₃)) (hn : l₂ ≠ []), chain' R (l₁ ++ l₂ ++ l₃) | [] l₂ l₃ h₁ h₂ hn := h₂ | l₁ [] l₃ h₁ h₂ hn := (hn rfl).elim | [a] (b::l₂) l₃ h₁ h₂ hn := by { simp at *, tauto } | (a::b::l₁) (c::l₂) l₃ h₁ h₂ hn := begin simp only [cons_append, chain'_cons] at h₁ h₂ ⊢, simp only [← cons_append] at h₁ h₂ ⊢, exact ⟨h₁.1, chain'.append_overlap h₁.2 h₂ (cons_ne_nil _ _)⟩ end /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is a `r`-chain starting from `a` and ending on `b`. -/ lemma exists_chain_of_relation_refl_trans_gen {r : α → α → Prop} {a b : α} (h : relation.refl_trans_gen r a b) : ∃ l, chain r a l ∧ last (a :: l) (cons_ne_nil _ _) = b := begin apply relation.refl_trans_gen.head_induction_on h, { exact ⟨[], chain.nil, rfl⟩ }, { intros c d e t ih, obtain ⟨l, hl₁, hl₂⟩ := ih, refine ⟨d :: l, chain.cons e hl₁, _⟩, rwa last_cons_cons } end /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y → p y → p x` then the predicate is true at `a`. That is, we can propagate the predicate up the chain. -/ lemma chain.induction {r : α → α → Prop} (p : α → Prop) {a b : α} (l : list α) (h : chain r a l) (hb : last (a :: l) (cons_ne_nil _ _) = b) (carries : ∀ {x y : α}, r x y → p y → p x) (final : p b) : p a := begin induction l generalizing a, { cases hb, exact final }, { rw chain_cons at h, apply carries h.1 (l_ih h.2 hb) } end end list
34d1c29f1e034595f0dd879ba869b7d2b059d57f
367134ba5a65885e863bdc4507601606690974c1
/src/topology/extend_from_subset.lean
6854109e48afbaba0044ee34103694393b1317ac
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
4,044
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Anatole Dedecker -/ import topology.separation /-! # Extending a function from a subset The main definition of this file is `extend_from A f` where `f : X → Y` and `A : set X`. This defines a new function `g : X → Y` which maps any `x₀ : X` to the limit of `f` as `x` tends to `x₀`, if such a limit exists. This is analoguous to the way `dense_inducing.extend` "extends" a function `f : X → Z` to a function `g : Y → Z` along a dense inducing `i : X → Y`. The main theorem we prove about this definition is `continuous_on_extend_from` which states that, for `extend_from A f` to be continuous on a set `B ⊆ closure A`, it suffices that `f` converges within `A` at any point of `B`, provided that `f` is a function to a regular space. -/ noncomputable theory open_locale topological_space open filter set variables {X Y : Type*} [topological_space X] [topological_space Y] /-- Extend a function from a set `A`. The resulting function `g` is such that at any `x₀`, if `f` converges to some `y` as `x` tends to `x₀` within `A`, then `g x₀` is defined to be one of these `y`. Else, `g x₀` could be anything. -/ def extend_from (A : set X) (f : X → Y) : X → Y := λ x, @@lim _ ⟨f x⟩ (𝓝[A] x) f /-- If `f` converges to some `y` as `x` tends to `x₀` within `A`, then `f` tends to `extend_from A f x` as `x` tends to `x₀`. -/ lemma tendsto_extend_from {A : set X} {f : X → Y} {x : X} (h : ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : tendsto f (𝓝[A] x) (𝓝 $ extend_from A f x) := tendsto_nhds_lim h lemma extend_from_eq [t2_space Y] {A : set X} {f : X → Y} {x : X} {y : Y} (hx : x ∈ closure A) (hf : tendsto f (𝓝[A] x) (𝓝 y)) : extend_from A f x = y := begin haveI := mem_closure_iff_nhds_within_ne_bot.mp hx, exact tendsto_nhds_unique (tendsto_nhds_lim ⟨y, hf⟩) hf, end lemma extend_from_extends [t2_space Y] {f : X → Y} {A : set X} (hf : continuous_on f A) : ∀ x ∈ A, extend_from A f x = f x := λ x x_in, extend_from_eq (subset_closure x_in) (hf x x_in) /-- If `f` is a function to a regular space `Y` which has a limit within `A` at any point of a set `B ⊆ closure A`, then `extend_from A f` is continuous on `B`. -/ lemma continuous_on_extend_from [regular_space Y] {f : X → Y} {A B : set X} (hB : B ⊆ closure A) (hf : ∀ x ∈ B, ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : continuous_on (extend_from A f) B := begin set φ := extend_from A f, intros x x_in, suffices : ∀ V' ∈ 𝓝 (φ x), is_closed V' → φ ⁻¹' V' ∈ 𝓝[B] x, by simpa [continuous_within_at, (closed_nhds_basis _).tendsto_right_iff], intros V' V'_in V'_closed, obtain ⟨V, V_in, V_op, hV⟩ : ∃ V ∈ 𝓝 x, is_open V ∧ V ∩ A ⊆ f ⁻¹' V', { have := tendsto_extend_from (hf x x_in), rcases (nhds_within_basis_open x A).tendsto_left_iff.mp this V' V'_in with ⟨V, ⟨hxV, V_op⟩, hV⟩, use [V, mem_nhds_sets V_op hxV, V_op, hV] }, suffices : ∀ y ∈ V ∩ B, φ y ∈ V', from mem_sets_of_superset (inter_mem_inf_sets V_in $ mem_principal_self B) this, rintros y ⟨hyV, hyB⟩, haveI := mem_closure_iff_nhds_within_ne_bot.mp (hB hyB), have limy : tendsto f (𝓝[A] y) (𝓝 $ φ y) := tendsto_extend_from (hf y hyB), have hVy : V ∈ 𝓝 y := mem_nhds_sets V_op hyV, have : V ∩ A ∈ (𝓝[A] y), by simpa [inter_comm] using inter_mem_nhds_within _ hVy, exact V'_closed.mem_of_tendsto limy (mem_sets_of_superset this hV) end /-- If a function `f` to a regular space `Y` has a limit within a dense set `A` for any `x`, then `extend_from A f` is continuous. -/ lemma continuous_extend_from [regular_space Y] {f : X → Y} {A : set X} (hA : dense A) (hf : ∀ x, ∃ y, tendsto f (𝓝[A] x) (𝓝 y)) : continuous (extend_from A f) := begin rw continuous_iff_continuous_on_univ, exact continuous_on_extend_from (λ x _, hA x) (by simpa using hf) end
32d08798f20b02551e4de4a80e5c582296cce838
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world2/level4.lean
3102493a5197d321a6ad2386bbfc80f3e94de66e
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
902
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level3 -- hide namespace mynat -- hide /- # Addition World ## Level 4: `add_comm` (boss level) [boss battle music] Look in Theorem statements -> Addition world to see the proofs you have. These should be enough. -/ /- 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 [nat_num_game] induction b with d hd, { 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 make a choice: Multiplication World or Function World. But there are just a couple more useful lemmas in Addition World which you should prove first. Press on to level 5. -/ end mynat -- hide
5383d3c02c96dbe575e03a71c570f2175fbd4d64
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tmp/new-frontend/parser/term.lean
a92f69cbccb4e6382cd75a90c387e50a18d81076
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
14,106
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich Term-Level parsers -/ prelude import init.lean.parser.level init.lean.parser.notation import init.lean.expr namespace Lean namespace Parser open Combinators Parser.HasView MonadParsec local postfix `?`:10000 := optional local postfix *:10000 := Combinators.many local postfix +:10000 := Combinators.many1 set_option class.instance_max_depth 200 @[derive Parser.HasTokens Parser.HasView] def identUnivSpec.Parser : basicParser := node! identUnivSpec [".{", levels: Level.Parser+, "}"] @[derive Parser.HasTokens Parser.HasView] def identUnivs.Parser : termParser := node! identUnivs [id: ident.Parser, univs: (monadLift identUnivSpec.Parser)?] namespace Term /-- Access leading Term -/ def getLeading : trailingTermParser := read instance : HasTokens getLeading := default _ instance : HasView Syntax getLeading := default _ @[derive Parser.HasTokens Parser.HasView] def paren.Parser : termParser := node! «paren» ["(":maxPrec, content: node! parenContent [ Term: Term.Parser, special: nodeChoice! parenSpecial { /- Do not allow trailing comma. Looks a bit weird and would clash with adding support for tuple sections (https://downloads.haskell.org/~ghc/8.2.1/docs/html/usersGuide/glasgowExts.html#tuple-sections). -/ tuple: node! tuple [", ", tail: sepBy (Term.Parser 0) (symbol ", ") false], typed: node! typed [" : ", type: Term.Parser], }?, ]?, ")" ] @[derive Parser.HasTokens Parser.HasView] def hole.Parser : termParser := node! hole [hole: symbol "_" maxPrec] @[derive Parser.HasTokens Parser.HasView] def sort.Parser : termParser := nodeChoice! sort {"Sort":maxPrec, "Type":maxPrec} @[derive HasTokens HasView] def typeSpec.Parser : termParser := node! typeSpec [" : ", type: Term.Parser 0] @[derive HasTokens HasView] def optType.Parser : termParser := typeSpec.Parser? instance optType.viewDefault : HasViewDefault optType.Parser _ none := ⟨⟩ section binder @[derive HasTokens HasView] def binderIdent.Parser : termParser := nodeChoice! binderIdent {id: ident.Parser, hole: hole.Parser} @[derive HasTokens HasView] def binderDefault.Parser : termParser := nodeChoice! binderDefault { val: node! binderDefaultVal [":=", Term: Term.Parser 0], tac: node! binderDefaultTac [".", Term: Term.Parser 0], } @[derive HasTokens HasView] def binderContent.Parser (requireType := false) : termParser := node! binderContent [ ids: binderIdent.Parser+, type: optional typeSpec.Parser requireType, default: binderDefault.Parser? ] @[derive HasTokens HasView] def simpleBinder.Parser : termParser := nodeChoice! simpleBinder { explicit: node! simpleExplicitBinder ["(", id: ident.Parser, " : ", type: Term.Parser 0, right: symbol ")"], implicit: node! simpleImplicitBinder ["{", id: ident.Parser, " : ", type: Term.Parser 0, right: symbol "}"], strictImplicit: node! simpleStrictImplicitBinder ["⦃", id: ident.Parser, " : ", type: Term.Parser 0, right: symbol "⦄"], instImplicit: node! simpleInstImplicitBinder ["[", id: ident.Parser, " : ", type: Term.Parser 0, right: symbol "]"], } def simpleBinder.View.toBinderInfo : simpleBinder.View → (BinderInfo × SyntaxIdent × Syntax) | (simpleBinder.View.explicit {id := id, type := type}) := (BinderInfo.default, id, type) | (simpleBinder.View.implicit {id := id, type := type}) := (BinderInfo.implicit, id, type) | (simpleBinder.View.strictImplicit {id := id, type := type}) := (BinderInfo.strictImplicit, id, type) | (simpleBinder.View.instImplicit {id := id, type := type}) := (BinderInfo.instImplicit, id, type) @[derive Parser.HasTokens Parser.HasView] def anonymousConstructor.Parser : termParser := node! anonymousConstructor ["⟨":maxPrec, args: sepBy (Term.Parser 0) (symbol ","), "⟩"] /- All binders must be surrounded with some kind of bracket. (e.g., '()', '{}', '[]'). We use this feature when parsing examples/definitions/theorems. The goal is to avoid counter-intuitive declarations such as: example p : False := trivial def main proof : False := trivial which would be parsed as example (p : False) : _ := trivial def main (proof : False) : _ := trivial where `_` in both cases is elaborated into `True`. This issue was raised by @gebner in the slack channel. Remark: we still want implicit delimiters for lambda/pi expressions. That is, we want to write fun x : t, s or fun x, s instead of fun (x : t), s -/ @[derive HasTokens HasView] def bracketedBinder.Parser (requireType := false) : termParser := nodeChoice! bracketedBinder { explicit: node! explicitBinder ["(", content: nodeChoice! explicitBinderContent { «notation»: command.notationLike.Parser, other: binderContent.Parser requireType }, right: symbol ")"], implicit: node! implicitBinder ["{", content: binderContent.Parser, "}"], strictImplicit: node! strictImplicitBinder ["⦃", content: binderContent.Parser, "⦄"], instImplicit: node! instImplicitBinder ["[", content: nodeLongestChoice! instImplicitBinderContent { named: node! instImplicitNamedBinder [id: ident.Parser, " : ", type: Term.Parser 0], anonymous: node! instImplicitAnonymousBinder [type: Term.Parser 0] }, "]"], anonymousConstructor: anonymousConstructor.Parser, } @[derive HasTokens HasView] def binder.Parser : termParser := nodeChoice! binder { bracketed: bracketedBinder.Parser, unbracketed: binderContent.Parser, } @[derive HasTokens HasView] def bindersExt.Parser : termParser := node! bindersExt [ leadingIds: binderIdent.Parser*, remainder: nodeChoice! bindersRemainder { type: node! bindersTypes [":", type: Term.Parser 0], -- we allow mixing like in `a (b : β) c`, but not `a : α (b : β) c : γ` mixed: nodeChoice! mixedBinder { bracketed: bracketedBinder.Parser, id: binderIdent.Parser, }+, }? ] /-- We normalize binders to simpler singleton ones during expansion. -/ @[derive HasTokens HasView] def binders.Parser : termParser := nodeChoice! binders { extended: bindersExt.Parser, -- a strict subset of `extended`, so only useful after parsing simple: simpleBinder.Parser, } /-- We normalize binders to simpler ones during expansion. These always-bracketed binders are used in declarations and cannot be reduced to nested singleton binders. -/ @[derive HasTokens HasView] def bracketedBinders.Parser : termParser := nodeChoice! bracketedBinders { extended: bracketedBinder.Parser*, -- a strict subset of `extended`, so only useful after parsing simple: simpleBinder.Parser*, } end binder @[derive Parser.HasTokens Parser.HasView] def lambda.Parser : termParser := node! lambda [ op: unicodeSymbol "λ" "fun" maxPrec, binders: binders.Parser, ",", body: Term.Parser 0 ] @[derive Parser.HasTokens Parser.HasView] def assume.Parser : termParser := node! «assume» [ "assume ":maxPrec, binders: nodeChoice! assumeBinders { anonymous: node! assumeAnonymous [": ", type: Term.Parser], binders: binders.Parser }, ", ", body: Term.Parser 0 ] @[derive Parser.HasTokens Parser.HasView] def pi.Parser : termParser := node! pi [ op: anyOf [unicodeSymbol "Π" "Pi" maxPrec, unicodeSymbol "∀" "forall" maxPrec], binders: binders.Parser, ",", range: Term.Parser 0 ] @[derive Parser.HasTokens Parser.HasView] def explicit.Parser : termParser := node! explicit [ mod: nodeChoice! explicitModifier { explicit: symbol "@" maxPrec, partialExplicit: symbol "@@" maxPrec }, id: identUnivs.Parser ] @[derive Parser.HasTokens Parser.HasView] def from.Parser : termParser := node! «from» ["from ", proof: Term.Parser] @[derive Parser.HasTokens Parser.HasView] def let.Parser : termParser := node! «let» [ "let ", lhs: nodeChoice! letLhs { id: node! letLhsId [ id: ident.Parser, -- NOTE: after expansion, binders are Empty binders: bracketedBinder.Parser*, type: optType.Parser, ], pattern: Term.Parser }, " := ", value: Term.Parser, " in ", body: Term.Parser, ] @[derive Parser.HasTokens Parser.HasView] def optIdent.Parser : termParser := (try node! optIdent [id: ident.Parser, " : "])? @[derive Parser.HasTokens Parser.HasView] def have.Parser : termParser := node! «have» [ "have ", id: optIdent.Parser, prop: Term.Parser, proof: nodeChoice! haveProof { Term: node! haveTerm [" := ", Term: Term.Parser], «from»: node! haveFrom [", ", «from»: from.Parser], }, ", ", body: Term.Parser, ] @[derive Parser.HasTokens Parser.HasView] def show.Parser : termParser := node! «show» [ "show ", prop: Term.Parser, ", ", «from»: from.Parser, ] @[derive Parser.HasTokens Parser.HasView] def match.Parser : termParser := node! «match» [ "match ", scrutinees: sepBy1 Term.Parser (symbol ", ") false, type: optType.Parser, " with ", optBar: (symbol " | ")?, equations: sepBy1 node! «matchEquation» [ lhs: sepBy1 Term.Parser (symbol ", ") false, ":=", rhs: Term.Parser] (symbol " | ") false, ] @[derive Parser.HasTokens Parser.HasView] def if.Parser : termParser := node! «if» [ "if ", id: optIdent.Parser, prop: Term.Parser, " then ", thenBranch: Term.Parser, " else ", elseBranch: Term.Parser, ] @[derive Parser.HasTokens Parser.HasView] def structInst.Parser : termParser := node! structInst [ "{":maxPrec, type: (try node! structInstType [id: ident.Parser, " . "])?, «with»: (try node! structInstWith [source: Term.Parser, " with "])?, items: sepBy nodeChoice! structInstItem { field: node! structInstField [id: ident.Parser, " := ", val: Term.Parser], source: node! structInstSource ["..", source: Term.Parser?], } (symbol ", "), "}", ] @[derive Parser.HasTokens Parser.HasView] def Subtype.Parser : termParser := node! Subtype [ "{":maxPrec, id: ident.Parser, type: optType.Parser, "//", prop: Term.Parser, "}" ] @[derive Parser.HasTokens Parser.HasView] def inaccessible.Parser : termParser := node! inaccessible [".(":maxPrec, Term: Term.Parser, ")"] @[derive Parser.HasTokens Parser.HasView] def anonymousInaccessible.Parser : termParser := node! anonymousInaccessible ["._":maxPrec] @[derive Parser.HasTokens Parser.HasView] def sorry.Parser : termParser := node! «sorry» ["sorry":maxPrec] def borrowPrec := maxPrec - 1 @[derive Parser.HasTokens Parser.HasView] def borrowed.Parser : termParser := node! borrowed ["@&":maxPrec, Term: Term.Parser borrowPrec] --- Agda's `(x : e) → f` @[derive Parser.HasTokens Parser.HasView] def depArrow.Parser : termParser := node! depArrow [binder: bracketedBinder.Parser true, op: unicodeSymbol "→" "->" 25, range: Term.Parser 24] -- TODO(Sebastian): replace with attribute @[derive HasTokens] def builtinLeadingParsers : TokenMap termParser := TokenMap.ofList [ (`ident, identUnivs.Parser), (number.name, number.Parser), (stringLit.name, stringLit.Parser), ("(", paren.Parser), ("(", depArrow.Parser), ("_", hole.Parser), ("Sort", sort.Parser), ("Type", sort.Parser), ("λ", lambda.Parser), ("fun", lambda.Parser), ("Π", pi.Parser), ("Pi", pi.Parser), ("∀", pi.Parser), ("forall", pi.Parser), ("⟨", anonymousConstructor.Parser), ("@", explicit.Parser), ("@@", explicit.Parser), ("let", let.Parser), ("have", have.Parser), ("show", show.Parser), ("assume", assume.Parser), ("match", match.Parser), ("if", if.Parser), ("{", structInst.Parser), ("{", Subtype.Parser), ("{", depArrow.Parser), ("[", depArrow.Parser), (".(", inaccessible.Parser), ("._", anonymousInaccessible.Parser), ("sorry", sorry.Parser), ("@&", borrowed.Parser) ] @[derive Parser.HasTokens Parser.HasView] def sortApp.Parser : trailingTermParser := do { l ← getLeading, guard $ l.isOfKind sort } *> node! sortApp [fn: getLeading, Arg: monadLift (Level.Parser maxPrec).run] @[derive Parser.HasTokens Parser.HasView] def app.Parser : trailingTermParser := node! app [fn: getLeading, Arg: Term.Parser maxPrec] def mkApp (fn : Syntax) (args : List Syntax) : Syntax := args.foldl (λ fn Arg, Syntax.mkNode app [fn, Arg]) fn @[derive Parser.HasTokens Parser.HasView] def arrow.Parser : trailingTermParser := node! arrow [dom: getLeading, op: unicodeSymbol "→" "->" 25, range: Term.Parser 24] @[derive Parser.HasView] def projection.Parser : trailingTermParser := try $ node! projection [ Term: getLeading, -- do not consume trailing whitespace «.»: rawStr ".", proj: nodeChoice! projectionSpec { id: Parser.ident.Parser, num: number.Parser, }, ] -- register '.' manually because of `rawStr` instance projection.tokens : HasTokens projection.Parser := /- Use maxPrec + 1 so that it bind more tightly than application: `a (b).c` should be parsed as `a ((b).c)`. -/ ⟨[{«prefix» := ".", lbp := maxPrec.succ}]⟩ @[derive HasTokens] def builtinTrailingParsers : TokenMap trailingTermParser := TokenMap.ofList [ ("→", arrow.Parser), ("->", arrow.Parser), (".", projection.Parser) ] end Term private def trailing (cfg : CommandParserConfig) : trailingTermParser := -- try local parsers first, starting with the newest one (do ps ← indexed cfg.localTrailingTermParsers, ps.foldr (<|>) (error "")) <|> -- next try all non-local parsers (do ps ← indexed cfg.trailingTermParsers, longestMatch ps) <|> -- The application parsers should only be tried as a fall-back; -- e.g. `a + b` should not be parsed as `a (+ b)`. -- TODO(Sebastian): We should be able to remove this workaround using -- the proposed more robust precedence handling anyOf [Term.sortApp.Parser, Term.app.Parser] private def leading (cfg : CommandParserConfig) : termParser := (do ps ← indexed cfg.localLeadingTermParsers, ps.foldr (<|>) (error "")) <|> (do ps ← indexed cfg.leadingTermParsers, longestMatch ps) def termParser.run (p : termParser) : commandParser := do cfg ← read, adaptReader coe $ prattParser (leading cfg) (trailing cfg) p end Parser end Lean
ee371463ea204cfc3dc2c82ee36629f4d95d97ef
4727251e0cd73359b15b664c3170e5d754078599
/src/model_theory/semantics.lean
494106eacdb121089e3bdf5b80308fec2f9b910e
[ "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
31,764
lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import data.finset.basic import model_theory.syntax /-! # Basics on First-Order Semantics This file defines the interpretations of first-order terms, formulas, sentences, and theories in a style inspired by the [Flypitch project](https://flypitch.github.io/). ## Main Definitions * `first_order.language.term.realize` is defined so that `t.realize v` is the term `t` evaluated at variables `v`. * `first_order.language.bounded_formula.realize` is defined so that `φ.realize v xs` is the bounded formula `φ` evaluated at tuples of variables `v` and `xs`. * `first_order.language.formula.realize` is defined so that `φ.realize v` is the formula `φ` evaluated at variables `v`. * `first_order.language.sentence.realize` is defined so that `φ.realize M` is the sentence `φ` evaluated in the structure `M`. Also denoted `M ⊨ φ`. * `first_order.language.Theory.model` is defined so that `T.model M` is true if and only if every sentence of `T` is realized in `M`. Also denoted `T ⊨ φ`. ## Main Results * `first_order.language.bounded_formula.realize_to_prenex` shows that the prenex normal form of a formula has the same realization as the original formula. * Several results in this file show that syntactic constructions such as `relabel`, `cast_le`, `lift_at`, `subst`, and the actions of language maps commute with realization of terms, formulas, sentences, and theories. ## Implementation Notes * Formulas use a modified version of de Bruijn variables. Specifically, a `L.bounded_formula α n` is a formula with some variables indexed by a type `α`, which cannot be quantified over, and some indexed by `fin n`, which can. For any `φ : L.bounded_formula α (n + 1)`, we define the formula `∀' φ : L.bounded_formula α n` by universally quantifying over the variable indexed by `n : fin (n + 1)`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universes u v w u' v' namespace first_order namespace language variables {L : language.{u v}} {L' : language} variables {M : Type w} {N P : Type*} [L.Structure M] [L.Structure N] [L.Structure P] variables {α : Type u'} {β : Type v'} open_locale first_order cardinal open Structure cardinal fin namespace term /-- A term `t` with variables indexed by `α` can be evaluated by giving a value to each variable. -/ @[simp] def realize (v : α → M) : ∀ (t : L.term α), M | (var k) := v k | (func f ts) := fun_map f (λ i, (ts i).realize) @[simp] lemma realize_relabel {t : L.term α} {g : α → β} {v : β → M} : (t.relabel g).realize v = t.realize (v ∘ g) := begin induction t with _ n f ts ih, { refl, }, { simp [ih] } end @[simp] lemma realize_lift_at {n n' m : ℕ} {t : L.term (α ⊕ fin n)} {v : (α ⊕ fin (n + n')) → M} : (t.lift_at n' m).realize v = t.realize (v ∘ (sum.map id (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i))) := realize_relabel @[simp] lemma realize_constants {c : L.constants} {v : α → M} : c.term.realize v = c := fun_map_eq_coe_constants @[simp] lemma realize_functions_apply₁ {f : L.functions 1} {t : L.term α} {v : α → M} : (f.apply₁ t).realize v = fun_map f ![t.realize v] := begin rw [functions.apply₁, term.realize], refine congr rfl (funext (λ i, _)), simp only [matrix.cons_val_fin_one], end @[simp] lemma realize_functions_apply₂ {f : L.functions 2} {t₁ t₂ : L.term α} {v : α → M} : (f.apply₂ t₁ t₂).realize v = fun_map f ![t₁.realize v, t₂.realize v] := begin rw [functions.apply₂, term.realize], refine congr rfl (funext (fin.cases _ _)), { simp only [matrix.cons_val_zero], }, { simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] } end lemma realize_con {A : set M} {a : A} {v : α → M} : (L.con a).term.realize v = a := rfl @[simp] lemma realize_subst {t : L.term α} {tf : α → L.term β} {v : β → M} : (t.subst tf).realize v = t.realize (λ a, (tf a).realize v) := begin induction t with _ _ _ _ ih, { refl }, { simp [ih] } end @[simp] lemma realize_restrict_var [decidable_eq α] {t : L.term α} {s : set α} (h : ↑t.var_finset ⊆ s) {v : α → M} : (t.restrict_var (set.inclusion h)).realize (v ∘ coe) = t.realize v := begin induction t with _ _ _ _ ih, { refl }, { simp_rw [var_finset, finset.coe_bUnion, set.Union_subset_iff] at h, exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) }, end @[simp] lemma realize_restrict_var_left [decidable_eq α] {γ : Type*} {t : L.term (α ⊕ γ)} {s : set α} (h : ↑t.var_finset_left ⊆ s) {v : α → M} {xs : γ → M} : (t.restrict_var_left (set.inclusion h)).realize (sum.elim (v ∘ coe) xs) = t.realize (sum.elim v xs) := begin induction t with a _ _ _ ih, { cases a; refl }, { simp_rw [var_finset_left, finset.coe_bUnion, set.Union_subset_iff] at h, exact congr rfl (funext (λ i, ih i (h i (finset.mem_univ i)))) }, end end term namespace Lhom @[simp] lemma realize_on_term [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] (t : L.term α) (v : α → M) : (φ.on_term t).realize v = t.realize v := begin induction t with _ n f ts ih, { refl }, { simp only [term.realize, Lhom.on_term, Lhom.is_expansion_on.map_on_function, ih] } end end Lhom @[simp] lemma hom.realize_term (g : M →[L] N) {t : L.term α} {v : α → M} : t.realize (g ∘ v) = g (t.realize v) := begin induction t, { refl }, { rw [term.realize, term.realize, g.map_fun], refine congr rfl _, ext x, simp [t_ih x], }, end @[simp] lemma embedding.realize_term {v : α → M} (t : L.term α) (g : M ↪[L] N) : t.realize (g ∘ v) = g (t.realize v) := g.to_hom.realize_term @[simp] lemma equiv.realize_term {v : α → M} (t : L.term α) (g : M ≃[L] N) : t.realize (g ∘ v) = g (t.realize v) := g.to_hom.realize_term variables {L} {α} {n : ℕ} namespace bounded_formula open term /-- A bounded formula can be evaluated as true or false by giving values to each free variable. -/ def realize : ∀ {l} (f : L.bounded_formula α l) (v : α → M) (xs : fin l → M), Prop | _ falsum v xs := false | _ (bounded_formula.equal t₁ t₂) v xs := t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs) | _ (bounded_formula.rel R ts) v xs := rel_map R (λ i, (ts i).realize (sum.elim v xs)) | _ (bounded_formula.imp f₁ f₂) v xs := realize f₁ v xs → realize f₂ v xs | _ (bounded_formula.all f) v xs := ∀(x : M), realize f v (snoc xs x) variables {l : ℕ} {φ ψ : L.bounded_formula α l} {θ : L.bounded_formula α l.succ} variables {v : α → M} {xs : fin l → M} @[simp] lemma realize_bot : (⊥ : L.bounded_formula α l).realize v xs ↔ false := iff.rfl @[simp] lemma realize_not : φ.not.realize v xs ↔ ¬ φ.realize v xs := iff.rfl @[simp] lemma realize_bd_equal (t₁ t₂ : L.term (α ⊕ fin l)) : (t₁.bd_equal t₂).realize v xs ↔ (t₁.realize (sum.elim v xs) = t₂.realize (sum.elim v xs)) := iff.rfl @[simp] lemma realize_top : (⊤ : L.bounded_formula α l).realize v xs ↔ true := by simp [has_top.top] @[simp] lemma realize_inf : (φ ⊓ ψ).realize v xs ↔ (φ.realize v xs ∧ ψ.realize v xs) := by simp [has_inf.inf, realize] @[simp] lemma realize_foldr_inf (l : list (L.bounded_formula α n)) (v : α → M) (xs : fin n → M) : (l.foldr (⊓) ⊤).realize v xs ↔ ∀ φ ∈ l, bounded_formula.realize φ v xs := begin induction l with φ l ih, { simp }, { simp [ih] } end @[simp] lemma realize_imp : (φ.imp ψ).realize v xs ↔ (φ.realize v xs → ψ.realize v xs) := by simp only [realize] @[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term _} : (R.bounded_formula ts).realize v xs ↔ rel_map R (λ i, (ts i).realize (sum.elim v xs)) := iff.rfl @[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} : (R.bounded_formula₁ t).realize v xs ↔ rel_map R ![t.realize (sum.elim v xs)] := begin rw [relations.bounded_formula₁, realize_rel, iff_eq_eq], refine congr rfl (funext (λ _, _)), simp only [matrix.cons_val_fin_one], end @[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} : (R.bounded_formula₂ t₁ t₂).realize v xs ↔ rel_map R ![t₁.realize (sum.elim v xs), t₂.realize (sum.elim v xs)] := begin rw [relations.bounded_formula₂, realize_rel, iff_eq_eq], refine congr rfl (funext (fin.cases _ _)), { simp only [matrix.cons_val_zero]}, { simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] } end @[simp] lemma realize_sup : (φ ⊔ ψ).realize v xs ↔ (φ.realize v xs ∨ ψ.realize v xs) := begin simp only [realize, has_sup.sup, realize_not, eq_iff_iff], tauto, end @[simp] lemma realize_foldr_sup (l : list (L.bounded_formula α n)) (v : α → M) (xs : fin n → M) : (l.foldr (⊔) ⊥).realize v xs ↔ ∃ φ ∈ l, bounded_formula.realize φ v xs := begin induction l with φ l ih, { simp }, { simp_rw [list.foldr_cons, realize_sup, ih, exists_prop, list.mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] } end @[simp] lemma realize_all : (all θ).realize v xs ↔ ∀ (a : M), (θ.realize v (fin.snoc xs a)) := iff.rfl @[simp] lemma realize_ex : θ.ex.realize v xs ↔ ∃ (a : M), (θ.realize v (fin.snoc xs a)) := begin rw [bounded_formula.ex, realize_not, realize_all, not_forall], simp_rw [realize_not, not_not], end @[simp] lemma realize_iff : (φ.iff ψ).realize v xs ↔ (φ.realize v xs ↔ ψ.realize v xs) := by simp only [bounded_formula.iff, realize_inf, realize_imp, and_imp, ← iff_def] lemma realize_cast_le_of_eq {m n : ℕ} (h : m = n) {h' : m ≤ n} {φ : L.bounded_formula α m} {v : α → M} {xs : fin n → M} : (φ.cast_le h').realize v xs ↔ φ.realize v (xs ∘ fin.cast h) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 k _ ih3 generalizing n xs h h', { simp [cast_le, realize] }, { simp only [cast_le, realize, realize_bd_equal, term.realize_relabel, sum.elim_comp_map, function.comp.right_id, cast_le_of_eq h], }, { simp only [cast_le, realize, realize_rel, term.realize_relabel, sum.elim_comp_map, function.comp.right_id, cast_le_of_eq h] }, { simp only [cast_le, realize, ih1 h, ih2 h], }, { simp only [cast_le, realize, ih3 (nat.succ_inj'.2 h)], refine forall_congr (λ x, iff_eq_eq.mpr (congr rfl (funext (last_cases _ (λ i, _))))), { rw [function.comp_app, snoc_last, cast_last, snoc_last] }, { rw [function.comp_app, snoc_cast_succ, cast_cast_succ, snoc_cast_succ] } } end lemma realize_relabel {m n : ℕ} {φ : L.bounded_formula α n} {g : α → (β ⊕ fin m)} {v : β → M} {xs : fin (m + n) → M} : (φ.relabel g).realize v xs ↔ φ.realize (sum.elim v (xs ∘ (fin.cast_add n)) ∘ g) (xs ∘ (fin.nat_add m)) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 n' _ ih3, { refl }, { simp [realize, relabel] }, { simp [realize, relabel] }, { simp [realize, relabel, ih1, ih2] }, { simp only [ih3, realize, relabel], refine forall_congr (λ a, (iff_eq_eq.mpr (congr (congr rfl (congr (congr rfl (congr rfl (funext (λ i, (dif_pos _).trans rfl)))) rfl)) _))), { ext i, by_cases h : i.val < n', { exact (dif_pos (nat.add_lt_add_left h m)).trans (dif_pos h).symm }, { exact (dif_neg (λ h', h (nat.lt_of_add_lt_add_left h'))).trans (dif_neg h).symm } } } end lemma realize_lift_at {n n' m : ℕ} {φ : L.bounded_formula α n} {v : α → M} {xs : fin (n + n') → M} (hmn : m + n' ≤ n + 1) : (φ.lift_at n' m).realize v xs ↔ φ.realize v (xs ∘ (λ i, if ↑i < m then fin.cast_add n' i else fin.add_nat n' i)) := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 k _ ih3, { simp [lift_at, realize] }, { simp only [lift_at, realize, realize_bd_equal, realize_lift_at, sum.elim_comp_map, function.comp.right_id] }, { simp only [lift_at, realize, realize_rel, realize_lift_at, sum.elim_comp_map, function.comp.right_id] }, { simp only [lift_at, realize, ih1 hmn, ih2 hmn], }, { have h : k + 1 + n' = k + n'+ 1, { rw [add_assoc, add_comm 1 n', ← add_assoc], }, simp only [lift_at, realize, realize_cast_le_of_eq h, ih3 (hmn.trans k.succ.le_succ)], refine forall_congr (λ x, iff_eq_eq.mpr (congr rfl (funext (fin.last_cases _ (λ i, _))))), { simp only [function.comp_app, coe_last, snoc_last], by_cases (k < m), { rw if_pos h, refine (congr rfl (ext _)).trans (snoc_last _ _), simp only [coe_cast, coe_cast_add, coe_last, self_eq_add_right], refine le_antisymm (le_of_add_le_add_left ((hmn.trans (nat.succ_le_of_lt h)).trans _)) n'.zero_le, rw add_zero }, { rw if_neg h, refine (congr rfl (ext _)).trans (snoc_last _ _), simp } }, { simp only [function.comp_app, fin.snoc_cast_succ], refine (congr rfl (ext _)).trans (snoc_cast_succ _ _ _), simp only [cast_refl, coe_cast_succ, order_iso.coe_refl, id.def], split_ifs; simp } } end lemma realize_lift_at_one {n m : ℕ} {φ : L.bounded_formula α n} {v : α → M} {xs : fin (n + 1) → M} (hmn : m ≤ n) : (φ.lift_at 1 m).realize v xs ↔ φ.realize v (xs ∘ (λ i, if ↑i < m then cast_succ i else i.succ)) := by simp_rw [realize_lift_at (add_le_add_right hmn 1), cast_succ, add_nat_one] @[simp] lemma realize_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n} {v : α → M} {xs : fin (n + 1) → M} : (φ.lift_at 1 n).realize v xs ↔ φ.realize v (xs ∘ cast_succ) := begin rw [realize_lift_at_one (refl n), iff_eq_eq], refine congr rfl (congr rfl (funext (λ i, _))), rw [if_pos i.is_lt], end @[simp] lemma realize_subst_aux {tf : α → L.term β} {v : β → M} {xs : fin n → M} : (λ x, term.realize (sum.elim v xs) (sum.elim (term.relabel sum.inl ∘ tf) (var ∘ sum.inr) x)) = sum.elim (λ (a : α), term.realize v (tf a)) xs := funext (λ x, sum.cases_on x (λ x, by simp only [sum.elim_inl, term.realize_relabel, sum.elim_comp_inl]) (λ x, rfl)) lemma realize_subst {φ : L.bounded_formula α n} {tf : α → L.term β} {v : β → M} {xs : fin n → M} : (φ.subst tf).realize v xs ↔ φ.realize (λ a, (tf a).realize v) xs := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih, { refl }, { simp only [subst, bounded_formula.realize, realize_subst, realize_subst_aux] }, { simp only [subst, bounded_formula.realize, realize_subst, realize_subst_aux] }, { simp only [subst, realize_imp, ih1, ih2] }, { simp only [ih, subst, realize_all] } end @[simp] lemma realize_restrict_free_var [decidable_eq α] {n : ℕ} {φ : L.bounded_formula α n} {s : set α} (h : ↑φ.free_var_finset ⊆ s) {v : α → M} {xs : fin n → M} : (φ.restrict_free_var (set.inclusion h)).realize (v ∘ coe) xs ↔ φ.realize v xs := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp [restrict_free_var, realize] }, { simp [restrict_free_var, realize] }, { simp [restrict_free_var, realize, ih1, ih2] }, { simp [restrict_free_var, realize, ih3] }, end variables [nonempty M] lemma realize_all_lift_at_one_self {n : ℕ} {φ : L.bounded_formula α n} {v : α → M} {xs : fin n → M} : (φ.lift_at 1 n).all.realize v xs ↔ φ.realize v xs := begin inhabit M, simp only [realize_all, realize_lift_at_one_self], refine ⟨λ h, _, λ h a, _⟩, { refine (congr rfl (funext (λ i, _))).mp (h default), simp, }, { refine (congr rfl (funext (λ i, _))).mp h, simp } end lemma realize_to_prenex_imp_right {φ ψ : L.bounded_formula α n} (hφ : is_qf φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} : (φ.to_prenex_imp_right ψ).realize v xs ↔ (φ.imp ψ).realize v xs := begin revert φ, induction hψ with _ _ hψ _ _ hψ ih _ _ hψ ih; intros φ hφ, { rw hψ.to_prenex_imp_right }, { refine trans (forall_congr (λ _, ih hφ.lift_at)) _, simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all], exact ⟨λ h1 a h2, h1 h2 a, λ h1 h2 a, h1 a h2⟩, }, { rw [to_prenex_imp_right, realize_ex], refine trans (exists_congr (λ _, ih hφ.lift_at)) _, simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_ex], refine ⟨_, λ h', _⟩, { rintro ⟨a, ha⟩ h, exact ⟨a, ha h⟩ }, { by_cases φ.realize v xs, { obtain ⟨a, ha⟩ := h' h, exact ⟨a, λ _, ha⟩ }, { inhabit M, exact ⟨default, λ h'', (h h'').elim⟩ } } } end lemma realize_to_prenex_imp {φ ψ : L.bounded_formula α n} (hφ : is_prenex φ) (hψ : is_prenex ψ) {v : α → M} {xs : fin n → M} : (φ.to_prenex_imp ψ).realize v xs ↔ (φ.imp ψ).realize v xs := begin revert ψ, induction hφ with _ _ hφ _ _ hφ ih _ _ hφ ih; intros ψ hψ, { rw [hφ.to_prenex_imp], exact realize_to_prenex_imp_right hφ hψ, }, { rw [to_prenex_imp, realize_ex], refine trans (exists_congr (λ _, ih hψ.lift_at)) _, simp only [realize_imp, realize_lift_at_one_self, snoc_comp_cast_succ, realize_all], refine ⟨_, λ h', _⟩, { rintro ⟨a, ha⟩ h, exact ha (h a) }, { by_cases ψ.realize v xs, { inhabit M, exact ⟨default, λ h'', h⟩ }, { obtain ⟨a, ha⟩ := not_forall.1 (h ∘ h'), exact ⟨a, λ h, (ha h).elim⟩ } } }, { refine trans (forall_congr (λ _, ih hψ.lift_at)) _, simp, }, end @[simp] lemma realize_to_prenex (φ : L.bounded_formula α n) {v : α → M} : ∀ {xs : fin n → M}, φ.to_prenex.realize v xs ↔ φ.realize v xs := begin refine bounded_formula.rec_on φ (λ _ _, iff.rfl) (λ _ _ _ _, iff.rfl) (λ _ _ _ _ _, iff.rfl) (λ _ f1 f2 h1 h2 _, _) (λ _ f h xs, _), { rw [to_prenex, realize_to_prenex_imp f1.to_prenex_is_prenex f2.to_prenex_is_prenex, realize_imp, realize_imp, h1, h2], apply_instance }, { rw [realize_all, to_prenex, realize_all], exact forall_congr (λ a, h) }, end end bounded_formula attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel attribute [protected] bounded_formula.imp bounded_formula.all namespace Lhom open bounded_formula @[simp] lemma realize_on_bounded_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] {n : ℕ} (ψ : L.bounded_formula α n) {v : α → M} {xs : fin n → M} : (φ.on_bounded_formula ψ).realize v xs ↔ ψ.realize v xs := begin induction ψ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [on_bounded_formula, realize_bd_equal, realize_on_term], refl, }, { simp only [on_bounded_formula, realize_rel, realize_on_term, is_expansion_on.map_on_relation], refl, }, { simp only [on_bounded_formula, ih1, ih2, realize_imp], }, { simp only [on_bounded_formula, ih3, realize_all], }, end end Lhom attribute [protected] bounded_formula.falsum bounded_formula.equal bounded_formula.rel attribute [protected] bounded_formula.imp bounded_formula.all namespace formula /-- A formula can be evaluated as true or false by giving values to each free variable. -/ def realize (φ : L.formula α) (v : α → M) : Prop := φ.realize v default variables {M} {φ ψ : L.formula α} {v : α → M} @[simp] lemma realize_not : (φ.not).realize v ↔ ¬ φ.realize v := iff.rfl @[simp] lemma realize_bot : (⊥ : L.formula α).realize v ↔ false := iff.rfl @[simp] lemma realize_top : (⊤ : L.formula α).realize v ↔ true := bounded_formula.realize_top @[simp] lemma realize_inf : (φ ⊓ ψ).realize v ↔ (φ.realize v ∧ ψ.realize v) := bounded_formula.realize_inf @[simp] lemma realize_imp : (φ.imp ψ).realize v ↔ (φ.realize v → ψ.realize v) := bounded_formula.realize_imp @[simp] lemma realize_rel {k : ℕ} {R : L.relations k} {ts : fin k → L.term α} : (R.formula ts).realize v ↔ rel_map R (λ i, (ts i).realize v) := bounded_formula.realize_rel.trans (by simp) @[simp] lemma realize_rel₁ {R : L.relations 1} {t : L.term _} : (R.formula₁ t).realize v ↔ rel_map R ![t.realize v] := begin rw [relations.formula₁, realize_rel, iff_eq_eq], refine congr rfl (funext (λ _, _)), simp only [matrix.cons_val_fin_one], end @[simp] lemma realize_rel₂ {R : L.relations 2} {t₁ t₂ : L.term _} : (R.formula₂ t₁ t₂).realize v ↔ rel_map R ![t₁.realize v, t₂.realize v] := begin rw [relations.formula₂, realize_rel, iff_eq_eq], refine congr rfl (funext (fin.cases _ _)), { simp only [matrix.cons_val_zero]}, { simp only [matrix.cons_val_succ, matrix.cons_val_fin_one, forall_const] } end @[simp] lemma realize_sup : (φ ⊔ ψ).realize v ↔ (φ.realize v ∨ ψ.realize v) := bounded_formula.realize_sup @[simp] lemma realize_iff : (φ.iff ψ).realize v ↔ (φ.realize v ↔ ψ.realize v) := bounded_formula.realize_iff @[simp] lemma realize_relabel {φ : L.formula α} {g : α → β} {v : β → M} : (φ.relabel g).realize v ↔ φ.realize (v ∘ g) := begin rw [realize, realize, relabel, bounded_formula.realize_relabel, iff_eq_eq, fin.cast_add_zero], exact congr rfl (funext fin_zero_elim), end lemma realize_relabel_sum_inr (φ : L.formula (fin n)) {v : empty → M} {x : fin n → M} : (bounded_formula.relabel sum.inr φ).realize v x ↔ φ.realize x := by rw [bounded_formula.realize_relabel, formula.realize, sum.elim_comp_inr, fin.cast_add_zero, cast_refl, order_iso.coe_refl, function.comp.right_id, subsingleton.elim (x ∘ (nat_add n : fin 0 → fin n)) default] @[simp] lemma realize_equal {t₁ t₂ : L.term α} {x : α → M} : (t₁.equal t₂).realize x ↔ t₁.realize x = t₂.realize x := by simp [term.equal, realize] @[simp] lemma realize_graph {f : L.functions n} {x : fin n → M} {y : M} : (formula.graph f).realize (fin.cons y x : _ → M) ↔ fun_map f x = y := begin simp only [formula.graph, term.realize, realize_equal, fin.cons_zero, fin.cons_succ], rw eq_comm, end end formula @[simp] lemma Lhom.realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] (ψ : L.formula α) {v : α → M} : (φ.on_formula ψ).realize v ↔ ψ.realize v := φ.realize_on_bounded_formula ψ @[simp] lemma Lhom.set_of_realize_on_formula [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] (ψ : L.formula α) : (set_of (φ.on_formula ψ).realize : set (α → M)) = set_of ψ.realize := by { ext, simp } variable (M) /-- A sentence can be evaluated as true or false in a structure. -/ def sentence.realize (φ : L.sentence) : Prop := φ.realize (default : _ → M) infix ` ⊨ `:51 := sentence.realize -- input using \|= or \vDash, but not using \models @[simp] lemma sentence.realize_not {φ : L.sentence} : M ⊨ φ.not ↔ ¬ M ⊨ φ := iff.rfl @[simp] lemma Lhom.realize_on_sentence [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] (ψ : L.sentence) : M ⊨ φ.on_sentence ψ ↔ M ⊨ ψ := φ.realize_on_formula ψ variables (L) /-- The complete theory of a structure `M` is the set of all sentences `M` satisfies. -/ def complete_theory : L.Theory := { φ | M ⊨ φ } variables {L} /-- A model of a theory is a structure in which every sentence is realized as true. -/ class Theory.model (T : L.Theory) : Prop := (realize_of_mem : ∀ φ ∈ T, M ⊨ φ) infix ` ⊨ `:51 := Theory.model -- input using \|= or \vDash, but not using \models variables {M} (T : L.Theory) @[simp] lemma Theory.model_iff : M ⊨ T ↔ ∀ φ ∈ T, M ⊨ φ := ⟨λ h, h.realize_of_mem, λ h, ⟨h⟩⟩ lemma Theory.realize_sentence_of_mem [M ⊨ T] {φ : L.sentence} (h : φ ∈ T) : M ⊨ φ := Theory.model.realize_of_mem φ h @[simp] lemma Lhom.on_Theory_model [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] (T : L.Theory) : M ⊨ φ.on_Theory T ↔ M ⊨ T := by simp [Theory.model_iff, Lhom.on_Theory] variables {M} {T} instance model_empty : M ⊨ (∅ : L.Theory) := ⟨λ φ hφ, (set.not_mem_empty φ hφ).elim⟩ namespace Theory lemma model.mono {T' : L.Theory} (h : M ⊨ T') (hs : T ⊆ T') : M ⊨ T := ⟨λ φ hφ, T'.realize_sentence_of_mem (hs hφ)⟩ lemma model.union {T' : L.Theory} (h : M ⊨ T) (h' : M ⊨ T') : M ⊨ T ∪ T' := begin simp only [model_iff, set.mem_union_eq] at *, exact λ φ hφ, hφ.elim (h _) (h' _), end @[simp] lemma model_union_iff {T' : L.Theory} : M ⊨ T ∪ T' ↔ M ⊨ T ∧ M ⊨ T' := ⟨λ h, ⟨h.mono (T.subset_union_left T'), h.mono (T.subset_union_right T')⟩, λ h, h.1.union h.2⟩ lemma model_singleton_iff {φ : L.sentence} : M ⊨ ({φ} : L.Theory) ↔ M ⊨ φ := by simp theorem model_iff_subset_complete_theory : M ⊨ T ↔ T ⊆ L.complete_theory M := T.model_iff end Theory instance model_complete_theory : M ⊨ L.complete_theory M := Theory.model_iff_subset_complete_theory.2 (subset_refl _) variables (M N) theorem realize_iff_of_model_complete_theory [N ⊨ L.complete_theory M] (φ : L.sentence) : N ⊨ φ ↔ M ⊨ φ := begin refine ⟨λ h, _, Theory.realize_sentence_of_mem (L.complete_theory M)⟩, contrapose! h, rw [← sentence.realize_not] at *, exact Theory.realize_sentence_of_mem (L.complete_theory M) h, end variables {M N} namespace bounded_formula @[simp] lemma realize_alls {φ : L.bounded_formula α n} {v : α → M} : φ.alls.realize v ↔ ∀ (xs : fin n → M), (φ.realize v xs) := begin induction n with n ih, { exact unique.forall_iff.symm }, { simp only [alls, ih, realize], exact ⟨λ h xs, (fin.snoc_init_self xs) ▸ h _ _, λ h xs x, h (fin.snoc xs x)⟩ } end @[simp] lemma realize_exs {φ : L.bounded_formula α n} {v : α → M} : φ.exs.realize v ↔ ∃ (xs : fin n → M), (φ.realize v xs) := begin induction n with n ih, { exact unique.exists_iff.symm }, { simp only [bounded_formula.exs, ih, realize_ex], split, { rintros ⟨xs, x, h⟩, exact ⟨_, h⟩ }, { rintros ⟨xs, h⟩, rw ← fin.snoc_init_self xs at h, exact ⟨_, _, h⟩ } } end end bounded_formula namespace equiv @[simp] lemma realize_bounded_formula (g : M ≃[L] N) (φ : L.bounded_formula α n) {v : α → M} {xs : fin n → M} : φ.realize (g ∘ v) (g ∘ xs) ↔ φ.realize v xs := begin induction φ with _ _ _ _ _ _ _ _ _ _ _ ih1 ih2 _ _ ih3, { refl }, { simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.injective.eq_iff] }, { simp only [bounded_formula.realize, ← sum.comp_elim, equiv.realize_term, g.map_rel], }, { rw [bounded_formula.realize, ih1, ih2, bounded_formula.realize] }, { rw [bounded_formula.realize, bounded_formula.realize], split, { intros h a, have h' := h (g a), rw [← fin.comp_snoc, ih3] at h', exact h' }, { intros h a, have h' := h (g.symm a), rw [← ih3, fin.comp_snoc, g.apply_symm_apply] at h', exact h' }} end @[simp] lemma realize_formula (g : M ≃[L] N) (φ : L.formula α) {v : α → M} : φ.realize (g ∘ v) ↔ φ.realize v := by rw [formula.realize, formula.realize, ← g.realize_bounded_formula φ, iff_eq_eq, unique.eq_default (g ∘ default)] lemma realize_sentence (g : M ≃[L] N) (φ : L.sentence) : M ⊨ φ ↔ N ⊨ φ := by rw [sentence.realize, sentence.realize, ← g.realize_formula, unique.eq_default (g ∘ default)] lemma Theory_model (g : M ≃[L] N) [M ⊨ T] : N ⊨ T := ⟨λ φ hφ, (g.realize_sentence φ).1 (Theory.realize_sentence_of_mem T hφ)⟩ end equiv namespace relations open bounded_formula variable {r : L.relations 2} @[simp] lemma realize_reflexive : M ⊨ r.reflexive ↔ reflexive (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, realize_rel₂) @[simp] lemma realize_irreflexive : M ⊨ r.irreflexive ↔ irreflexive (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, not_congr realize_rel₂) @[simp] lemma realize_symmetric : M ⊨ r.symmetric ↔ symmetric (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ realize_rel₂)) @[simp] lemma realize_antisymmetric : M ⊨ r.antisymmetric ↔ anti_symmetric (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ iff.rfl))) @[simp] lemma realize_transitive : M ⊨ r.transitive ↔ transitive (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, forall_congr (λ _, forall_congr (λ _, imp_congr realize_rel₂ (imp_congr realize_rel₂ realize_rel₂)))) @[simp] lemma realize_total : M ⊨ r.total ↔ total (λ (x y : M), rel_map r ![x,y]) := forall_congr (λ _, forall_congr (λ _, realize_sup.trans (or_congr realize_rel₂ realize_rel₂))) end relations section cardinality variable (L) @[simp] lemma sentence.realize_card_ge (n) : M ⊨ (sentence.card_ge L n) ↔ ↑n ≤ (# M) := begin rw [← lift_mk_fin, ← lift_le, lift_lift, lift_mk_le, sentence.card_ge, sentence.realize, bounded_formula.realize_exs], simp_rw [bounded_formula.realize_foldr_inf], simp only [function.comp_app, list.mem_map, prod.exists, ne.def, list.mem_product, list.mem_fin_range, forall_exists_index, and_imp, list.mem_filter, true_and], refine ⟨_, λ xs, ⟨xs.some, _⟩⟩, { rintro ⟨xs, h⟩, refine ⟨⟨xs, λ i j ij, _⟩⟩, contrapose! ij, have hij := h _ i j ij rfl, simp only [bounded_formula.realize_not, term.realize, bounded_formula.realize_bd_equal, sum.elim_inr] at hij, exact hij }, { rintro _ i j ij rfl, simp [ij] } end @[simp] lemma model_infinite_theory_iff : M ⊨ L.infinite_theory ↔ infinite M := by simp [infinite_theory, infinite_iff, omega_le] instance model_infinite_theory [h : infinite M] : M ⊨ L.infinite_theory := L.model_infinite_theory_iff.2 h @[simp] lemma model_nonempty_theory_iff : M ⊨ L.nonempty_theory ↔ nonempty M := by simp only [nonempty_theory, Theory.model_iff, set.mem_singleton_iff, forall_eq, sentence.realize_card_ge, nat.cast_one, one_le_iff_ne_zero, mk_ne_zero_iff] instance model_nonempty [h : nonempty M] : M ⊨ L.nonempty_theory := L.model_nonempty_theory_iff.2 h lemma model_distinct_constants_theory {M : Type w} [L[[α]].Structure M] (s : set α) : M ⊨ L.distinct_constants_theory s ↔ set.inj_on (λ (i : α), (L.con i : M)) s := begin simp only [distinct_constants_theory, set.compl_eq_compl, Theory.model_iff, set.mem_image, set.mem_inter_eq, set.mem_prod, set.mem_compl_eq, prod.exists, forall_exists_index, and_imp], refine ⟨λ h a as b bs ab, _, _⟩, { contrapose! ab, have h' := h _ a b as bs ab rfl, simp only [sentence.realize, formula.realize_not, formula.realize_equal, term.realize_constants] at h', exact h', }, { rintros h φ a b as bs ab rfl, simp only [sentence.realize, formula.realize_not, formula.realize_equal, term.realize_constants], exact λ contra, ab (h as bs contra) } end lemma card_le_of_model_distinct_constants_theory (s : set α) (M : Type w) [L[[α]].Structure M] [h : M ⊨ L.distinct_constants_theory s] : cardinal.lift.{w} (# s) ≤ cardinal.lift.{u'} (# M) := lift_mk_le'.2 ⟨⟨_, set.inj_on_iff_injective.1 ((L.model_distinct_constants_theory s).1 h)⟩⟩ end cardinality end language end first_order
af4a6d6de3f7f3a863d76012b2cc626e7de1bfb6
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/inseparable.lean
48f4bc2623521f2cd0a0fe9731a9b4493e3f00cb
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
20,028
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Yury G. Kudryashov -/ import topology.continuous_on import data.setoid.basic import tactic.tfae /-! # Inseparable points in a topological space In this file we define * `specializes` (notation: `x ⤳ y`) : a relation saying that `𝓝 x ≤ 𝓝 y`; * `inseparable`: a relation saying that two points in a topological space have the same neighbourhoods; equivalently, they can't be separated by an open set; * `inseparable_setoid X`: same relation, as a `setoid`; * `separation_quotient X`: the quotient of `X` by its `inseparable_setoid`. We also prove various basic properties of the relation `inseparable`. ## Notations - `x ⤳ y`: notation for `specializes x y`; - `x ~ y` is used as a local notation for `inseparable x y`; - `𝓝 x` is the neighbourhoods filter `nhds x` of a point `x`, defined elsewhere. ## Tags topological space, separation setoid -/ open set filter function open_locale topological_space filter variables {X Y Z α ι : Type*} {π : ι → Type*} [topological_space X] [topological_space Y] [topological_space Z] [∀ i, topological_space (π i)] {x y z : X} {s : set X} {f : X → Y} /-! ### `specializes` relation -/ /-- `x` specializes to `y` (notation: `x ⤳ y`) if either of the following equivalent properties hold: * `𝓝 x ≤ 𝓝 y`; this property is used as the definition; * `pure x ≤ 𝓝 y`; in other words, any neighbourhood of `y` contains `x`; * `y ∈ closure {x}`; * `closure {y} ⊆ closure {x}`; * for any closed set `s` we have `x ∈ s → y ∈ s`; * for any open set `s` we have `y ∈ s → x ∈ s`; * `y` is a cluster point of the filter `pure x = 𝓟 {x}`. This relation defines a `preorder` on `X`. If `X` is a T₀ space, then this preorder is a partial order. If `X` is a T₁ space, then this partial order is trivial : `x ⤳ y ↔ x = y`. -/ def specializes (x y : X) : Prop := 𝓝 x ≤ 𝓝 y infix ` ⤳ `:300 := specializes /-- A collection of equivalent definitions of `x ⤳ y`. The public API is given by `iff` lemmas below. -/ lemma specializes_tfae (x y : X) : tfae [x ⤳ y, pure x ≤ 𝓝 y, ∀ s : set X, is_open s → y ∈ s → x ∈ s, ∀ s : set X, is_closed s → x ∈ s → y ∈ s, y ∈ closure ({x} : set X), closure ({y} : set X) ⊆ closure {x}, cluster_pt y (pure x)] := begin tfae_have : 1 → 2, from (pure_le_nhds _).trans, tfae_have : 2 → 3, from λ h s hso hy, h (hso.mem_nhds hy), tfae_have : 3 → 4, from λ h s hsc hx, of_not_not $ λ hy, h sᶜ hsc.is_open_compl hy hx, tfae_have : 4 → 5, from λ h, h _ is_closed_closure (subset_closure $ mem_singleton _), tfae_have : 6 ↔ 5, from is_closed_closure.closure_subset_iff.trans singleton_subset_iff, tfae_have : 5 ↔ 7, by rw [mem_closure_iff_cluster_pt, principal_singleton], tfae_have : 5 → 1, { refine λ h, (nhds_basis_opens _).ge_iff.2 _, rintro s ⟨hy, ho⟩, rcases mem_closure_iff.1 h s ho hy with ⟨z, hxs, (rfl : z = x)⟩, exact ho.mem_nhds hxs }, tfae_finish end lemma specializes_iff_nhds : x ⤳ y ↔ 𝓝 x ≤ 𝓝 y := iff.rfl lemma specializes_iff_pure : x ⤳ y ↔ pure x ≤ 𝓝 y := (specializes_tfae x y).out 0 1 alias specializes_iff_nhds ↔ specializes.nhds_le_nhds _ alias specializes_iff_pure ↔ specializes.pure_le_nhds _ lemma specializes_iff_forall_open : x ⤳ y ↔ ∀ s : set X, is_open s → y ∈ s → x ∈ s := (specializes_tfae x y).out 0 2 lemma specializes.mem_open (h : x ⤳ y) (hs : is_open s) (hy : y ∈ s) : x ∈ s := specializes_iff_forall_open.1 h s hs hy lemma is_open.not_specializes (hs : is_open s) (hx : x ∉ s) (hy : y ∈ s) : ¬ x ⤳ y := λ h, hx $ h.mem_open hs hy lemma specializes_iff_forall_closed : x ⤳ y ↔ ∀ s : set X, is_closed s → x ∈ s → y ∈ s := (specializes_tfae x y).out 0 3 lemma specializes.mem_closed (h : x ⤳ y) (hs : is_closed s) (hx : x ∈ s) : y ∈ s := specializes_iff_forall_closed.1 h s hs hx lemma is_closed.not_specializes (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬ x ⤳ y := λ h, hy $ h.mem_closed hs hx lemma specializes_iff_mem_closure : x ⤳ y ↔ y ∈ closure ({x} : set X) := (specializes_tfae x y).out 0 4 alias specializes_iff_mem_closure ↔ specializes.mem_closure _ lemma specializes_iff_closure_subset : x ⤳ y ↔ closure ({y} : set X) ⊆ closure {x} := (specializes_tfae x y).out 0 5 alias specializes_iff_closure_subset ↔ specializes.closure_subset _ lemma filter.has_basis.specializes_iff {ι} {p : ι → Prop} {s : ι → set X} (h : (𝓝 y).has_basis p s) : x ⤳ y ↔ ∀ i, p i → x ∈ s i := specializes_iff_pure.trans h.ge_iff lemma specializes_rfl : x ⤳ x := le_rfl @[refl] lemma specializes_refl (x : X) : x ⤳ x := specializes_rfl @[trans] lemma specializes.trans : x ⤳ y → y ⤳ z → x ⤳ z := le_trans lemma specializes_of_eq (e : x = y) : x ⤳ y := e ▸ specializes_refl x lemma specializes_of_nhds_within (h₁ : 𝓝[s] x ≤ 𝓝[s] y) (h₂ : x ∈ s) : x ⤳ y := specializes_iff_pure.2 $ calc pure x ≤ 𝓝[s] x : le_inf (pure_le_nhds _) (le_principal_iff.2 h₂) ... ≤ 𝓝[s] y : h₁ ... ≤ 𝓝 y : inf_le_left lemma specializes.map_of_continuous_at (h : x ⤳ y) (hy : continuous_at f y) : f x ⤳ f y := specializes_iff_pure.2 $ λ s hs, mem_pure.2 $ mem_preimage.1 $ mem_of_mem_nhds $ hy.mono_left h hs lemma specializes.map (h : x ⤳ y) (hf : continuous f) : f x ⤳ f y := h.map_of_continuous_at hf.continuous_at lemma inducing.specializes_iff (hf : inducing f) : f x ⤳ f y ↔ x ⤳ y := by simp only [specializes_iff_mem_closure, hf.closure_eq_preimage_closure_image, image_singleton, mem_preimage] lemma subtype_specializes_iff {p : X → Prop} (x y : subtype p) : x ⤳ y ↔ (x : X) ⤳ y := inducing_coe.specializes_iff.symm @[simp] lemma specializes_prod {x₁ x₂ : X} {y₁ y₂ : Y} : (x₁, y₁) ⤳ (x₂, y₂) ↔ x₁ ⤳ x₂ ∧ y₁ ⤳ y₂ := by simp only [specializes, nhds_prod_eq, prod_le_prod] lemma specializes.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ⤳ x₂) (hy : y₁ ⤳ y₂) : (x₁, y₁) ⤳ (x₂, y₂) := specializes_prod.2 ⟨hx, hy⟩ @[simp] lemma specializes_pi {f g : Π i, π i} : f ⤳ g ↔ ∀ i, f i ⤳ g i := by simp only [specializes, nhds_pi, pi_le_pi] lemma not_specializes_iff_exists_open : ¬ x ⤳ y ↔ ∃ (S : set X), is_open S ∧ y ∈ S ∧ x ∉ S := by { rw [specializes_iff_forall_open], push_neg, refl } lemma not_specializes_iff_exists_closed : ¬ x ⤳ y ↔ ∃ (S : set X), is_closed S ∧ x ∈ S ∧ y ∉ S := by { rw [specializes_iff_forall_closed], push_neg, refl } variable (X) /-- Specialization forms a preorder on the topological space. -/ def specialization_preorder : preorder X := { le := λ x y, y ⤳ x, lt := λ x y, y ⤳ x ∧ ¬(x ⤳ y), .. preorder.lift (order_dual.to_dual ∘ 𝓝) } variable {X} /-- A continuous function is monotone with respect to the specialization preorders on the domain and the codomain. -/ lemma continuous.specialization_monotone (hf : continuous f) : @monotone _ _ (specialization_preorder X) (specialization_preorder Y) f := λ x y h, h.map hf /-! ### `inseparable` relation -/ /-- Two points `x` and `y` in a topological space are `inseparable` if any of the following equivalent properties hold: - `𝓝 x = 𝓝 y`; we use this property as the definition; - for any open set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_open`; - for any closed set `s`, `x ∈ s ↔ y ∈ s`, see `inseparable_iff_closed`; - `x ∈ closure {y}` and `y ∈ closure {x}`, see `inseparable_iff_mem_closure`; - `closure {x} = closure {y}`, see `inseparable_iff_closure_eq`. -/ def inseparable (x y : X) : Prop := 𝓝 x = 𝓝 y local infix ` ~ ` := inseparable lemma inseparable_def : x ~ y ↔ 𝓝 x = 𝓝 y := iff.rfl lemma inseparable_iff_specializes_and : x ~ y ↔ x ⤳ y ∧ y ⤳ x := le_antisymm_iff lemma inseparable.specializes (h : x ~ y) : x ⤳ y := h.le lemma inseparable.specializes' (h : x ~ y) : y ⤳ x := h.ge lemma specializes.antisymm (h₁ : x ⤳ y) (h₂ : y ⤳ x) : x ~ y := le_antisymm h₁ h₂ lemma inseparable_iff_forall_open : x ~ y ↔ ∀ s : set X, is_open s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_open, ← forall_and_distrib, ← iff_def, iff.comm] lemma not_inseparable_iff_exists_open : ¬(x ~ y) ↔ ∃ s : set X, is_open s ∧ xor (x ∈ s) (y ∈ s) := by simp [inseparable_iff_forall_open, ← xor_iff_not_iff] lemma inseparable_iff_forall_closed : x ~ y ↔ ∀ s : set X, is_closed s → (x ∈ s ↔ y ∈ s) := by simp only [inseparable_iff_specializes_and, specializes_iff_forall_closed, ← forall_and_distrib, ← iff_def] lemma inseparable_iff_mem_closure : x ~ y ↔ x ∈ closure ({y} : set X) ∧ y ∈ closure ({x} : set X) := inseparable_iff_specializes_and.trans $ by simp only [specializes_iff_mem_closure, and_comm] lemma inseparable_iff_closure_eq : x ~ y ↔ closure ({x} : set X) = closure {y} := by simp only [inseparable_iff_specializes_and, specializes_iff_closure_subset, ← subset_antisymm_iff, eq_comm] lemma inseparable_of_nhds_within_eq (hx : x ∈ s) (hy : y ∈ s) (h : 𝓝[s] x = 𝓝[s] y) : x ~ y := (specializes_of_nhds_within h.le hx).antisymm (specializes_of_nhds_within h.ge hy) lemma inducing.inseparable_iff (hf : inducing f) : f x ~ f y ↔ x ~ y := by simp only [inseparable_iff_specializes_and, hf.specializes_iff] lemma subtype_inseparable_iff {p : X → Prop} (x y : subtype p) : x ~ y ↔ (x : X) ~ y := inducing_coe.inseparable_iff.symm @[simp] lemma inseparable_prod {x₁ x₂ : X} {y₁ y₂ : Y} : (x₁, y₁) ~ (x₂, y₂) ↔ x₁ ~ x₂ ∧ y₁ ~ y₂ := by simp only [inseparable, nhds_prod_eq, prod_inj] lemma inseparable.prod {x₁ x₂ : X} {y₁ y₂ : Y} (hx : x₁ ~ x₂) (hy : y₁ ~ y₂) : (x₁, y₁) ~ (x₂, y₂) := inseparable_prod.2 ⟨hx, hy⟩ @[simp] lemma inseparable_pi {f g : Π i, π i} : f ~ g ↔ ∀ i, f i ~ g i := by simp only [inseparable, nhds_pi, funext_iff, pi_inj] namespace inseparable @[refl] lemma refl (x : X) : x ~ x := eq.refl (𝓝 x) lemma rfl : x ~ x := refl x lemma of_eq (e : x = y) : inseparable x y := e ▸ refl x @[symm] lemma symm (h : x ~ y) : y ~ x := h.symm @[trans] lemma trans (h₁ : x ~ y) (h₂ : y ~ z) : x ~ z := h₁.trans h₂ lemma nhds_eq (h : x ~ y) : 𝓝 x = 𝓝 y := h lemma mem_open_iff (h : x ~ y) (hs : is_open s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_open.1 h s hs lemma mem_closed_iff (h : x ~ y) (hs : is_closed s) : x ∈ s ↔ y ∈ s := inseparable_iff_forall_closed.1 h s hs lemma map_of_continuous_at (h : x ~ y) (hx : continuous_at f x) (hy : continuous_at f y) : f x ~ f y := (h.specializes.map_of_continuous_at hy).antisymm (h.specializes'.map_of_continuous_at hx) lemma map (h : x ~ y) (hf : continuous f) : f x ~ f y := h.map_of_continuous_at hf.continuous_at hf.continuous_at end inseparable lemma is_closed.not_inseparable (hs : is_closed s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y := λ h, hy $ (h.mem_closed_iff hs).1 hx lemma is_open.not_inseparable (hs : is_open s) (hx : x ∈ s) (hy : y ∉ s) : ¬x ~ y := λ h, hy $ (h.mem_open_iff hs).1 hx /-! ### Separation quotient In this section we define the quotient of a topological space by the `inseparable` relation. -/ variable (X) /-- A `setoid` version of `inseparable`, used to define the `separation_quotient`. -/ def inseparable_setoid : setoid X := { r := (~), .. setoid.comap 𝓝 ⊥ } /-- The quotient of a topological space by its `inseparable_setoid`. This quotient is guaranteed to be a T₀ space. -/ @[derive topological_space] def separation_quotient := quotient (inseparable_setoid X) variables {X} {t : set (separation_quotient X)} namespace separation_quotient /-- The natural map from a topological space to its separation quotient. -/ def mk : X → separation_quotient X := quotient.mk' lemma quotient_map_mk : quotient_map (mk : X → separation_quotient X) := quotient_map_quot_mk lemma continuous_mk : continuous (mk : X → separation_quotient X) := continuous_quot_mk @[simp] lemma mk_eq_mk : mk x = mk y ↔ x ~ y := quotient.eq' lemma surjective_mk : surjective (mk : X → separation_quotient X) := surjective_quot_mk _ @[simp] lemma range_mk : range (mk : X → separation_quotient X) = univ := surjective_mk.range_eq instance [nonempty X] : nonempty (separation_quotient X) := nonempty.map mk ‹_› instance [inhabited X] : inhabited (separation_quotient X) := ⟨mk default⟩ instance [subsingleton X] : subsingleton (separation_quotient X) := surjective_mk.subsingleton lemma preimage_image_mk_open (hs : is_open s) : mk ⁻¹' (mk '' s) = s := begin refine subset.antisymm _ (subset_preimage_image _ _), rintro x ⟨y, hys, hxy⟩, exact ((mk_eq_mk.1 hxy).mem_open_iff hs).1 hys end lemma is_open_map_mk : is_open_map (mk : X → separation_quotient X) := λ s hs, quotient_map_mk.is_open_preimage.1 $ by rwa preimage_image_mk_open hs lemma preimage_image_mk_closed (hs : is_closed s) : mk ⁻¹' (mk '' s) = s := begin refine subset.antisymm _ (subset_preimage_image _ _), rintro x ⟨y, hys, hxy⟩, exact ((mk_eq_mk.1 hxy).mem_closed_iff hs).1 hys end lemma inducing_mk : inducing (mk : X → separation_quotient X) := ⟨le_antisymm (continuous_iff_le_induced.1 continuous_mk) (λ s hs, ⟨mk '' s, is_open_map_mk s hs, preimage_image_mk_open hs⟩)⟩ lemma is_closed_map_mk : is_closed_map (mk : X → separation_quotient X) := inducing_mk.is_closed_map $ by { rw [range_mk], exact is_closed_univ } @[simp] lemma comap_mk_nhds_mk : comap mk (𝓝 (mk x)) = 𝓝 x := (inducing_mk.nhds_eq_comap _).symm @[simp] lemma comap_mk_nhds_set_image : comap mk (𝓝ˢ (mk '' s)) = 𝓝ˢ s := (inducing_mk.nhds_set_eq_comap _).symm lemma map_mk_nhds : map mk (𝓝 x) = 𝓝 (mk x) := by rw [← comap_mk_nhds_mk, map_comap_of_surjective surjective_mk] lemma map_mk_nhds_set : map mk (𝓝ˢ s) = 𝓝ˢ (mk '' s) := by rw [← comap_mk_nhds_set_image, map_comap_of_surjective surjective_mk] lemma comap_mk_nhds_set : comap mk (𝓝ˢ t) = 𝓝ˢ (mk ⁻¹' t) := by conv_lhs { rw [← image_preimage_eq t surjective_mk, comap_mk_nhds_set_image] } lemma preimage_mk_closure : mk ⁻¹' (closure t) = closure (mk ⁻¹' t) := is_open_map_mk.preimage_closure_eq_closure_preimage continuous_mk t lemma preimage_mk_interior : mk ⁻¹' (interior t) = interior (mk ⁻¹' t) := is_open_map_mk.preimage_interior_eq_interior_preimage continuous_mk t lemma preimage_mk_frontier : mk ⁻¹' (frontier t) = frontier (mk ⁻¹' t) := is_open_map_mk.preimage_frontier_eq_frontier_preimage continuous_mk t lemma image_mk_closure : mk '' closure s = closure (mk '' s) := (image_closure_subset_closure_image continuous_mk).antisymm $ is_closed_map_mk.closure_image_subset _ lemma map_prod_map_mk_nhds (x : X) (y : Y) : map (prod.map mk mk) (𝓝 (x, y)) = 𝓝 (mk x, mk y) := by rw [nhds_prod_eq, ← prod_map_map_eq', map_mk_nhds, map_mk_nhds, nhds_prod_eq] lemma map_mk_nhds_within_preimage (s : set (separation_quotient X)) (x : X) : map mk (𝓝[mk ⁻¹' s] x) = 𝓝[s] (mk x) := by rw [nhds_within, ← comap_principal, filter.push_pull, nhds_within, map_mk_nhds] /-- Lift a map `f : X → α` such that `inseparable x y → f x = f y` to a map `separation_quotient X → α`. -/ def lift (f : X → α) (hf : ∀ x y, x ~ y → f x = f y) : separation_quotient X → α := λ x, quotient.lift_on' x f hf @[simp] lemma lift_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) (x : X) : lift f hf (mk x) = f x := rfl @[simp] lemma lift_comp_mk {f : X → α} (hf : ∀ x y, x ~ y → f x = f y) : lift f hf ∘ mk = f := rfl @[simp] lemma tendsto_lift_nhds_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X} {l : filter α} : tendsto (lift f hf) (𝓝 $ mk x) l ↔ tendsto f (𝓝 x) l := by simp only [← map_mk_nhds, tendsto_map'_iff, lift_comp_mk] @[simp] lemma tendsto_lift_nhds_within_mk {f : X → α} {hf : ∀ x y, x ~ y → f x = f y} {x : X} {s : set (separation_quotient X)} {l : filter α} : tendsto (lift f hf) (𝓝[s] (mk x)) l ↔ tendsto f (𝓝[mk ⁻¹' s] x) l := by simp only [← map_mk_nhds_within_preimage, tendsto_map'_iff, lift_comp_mk] @[simp] lemma continuous_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {x : X} : continuous_at (lift f hf) (mk x) ↔ continuous_at f x := tendsto_lift_nhds_mk @[simp] lemma continuous_within_at_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {s : set (separation_quotient X)} {x : X} : continuous_within_at (lift f hf) s (mk x) ↔ continuous_within_at f (mk ⁻¹' s) x := tendsto_lift_nhds_within_mk @[simp] lemma continuous_on_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} {s : set (separation_quotient X)} : continuous_on (lift f hf) s ↔ continuous_on f (mk ⁻¹' s) := by simp only [continuous_on, surjective_mk.forall, continuous_within_at_lift, mem_preimage] @[simp] lemma continuous_lift {f : X → Y} {hf : ∀ x y, x ~ y → f x = f y} : continuous (lift f hf) ↔ continuous f := by simp only [continuous_iff_continuous_on_univ, continuous_on_lift, preimage_univ] /-- Lift a map `f : X → Y → α` such that `inseparable a b → inseparable c d → f a c = f b d` to a map `separation_quotient X → separation_quotient Y → α`. -/ def lift₂ (f : X → Y → α) (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) : separation_quotient X → separation_quotient Y → α := λ x y, quotient.lift_on₂' x y f hf @[simp] lemma lift₂_mk {f : X → Y → α} (hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d) (x : X) (y : Y) : lift₂ f hf (mk x) (mk y) = f x y := rfl @[simp] lemma tendsto_lift₂_nhds {f : X → Y → α} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} {l : filter α} : tendsto (uncurry $ lift₂ f hf) (𝓝 (mk x, mk y)) l ↔ tendsto (uncurry f) (𝓝 (x, y)) l := by { rw [← map_prod_map_mk_nhds, tendsto_map'_iff], refl } @[simp] lemma tendsto_lift₂_nhds_within {f : X → Y → α} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} {s : set (separation_quotient X × separation_quotient Y)} {l : filter α} : tendsto (uncurry $ lift₂ f hf) (𝓝[s] (mk x, mk y)) l ↔ tendsto (uncurry f) (𝓝[prod.map mk mk ⁻¹' s] (x, y)) l := by { rw [nhds_within, ← map_prod_map_mk_nhds, ← filter.push_pull, comap_principal], refl } @[simp] lemma continuous_at_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {x : X} {y : Y} : continuous_at (uncurry $ lift₂ f hf) (mk x, mk y) ↔ continuous_at (uncurry f) (x, y) := tendsto_lift₂_nhds @[simp] lemma continuous_within_at_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {s : set (separation_quotient X × separation_quotient Y)} {x : X} {y : Y} : continuous_within_at (uncurry $ lift₂ f hf) s (mk x, mk y) ↔ continuous_within_at (uncurry f) (prod.map mk mk ⁻¹' s) (x, y) := tendsto_lift₂_nhds_within @[simp] lemma continuous_on_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} {s : set (separation_quotient X × separation_quotient Y)} : continuous_on (uncurry $ lift₂ f hf) s ↔ continuous_on (uncurry f) (prod.map mk mk ⁻¹' s) := begin simp_rw [continuous_on, (surjective_mk.prod_map surjective_mk).forall, prod.forall, prod.map, continuous_within_at_lift₂], refl end @[simp] lemma continuous_lift₂ {f : X → Y → Z} {hf : ∀ a b c d, a ~ c → b ~ d → f a b = f c d} : continuous (uncurry $ lift₂ f hf) ↔ continuous (uncurry f) := by simp only [continuous_iff_continuous_on_univ, continuous_on_lift₂, preimage_univ] end separation_quotient
9c7f0c808e6aa5d79b07fae6464ff0e2d9c12fed
3b880d8d9f5be25fbdaadb8860a1e6beac8e52a5
/20170116_POPL/assoc/flat_assoc_trace.lean
737c02d6d6f0fbfc48636da76b8ae908b4f868b3
[ "Apache-2.0" ]
permissive
gebner/presentations
29ea49abd3feb88e0a36d24ace38fbf5a3b939ad
3b2149d19d6429c193965454d919e1b4eb1a44d8
refs/heads/master
1,609,598,807,163
1,484,466,986,000
1,484,466,986,000
78,720,148
0
0
null
1,484,206,190,000
1,484,206,190,000
null
UTF-8
Lean
false
false
4,038
lean
/- In this file, we add tracing capabilities to the flattening tactics we have defined at flat_assoc.lean. -/ import data.set open tactic expr /- The command `declare_trace` add a new trace.flat_assoc option to Lean -/ declare_trace flat_assoc /-- Return `some (a, b)` iff `e` is of the form `(op a b)` -/ meta def is_bin_app (op : expr) : expr → option (expr × expr) | (app (app fn a1) a2) := if op = fn then some (a1, a2) else none | _ := none /-- The tactic (flat_with op assoc lhs rhs) returns the flattening of (op lhs rhs) and proof that the resulting term is equal to (op lhs rhs). - `op` is a binary operator - `assoc` is a proof that it is associative The tactic may fail if `op` is not a binary operator, if `assoc` is not a proof that `op` is associative. -/ meta def flat_with (op : expr) (assoc : expr) : expr → expr → tactic (expr × expr) | lhs rhs := /- The tactic (when_tracing id tac) executes the tactic `tac` if the option trace.id is set to true. -/ when_tracing `flat_assoc (do /- The tactic (pp e) pretty-prints the given expression. It returns the formatting object for `e`. It will format it with respect to the local context and environment associated with the main goal. -/ lhs_fmt ← pp lhs, rhs_fmt ← pp rhs, trace (to_fmt "flattening " ++ lhs_fmt ++ " with " ++ rhs_fmt)) >> match is_bin_app op lhs with | (some (lhs₁, lhs₂)) := do (rhs₁, h₁) ← flat_with lhs₂ rhs, (rhs₂, h₂) ← flat_with lhs₁ rhs₁, h₃ ← return $ assoc lhs₁ lhs₂ rhs, h₄ ← mk_app `congr_arg [op lhs₁, h₁], h ← to_expr `(eq.trans %%h₃ (eq.trans %%h₄ %%h₂)), return (rhs₂, h) | none := do new_rhs ← return (op lhs rhs), h ← mk_app `eq.refl [new_rhs], return (new_rhs, h) end /-- The tactic (flat_core op assoc e) returns the flattening of `e` with respect to the binary operator `op`, and proof that the resulting term is equal to `e` - `op` is a binary operator - `assoc` is a proof that it is associative -/ meta def flat_core (op : expr) (assoc : expr) : expr → tactic (expr × expr) | e := match is_bin_app op e with | (some (lhs, rhs)) := do (new_rhs, h₁) ← flat_core rhs, (new_app, h₂) ← flat_with op assoc lhs new_rhs, h ← to_expr `(eq.trans (congr_arg %%(op lhs) %%h₁) %%h₂), return (new_app, h) | none := do pr ← mk_app `eq.refl [e], return (e, pr) end /-- The tactic a_refl closes the current goal iff it is of the form (lhs = rhs), and the flattening of lhs and rhs, with respect to op, is the same term. -/ meta def a_refl_core (op : expr) (assoc : expr) : tactic unit := do t ← target, when_tracing `flat_assoc (do t_fmt ← pp t, trace $ to_fmt ">> a_refl_core " ++ t_fmt), (lhs, rhs) ← match_eq t, when_tracing `flat_assoc (trace ">>> formating lhs"), (flat_lhs, h₁) ← flat_core op assoc lhs, when_tracing `flat_assoc (trace ">>> formating rhs"), (flat_rhs, h₂) ← flat_core op assoc rhs, guard (flat_lhs = flat_rhs), to_expr `(eq.trans %%h₁ (eq.symm %%h₂)) >>= exact meta def is_assoc_bin_app : expr → tactic (expr × expr) | (app (app op a1) a2) := do h ← to_expr `(is_associative.assoc %%op), return (op, h) | _ := failed meta def a_refl : tactic unit := do (lhs, rhs) ← target >>= match_eq, (op, assoc) ← is_assoc_bin_app lhs, a_refl_core op assoc /- We can enable/disable the tracing messages using the set_option command. Later, we demonstrate how to use the Lean debugger and VM monitor. -/ set_option trace.flat_assoc true example (a b c d e f g : nat) : ((a + b) + c) + ((d + e) + (f + g)) = a + (b + (c + (d + (e + (f + g))))) := by a_refl set_option trace.flat_assoc false example (s₁ s₂ s₃ s₄ : set nat) : (s₁ ∪ s₂) ∪ (s₃ ∪ s₄) = s₁ ∪ (s₂ ∪ (s₃ ∪ s₄)) := by a_refl
b81f49b351d6431c82de876aa0adc1bf7a0dc16e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/sheaves/sheaf_condition/equalizer_products.lean
eb5b673ba8e0d617026ddda033d8110b82b3d868
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
15,686
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.limits.shapes.equalizers import category_theory.limits.shapes.products import topology.sheaves.sheaf_condition.pairwise_intersections /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ F.obj (U i)` and `∏ F.obj (U i) ⊓ (U j)`. We show that this sheaf condition is equivalent to the `pairwise_intersections` sheaf condition when the presheaf is valued in a category with products, and thereby equivalent to the default sheaf condition. -/ universes v' 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.{v'} C] variables {X : Top.{v'}} (F : presheaf C X) {ι : Type v'} (U : ι → opens X) namespace presheaf namespace sheaf_condition_equalizer_products /-- The product of the sections of a presheaf over a family of open sets. -/ def pi_opens : C := ∏ (λ i : ι, F.obj (op (U i))) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def pi_inters : C := ∏ (λ p : ι × ι, F.obj (op (U p.1 ⊓ U p.2))) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def left_res : pi_opens F U ⟶ pi_inters.{v'} F U := pi.lift (λ p : ι × ι, pi.π _ p.1 ≫ F.map (inf_le_left (U p.1) (U p.2)).op) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def right_res : pi_opens F U ⟶ pi_inters.{v'} F U := pi.lift (λ p : ι × ι, pi.π _ p.2 ≫ F.map (inf_le_right (U p.1) (U p.2)).op) /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (supr U)) ⟶ pi_opens.{v'} F U := pi.lift (λ i : ι, F.map (topological_space.opens.le_supr U i).op) @[simp, elementwise] lemma res_π (i : ι) : res F U ≫ limit.π _ ⟨i⟩ = F.map (opens.le_supr U i).op := by rw [res, limit.lift_π, fan.mk_π_app] @[elementwise] lemma w : res F U ≫ left_res F U = res F U ≫ right_res F U := begin dsimp [res, left_res, right_res], ext, simp only [limit.lift_π, limit.lift_π_assoc, fan.mk_π_app, category.assoc], rw [←F.map_comp], rw [←F.map_comp], congr, end /-- The equalizer diagram for the sheaf condition. -/ @[reducible] def diagram : walking_parallel_pair ⥤ C := parallel_pair (left_res.{v'} F U) (right_res F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : fork.{v} (left_res F U) (right_res F U) := fork.of_ι _ (w F U) @[simp] lemma fork_X : (fork F U).X = F.obj (op (supr U)) := rfl @[simp] lemma fork_ι : (fork F U).ι = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_zero : (fork F U).π.app walking_parallel_pair.zero = res F U := rfl @[simp] lemma fork_π_app_walking_parallel_pair_one : (fork F U).π.app walking_parallel_pair.one = res F U ≫ left_res F U := rfl variables {F} {G : presheaf C X} /-- Isomorphic presheaves have isomorphic `pi_opens` for any cover `U`. -/ @[simp] def pi_opens.iso_of_iso (α : F ≅ G) : pi_opens F U ≅ pi_opens.{v'} G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic `pi_inters` for any cover `U`. -/ @[simp] def pi_inters.iso_of_iso (α : F ≅ G) : pi_inters F U ≅ pi_inters.{v'} G U := pi.map_iso (λ X, α.app _) /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.iso_of_iso (α : F ≅ G) : diagram F U ≅ diagram.{v'} G U := nat_iso.of_components begin rintro ⟨⟩, exact pi_opens.iso_of_iso U α, exact pi_inters.iso_of_iso U α end begin rintro ⟨⟩ ⟨⟩ ⟨⟩, { simp, }, { ext, simp [left_res], }, { ext, simp [right_res], }, { simp, }, end. /-- If `F G : presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.iso_of_iso (α : F ≅ G) : fork F U ≅ (cones.postcompose (diagram.iso_of_iso U α).inv).obj (fork G U) := begin fapply fork.ext, { apply α.app, }, { ext, dunfold fork.ι, -- Ugh, `simp` can't unfold abbreviations. simp [res, diagram.iso_of_iso], } end end 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)`. -/ def is_sheaf_equalizer_products (F : presheaf.{v' v u} C X) : Prop := ∀ ⦃ι : Type v'⦄ (U : ι → opens X), nonempty (is_limit (sheaf_condition_equalizer_products.fork F U)) /-! The remainder of this file shows that the equalizer_products sheaf condition is equivalent to the pariwise_intersections sheaf condition. -/ namespace sheaf_condition_pairwise_intersections open category_theory.pairwise category_theory.pairwise.hom /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor_obj (c : cone ((diagram U).op ⋙ F)) : cone (sheaf_condition_equalizer_products.diagram F U) := { X := c.X, π := { app := λ Z, walking_parallel_pair.cases_on Z (pi.lift (λ (i : ι), c.π.app (op (single i)))) (pi.lift (λ (b : ι × ι), c.π.app (op (pair b.1 b.2)))), naturality' := λ Y Z f, begin cases Y; cases Z; cases f, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.left i j)), dsimp at h, simpa using h, }, { ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res], simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], have h := c.π.naturality (quiver.hom.op (hom.right i j)), dsimp at h, simpa using h, }, { ext i, dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc], dsimp, simp only [limit.lift_π, category.id_comp, fan.mk_π_app], }, end, }, } section local attribute [tidy] tactic.case_bash /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_functor : limits.cone ((diagram U).op ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { obj := λ c, cone_equiv_functor_obj F U c, map := λ c c' f, { hom := f.hom, w' := λ j, begin cases j; { ext, simp only [limits.fan.mk_π_app, limits.cone_morphism.w, limits.limit.lift_π, category.assoc, cone_equiv_functor_obj_π_app], }, end }, }. end /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse_obj (c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone ((diagram U).op ⋙ F) := { X := c.X, π := { app := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, }, { exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), } end, naturality' := begin intros x y f, induction x using opposite.rec, induction y using opposite.rec, have ef : f = f.unop.op := rfl, revert ef, generalize : f.unop = f', rintro rfl, rcases x with ⟨i⟩|⟨⟩; rcases y with ⟨⟩|⟨j,j⟩; rcases f' with ⟨⟩, { dsimp, erw [F.map_id], simp, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.left), dsimp [sheaf_condition_equalizer_products.left_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (i, j), rw h', simp only [category.assoc, limit.lift_π, fan.mk_π_app], refl, }, { dsimp, simp only [category.id_comp, category.assoc], have h := c.π.naturality (walking_parallel_pair_hom.right), dsimp [sheaf_condition_equalizer_products.right_res] at h, simp only [category.id_comp] at h, have h' := h =≫ pi.π _ (j, i), rw h', simp, refl, }, { dsimp, erw [F.map_id], simp, }, end, }, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_inverse : limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone ((diagram U).op ⋙ F) := { obj := λ c, cone_equiv_inverse_obj F U c, map := λ c c' f, { hom := f.hom, w' := begin intro x, induction x using opposite.rec, rcases x with (⟨i⟩|⟨i,j⟩), { dsimp, dunfold fork.ι, rw [←(f.w walking_parallel_pair.zero), category.assoc], }, { dsimp, rw [←(f.w walking_parallel_pair.one), category.assoc], }, end }, }. /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso_app (c : cone ((diagram U).op ⋙ F)) : (𝟭 (cone ((diagram U).op ⋙ F))).obj c ≅ (cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c := { hom := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end, }, inv := { hom := 𝟙 _, w' := λ j, begin induction j using opposite.rec, rcases j; { dsimp, simp only [limits.fan.mk_π_app, category.id_comp, limits.limit.lift_π], } end }, hom_inv_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, inv_hom_id' := begin ext, simp only [category.comp_id, limits.cone.category_comp_hom, limits.cone.category_id_hom], end, } /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_unit_iso : 𝟭 (limits.cone ((diagram U).op ⋙ F)) ≅ cone_equiv_functor F U ⋙ cone_equiv_inverse F U := nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simps] def cone_equiv_counit_iso : cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅ 𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) := nat_iso.of_components (λ c, { hom := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨_|_⟩, { ext ⟨j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, { ext ⟨i,j⟩, dsimp, simp only [category.id_comp, limits.fan.mk_π_app, limits.limit.lift_π], }, end, }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, }) (λ c d f, by { ext, dsimp, simp only [category.comp_id, category.id_comp], }) /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def cone_equiv : limits.cone ((diagram U).op ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) := { functor := cone_equiv_functor F U, inverse := cone_equiv_inverse F U, unit_iso := cone_equiv_unit_iso F U, counit_iso := cone_equiv_counit_iso F U, } local attribute [reducible] sheaf_condition_equalizer_products.res sheaf_condition_equalizer_products.left_res /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork (P : is_limit (sheaf_condition_equalizer_products.fork F U)) : is_limit (F.map_cone (cocone U).op) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P) { hom := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin intro x, induction x using opposite.rec, rcases x with ⟨⟩, { dsimp, simp, refl, }, { dsimp, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone (Q : is_limit (F.map_cone (cocone U).op)) : is_limit (sheaf_condition_equalizer_products.fork F U) := is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q) { hom := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, inv := { hom := 𝟙 _, w' := begin rintro ⟨⟩, { dsimp, simp, refl, }, { dsimp, ext ⟨i, j⟩, simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc], rw ←F.map_comp, refl, } end }, hom_inv_id' := by { ext, dsimp, simp only [category.comp_id], }, inv_hom_id' := by { ext, dsimp, simp only [category.comp_id], }, } end sheaf_condition_pairwise_intersections open sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the default sheaf condition. -/ lemma is_sheaf_iff_is_sheaf_equalizer_products (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_equalizer_products := (is_sheaf_iff_is_sheaf_pairwise_intersections F).trans $ iff.intro (λ h ι U, ⟨is_limit_sheaf_condition_fork_of_is_limit_map_cone F U (h U).some⟩) (λ h ι U, ⟨is_limit_map_cone_of_is_limit_sheaf_condition_fork F U (h U).some⟩) end presheaf end Top
e43e377383ef4af1caae377c015b7e8ebd279470
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/perm/cycles.lean
6b7b9326005fa3917eef7ae54b7d4d3036b0a59f
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,011
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.perm.sign import Mathlib.PostPort universes u_2 u_1 namespace Mathlib /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm β`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `β` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. -/ namespace equiv.perm /-! ### `is_cycle` -/ /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle {β : Type u_2} (f : perm β) := ∃ (x : β), coe_fn f x ≠ x ∧ ∀ (y : β), coe_fn f y ≠ y → ∃ (i : ℤ), coe_fn (f ^ i) x = y theorem is_cycle.swap {α : Type u_1} [DecidableEq α] {x : α} {y : α} (hxy : x ≠ y) : is_cycle (swap x y) := sorry theorem is_cycle.inv {β : Type u_2} {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := sorry theorem is_cycle.exists_gpow_eq {β : Type u_2} {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : ∃ (i : ℤ), coe_fn (f ^ i) x = y := sorry theorem is_cycle.exists_pow_eq {β : Type u_2} [fintype β] {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : ∃ (i : ℕ), coe_fn (f ^ i) x = y := sorry theorem is_cycle_swap_mul_aux₁ {α : Type u_1} [DecidableEq α] (n : ℕ) {b : α} {x : α} {f : perm α} (hb : coe_fn (swap x (coe_fn f x) * f) b ≠ b) (h : coe_fn (f ^ n) (coe_fn f x) = b) : ∃ (i : ℤ), coe_fn ((swap x (coe_fn f x) * f) ^ i) (coe_fn f x) = b := sorry theorem is_cycle_swap_mul_aux₂ {α : Type u_1} [DecidableEq α] (n : ℤ) {b : α} {x : α} {f : perm α} (hb : coe_fn (swap x (coe_fn f x) * f) b ≠ b) (h : coe_fn (f ^ n) (coe_fn f x) = b) : ∃ (i : ℤ), coe_fn ((swap x (coe_fn f x) * f) ^ i) (coe_fn f x) = b := sorry theorem is_cycle.eq_swap_of_apply_apply_eq_self {α : Type u_1} [DecidableEq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : coe_fn f x ≠ x) (hffx : coe_fn f (coe_fn f x) = x) : f = swap x (coe_fn f x) := sorry theorem is_cycle.swap_mul {α : Type u_1} [DecidableEq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : coe_fn f x ≠ x) (hffx : coe_fn f (coe_fn f x) ≠ x) : is_cycle (swap x (coe_fn f x) * f) := sorry theorem is_cycle.sign {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} (hf : is_cycle f) : coe_fn sign f = -(-1) ^ finset.card (support f) := sorry /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle {β : Type u_2} (f : perm β) (x : β) (y : β) := ∃ (i : ℤ), coe_fn (f ^ i) x = y theorem same_cycle.refl {β : Type u_2} (f : perm β) (x : β) : same_cycle f x x := Exists.intro 0 rfl theorem same_cycle.symm {β : Type u_2} (f : perm β) {x : β} {y : β} : same_cycle f x y → same_cycle f y x := sorry theorem same_cycle.trans {β : Type u_2} (f : perm β) {x : β} {y : β} {z : β} : same_cycle f x y → same_cycle f y z → same_cycle f x z := sorry theorem same_cycle.apply_eq_self_iff {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x y → (coe_fn f x = x ↔ coe_fn f y = y) := sorry theorem is_cycle.same_cycle {β : Type u_2} {f : perm β} (hf : is_cycle f) {x : β} {y : β} (hx : coe_fn f x ≠ x) (hy : coe_fn f y ≠ y) : same_cycle f x y := is_cycle.exists_gpow_eq hf hx hy protected instance same_cycle.decidable_rel {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) : DecidableRel (same_cycle f) := fun (x y : α) => decidable_of_iff (∃ (n : ℕ), ∃ (H : n ∈ list.range (order_of f)), coe_fn (f ^ n) x = y) sorry theorem same_cycle_apply {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x (coe_fn f y) ↔ same_cycle f x y := sorry theorem same_cycle_cycle {β : Type u_2} {f : perm β} {x : β} (hx : coe_fn f x ≠ x) : is_cycle f ↔ ∀ {y : β}, same_cycle f x y ↔ coe_fn f y ≠ y := sorry theorem same_cycle_inv {β : Type u_2} (f : perm β) {x : β} {y : β} : same_cycle (f⁻¹) x y ↔ same_cycle f x y := sorry theorem same_cycle_inv_apply {β : Type u_2} {f : perm β} {x : β} {y : β} : same_cycle f x (coe_fn (f⁻¹) y) ↔ same_cycle f x y := sorry /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : perm α := coe_fn of_subtype (subtype_perm f sorry) theorem cycle_of_apply {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (y : α) : coe_fn (cycle_of f x) y = ite (same_cycle f x y) (coe_fn f y) y := rfl theorem cycle_of_inv {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : cycle_of f x⁻¹ = cycle_of (f⁻¹) x := sorry @[simp] theorem cycle_of_pow_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (n : ℕ) : coe_fn (cycle_of f x ^ n) x = coe_fn (f ^ n) x := sorry @[simp] theorem cycle_of_gpow_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) (n : ℤ) : coe_fn (cycle_of f x ^ n) x = coe_fn (f ^ n) x := sorry theorem same_cycle.cycle_of_apply {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} {x : α} {y : α} (h : same_cycle f x y) : coe_fn (cycle_of f x) y = coe_fn f y := dif_pos h theorem cycle_of_apply_of_not_same_cycle {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} {x : α} {y : α} (h : ¬same_cycle f x y) : coe_fn (cycle_of f x) y = y := dif_neg h @[simp] theorem cycle_of_apply_self {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) (x : α) : coe_fn (cycle_of f x) x = coe_fn f x := same_cycle.cycle_of_apply (same_cycle.refl f x) theorem is_cycle.cycle_of_eq {α : Type u_1} [DecidableEq α] [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : coe_fn f x ≠ x) : cycle_of f x = f := sorry theorem cycle_of_one {α : Type u_1} [DecidableEq α] [fintype α] (x : α) : cycle_of 1 x = 1 := sorry theorem is_cycle_cycle_of {α : Type u_1} [DecidableEq α] [fintype α] (f : perm α) {x : α} (hx : coe_fn f x ≠ x) : is_cycle (cycle_of f x) := sorry /-! ### `cycle_factors` -/ /-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux {α : Type u_1} [DecidableEq α] [fintype α] (l : List α) (f : perm α) : (∀ {x : α}, coe_fn f x ≠ x → x ∈ l) → Subtype fun (l : List (perm α)) => list.prod l = f ∧ (∀ (g : perm α), g ∈ l → is_cycle g) ∧ list.pairwise disjoint l := sorry /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors {α : Type u_1} [DecidableEq α] [fintype α] [linear_order α] (f : perm α) : Subtype fun (l : List (perm α)) => list.prod l = f ∧ (∀ (g : perm α), g ∈ l → is_cycle g) ∧ list.pairwise disjoint l := cycle_factors_aux (finset.sort LessEq finset.univ) f sorry /-! ### Fixed points -/ theorem one_lt_nonfixed_point_card_of_ne_one {α : Type u_1} [DecidableEq α] [fintype α] {σ : perm α} (h : σ ≠ 1) : 1 < finset.card (finset.filter (fun (x : α) => coe_fn σ x ≠ x) finset.univ) := sorry theorem fixed_point_card_lt_of_ne_one {α : Type u_1} [DecidableEq α] [fintype α] {σ : perm α} (h : σ ≠ 1) : finset.card (finset.filter (fun (x : α) => coe_fn σ x = x) finset.univ) < fintype.card α - 1 := sorry
79fc841c5f2372e968716395e70a718ffe5cdabb
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/chap3_exercise.lean
90225f16d5dcedb2d0c7e96224d4e5bcd28e0438
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
9,225
lean
open classical variables p q r s : Prop -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := iff.intro (assume h: p ∧ q, show q ∧ p, from and.intro h.right h.left) (assume h: q ∧ p, show p ∧ q, from and.intro h.right h.left) lemma swap_or: p ∨ q → q ∨ p := assume hpq: p ∨ q, show q ∨ p, from or.elim hpq (assume hp: p, or.intro_right q hp) (assume hq: q, or.intro_left p hq) example : p ∨ q ↔ q ∨ p := iff.intro (assume h: p ∨ q, show q ∨ p, from swap_or p q h) (assume h: q ∨ p, show p ∨ q, from swap_or q p h) -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro ( assume h: (p ∧ q) ∧ r, have hpq: (p ∧ q), from h.left, have hqr: (q ∧ r), from and.intro hpq.right h.right, and.intro hpq.left hqr ) ( assume h: p ∧ (q ∧ r), have hqr: (q ∧ r), from h.right, and.intro (and.intro h.left hqr.left) hqr.right ) -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := have hlr: p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r), from ( assume h: p ∧ (q ∨ r), or.elim h.right ( assume hq: q, have hpq: p ∧ q, from and.intro h.left hq, or.intro_left (p ∧ r) hpq ) ( assume hr: r, have hpr: p ∧ r, from and.intro h.left hr, or.intro_right (p ∧ q) hpr ) ), have hrl: (p ∧ q) ∨ (p ∧ r) → p ∧ (q ∨ r), from ( assume h: (p ∧ q) ∨ (p ∧ r), or.elim h ( assume hpq: p ∧ q, have hqr: q ∨ r, from or.intro_left r hpq.right, and.intro hpq.left hqr ) ( assume hpr: p ∧ r, have hqr: q ∨ r, from or.intro_right q hpr.right, and.intro hpr.left hqr ) ), iff.intro hlr hrl example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := iff.intro ( assume h: p ∨ (q ∧ r), or.elim h ( assume hp:p, have hpq: p ∨ q, from or.intro_left q hp, have hpr: p ∨ r, from or.intro_left r hp, and.intro hpq hpr ) ( assume hqr: q ∧ r, have hpq: p ∨ q, from or.intro_right p hqr.left, have hpr: p ∨ r, from or.intro_right p hqr.right, and.intro hpq hpr ) ) ( assume h: (p ∨ q) ∧ (p ∨ r), have hpq: p ∨ q, from h.left, have hpr: p ∨ r, from h.right, or.elim hpq (assume hp: p, or.intro_left (q ∧ r) hp) ( assume hq: q, or.elim hpr (assume hp: p, or.intro_left (q ∧ r) hp) ( assume hr: r, have hqr: q ∧ r, from and.intro hq hr, or.intro_right p hqr ) ) ) -- other properties example : (p → (q → r)) ↔ (p ∧ q → r) := have hlr: (p → (q → r)) → (p ∧ q → r), from ( assume h: p → q → r, assume hpq: p ∧ q, (h hpq.left) hpq.right ), have hrl: (p ∧ q → r) → (p → (q → r)), from ( assume h: (p ∧ q → r), assume hp: p, assume hq: q, h (and.intro hp hq) ), iff.intro hlr hrl example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := have hlr: ((p ∨ q) → r) → (p → r) ∧ (q → r), from ( assume h: ((p ∨ q) → r), have hpr: (p → r), from ( assume hp: p, have hpq: p ∨ q, from or.intro_left q hp, h hpq ), have hqr: (q → r), from ( assume hq: q, have hpq: p ∨ q, from or.intro_right p hq, h hpq ), and.intro hpr hqr ), have hrl: (p → r) ∧ (q → r) → ((p ∨ q) → r), from ( assume hp: (p → r) ∧ (q → r), assume hpq: p ∨ q, or.elim hpq hp.left hp.right ), iff.intro hlr hrl example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := iff.intro ( assume h: ¬ (p ∨ q), have hnp: ¬ p, from (assume hp: p, absurd (or.intro_left q hp) h), have hnq: ¬ q, from (assume hq: q, absurd (or.intro_right p hq) h), and.intro hnp hnq ) ( assume h: ¬ p ∧ ¬ q, assume hpq: p ∨ q, or.elim hpq (assume hp: p, absurd hp h.left) (assume hq: q, absurd hq h.right) ) example : ¬p ∨ ¬q → ¬(p ∧ q) := assume h: ¬ p ∨ ¬ q, assume hpq: p ∧ q, or.elim h (assume hnp: ¬ p, absurd hpq.left hnp) (assume hnq: ¬ q, absurd hpq.right hnq) example : ¬(p ∧ ¬p) := assume h: p ∧ ¬ p, absurd h.left h.right example : p ∧ ¬q → ¬(p → q) := assume h: p ∧ ¬ q, assume hpq: p → q, absurd (hpq h.left) h.right example : ¬p → (p → q) := assume hnp: ¬ p, assume hp: p, absurd hp hnp example : (¬p ∨ q) → (p → q) := assume h: ¬ p ∨ q, or.elim h (assume hnp: ¬ p, assume hp: p, absurd hp hnp) (assume hq: q, assume hp: p, hq) example : p ∨ false ↔ p := iff.intro ( assume h: p ∨ false, or.elim h (assume hp: p, hp) (false.elim) ) (assume p, or.intro_left false p) example : p ∧ false ↔ false := iff.intro (assume h: p ∧ false, h.right) (false.elim) example : ¬(p ↔ ¬p) := assume h: (p ↔ ¬ p), have hnp: ¬ p, from ( assume hp: p, absurd hp (h.mp hp) ), have hp: p, from h.mpr hnp, absurd hp (h.mp hp) example : (p → q) → (¬q → ¬p) := assume h: p → q, assume hnq: ¬ q, assume hp: p, absurd (h hp) hnq -- these require classical reasoning example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := assume h : p → r ∨ s, by_cases ( assume : p → r, or.intro_left (p → s) this ) ( assume : ¬ (p → r), have p → s, from ( assume : p, show s, from by_contradiction ( assume : ¬ s, have r ∨ s, from h ‹p›, or.elim this ( assume : r, have p → r, from (assume : p, ‹r›), absurd this ‹¬ (p → r)› ) ( assume : s, absurd this ‹¬ s› ) ) ), or.intro_right (p → r) this ) example : ¬(p ∧ q) → ¬p ∨ ¬q := assume h: ¬ (p ∧ q), by_cases ( assume hp: p, have ¬ q, from ( assume hq: q, absurd (and.intro hp hq) h ), or.intro_right (¬ p) this ) ( assume hnp: ¬ p, or.intro_left (¬ q) hnp ) example : ¬(p → q) → p ∧ ¬q := assume h : ¬ (p → q), by_cases ( assume : p, have ¬ q, from ( assume : q, have p → q, from ( assume : p, ‹ q › ), absurd this h ), and.intro ‹p› this ) ( assume : ¬ p, have p → q, from ( assume : p, absurd this ‹¬ p› ), absurd this h ) example : (p → q) → (¬p ∨ q) := assume h : p → q, by_cases (assume : q, or.intro_right (¬ p) this) ( assume : ¬ q, have ¬ p, from ( assume : p, absurd (h this) ‹¬ q› ), or.intro_left q this ) example : (¬q → ¬p) → (p → q) := assume h : ¬ q → ¬ p, assume hp : p, by_contradiction ( assume : ¬ q, absurd hp (h this) ) example : p ∨ ¬p := em p example : p ∨ ¬p := by_cases (assume : p, or.intro_left (¬ p) this) (assume : ¬ p, or.intro_right p this) example : (((p → q) → p) → p) := assume h : (p → q) → p, by_cases ( assume : p → q, show p, from h this ) ( assume : ¬ (p → q), show p, from by_contradiction ( assume : ¬ p, have p → q, from ( assume : p, absurd this ‹¬ p› ), absurd this ‹¬ (p → q)› ) )
ed024da843bd6dbe23a77592796e9b853c8bce04
e0e64c424bf126977aef10e58324934782979062
/src/wk2/notes/groups2.lean
2a2eeeb0abca5ed82ff78ac9129974277094971a
[]
no_license
jamesa9283/LiaLeanTutor
34e9e133a4f7dd415f02c14c4a62351bb9fd8c21
c7ac1400f26eb2992f5f1ee0aaafb54b74665072
refs/heads/master
1,686,146,337,422
1,625,227,392,000
1,625,227,392,000
373,130,175
0
0
null
null
null
null
UTF-8
Lean
false
false
2,342
lean
import ring_theory.unique_factorization_domain ring_theory.int.basic number_theory.divisors algebra.squarefree section squarefree variables {R : Type*} /-- An element of a monoid is squarefree if the only squares that divide it are the squares of units. -/ def squarefree' [monoid R] (r : R) : Prop := ∀ x : R, x * x ∣ r → is_unit x namespace multiplicity variables [comm_monoid R] [decidable_rel (has_dvd.dvd : R → R → Prop)] lemma squarefree_iff_multiplicity_le_one' (r : R) : squarefree r ↔ ∀ x : R, multiplicity x r ≤ 1 ∨ is_unit x := begin refine forall_congr (λ a, _), rw ← sq, rw pow_dvd_iff_le_multiplicity, rw or_iff_not_imp_left, rw not_le, rw imp_congr, { convert enat.add_one_le_iff_lt (enat.coe_ne_top _), norm_cast}, { refl}, end example : 1 + 1 = 2 := by linarith -- by norm_num end multiplicity open nat #check sq_mul_squarefree_of_pos lemma sq_mul_squarefree_of_pos' {n : ℕ} (h : 0 < n) : ∃ a b : ℕ, (b + 1) ^ 2 * (a + 1) = n ∧ squarefree (a + 1) := begin obtain ⟨a₁, b₁, ha₁, hb₁, hab₁, ha₂⟩ := sq_mul_squarefree_of_pos h, refine ⟨a₁.pred, b₁.pred, _, _⟩; simpa only [add_one, succ_pred_eq_of_pos, ha₁, hb₁], end end squarefree section finite_groups /-! # Finite Groups -/ variables {G : Type*} [group G] -- This one is a beast open subgroup #check submonoid.fg_iff #check le_antisymm /-- A subgroup is finitely generated if and only if it is finitely generated as a submonoid. -/ lemma fg_iff_submonoid_fg' (P : subgroup G) : P.fg ↔ P.to_submonoid.fg := begin split, { rintro ⟨S, rfl⟩, rw submonoid.fg_iff, refine ⟨S ∪ S⁻¹, (subgroup.closure_to_submonoid _).symm, S.finite_to_set.union S.finite_to_set.inv⟩, }, { rintro ⟨S, hS⟩, refine ⟨S, le_antisymm _ _⟩, { rw [closure_le, ← coe_to_submonoid, ← hS], exact submonoid.subset_closure, }, { rw [← subgroup.to_submonoid_le, ← hS, submonoid.closure_le], exact subgroup.subset_closure, } }, end /-! # NB! What we just proved is extremely useful, we can use several variants of it, for example; -/ #check subgroup.fg_iff_submonoid_fg -- ** #check add_subgroup.fg_iff_add_submonoid.fg -- ** -- ** these two are the same as Lean knows that `add_groups` are `groups` end finite_groups
808fbb44d9fbfb9712890292fb9e9b86a53c9421
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/meta/mk_dec_eq_instance.lean
d5f746d474fe8341faf660e3c95b768a3069a13f
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,350
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 Helper tactic for showing that a type has decidable equality. -/ prelude import init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics import init.meta.rec_util init.meta.interactive namespace tactic open expr environment list /- Retrieve the name of the type we are building a decidable equality proof for. -/ private meta def get_dec_eq_type_name : tactic name := do { (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const n ls) ← return (get_app_fn b), when (n ≠ `decidable) failed, (const I ls) ← return (get_app_fn d1), return I } <|> fail "mk_dec_eq_instance tactic failed, target type is expected to be of the form (decidable_eq ...)" /- Extract (lhs, rhs) from a goal (decidable (lhs = rhs)) -/ private meta def get_lhs_rhs : tactic (expr × expr) := do (app dec lhs_eq_rhs) ← target | fail "mk_dec_eq_instance failed, unexpected case", match_eq lhs_eq_rhs private meta def find_next_target : list expr → list expr → tactic (expr × expr) | (t::ts) (r::rs) := if t = r then find_next_target ts rs else return (t, r) | l1 l2 := failed /- Create an inhabitant of (decidable (lhs = rhs)) -/ private meta def mk_dec_eq_for (lhs : expr) (rhs : expr) : tactic expr := do lhs_type ← infer_type lhs, dec_type ← mk_app `decidable_eq [lhs_type] >>= whnf, do { inst ← mk_instance dec_type, return $ inst lhs rhs } <|> do { f ← pp dec_type, fail $ to_fmt "mk_dec_eq_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f) } /- Target is of the form (decidable (C ... = C ...)) where C is a constructor -/ private meta def dec_eq_same_constructor : name → name → nat → tactic unit | I_name F_name num_rec := do (lhs, rhs) ← get_lhs_rhs, -- Try easy case first, where the proof is just reflexivity (unify lhs rhs >> right >> reflexivity) <|> do { let lhs_list := get_app_args lhs, let rhs_list := get_app_args rhs, when (length lhs_list ≠ length rhs_list) (fail "mk_dec_eq_instance failed, constructor applications have different number of arguments"), (lhs_arg, rhs_arg) ← find_next_target lhs_list rhs_list, rec ← is_type_app_of lhs_arg I_name, inst ← if rec then do { inst_fn ← mk_brec_on_rec_value F_name num_rec, return $ app inst_fn rhs_arg } else do { mk_dec_eq_for lhs_arg rhs_arg }, `[apply @decidable.by_cases _ _ %%inst], -- discharge first (positive) case by recursion intro1 >>= subst >> dec_eq_same_constructor I_name F_name (if rec then num_rec + 1 else num_rec), -- discharge second (negative) case by contradiction intro1, left, -- decidable.is_false intro1 >>= injection, intros, contradiction, return () } /- Easy case: target is of the form (decidable (C_1 ... = C_2 ...)) where C_1 and C_2 are distinct constructors -/ private meta def dec_eq_diff_constructor : tactic unit := left >> intron 1 >> contradiction /- This tactic is invoked for each case of decidable_eq. There n^2 cases, where n is the number of constructors. -/ private meta def dec_eq_case_2 (I_name : name) (F_name : name) : tactic unit := do (lhs, rhs) ← get_lhs_rhs, let lhs_fn := get_app_fn lhs, let rhs_fn := get_app_fn rhs, if lhs_fn = rhs_fn then dec_eq_same_constructor I_name F_name 0 else dec_eq_diff_constructor private meta def dec_eq_case_1 (I_name : name) (F_name : name) : tactic unit := intro `w >>= cases >> all_goals (dec_eq_case_2 I_name F_name) meta def mk_dec_eq_instance_core : tactic unit := do I_name ← get_dec_eq_type_name, env ← get_env, let v_name := `_v, let F_name := `_F, let num_indices := inductive_num_indices env I_name, let idx_names := list.map (λ (p : name × nat), mk_num_name p~>fst p~>snd) (list.zip (list.repeat `idx num_indices) (list.iota num_indices)), -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro1 >>= (λ x, induction x (idx_names ++ [v_name, F_name]) (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), -- Apply cases to first element of type (I ...) get_local v_name >>= cases, all_goals (dec_eq_case_1 I_name F_name) meta def mk_dec_eq_instance : tactic unit := do env ← get_env, (pi x1 i1 d1 (pi x2 i2 d2 b)) ← target >>= whnf, (const I_name ls) ← return (get_app_fn d1), when (is_ginductive env I_name ∧ ¬ is_inductive env I_name) $ do { d1' ← whnf d1, (app I_basic_const I_idx) ← return d1', I_idx_type ← infer_type I_idx, new_goal ← to_expr ``(∀ (_idx : %%I_idx_type), decidable_eq (%%I_basic_const _idx)), assert `_basic_dec_eq new_goal, swap, to_expr `(_basic_dec_eq %%I_idx) >>= exact, intro1, return () }, mk_dec_eq_instance_core meta instance binder_info.has_decidable_eq : decidable_eq binder_info := by mk_dec_eq_instance end tactic /- instances of types in dependent files -/ instance : decidable_eq ordering := by tactic.mk_dec_eq_instance
f1110a1bdf19dd26691dc1fa62a6c9b0573129ce
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0405.lean
be015fd1255c219130478e2467218697eb7be48c
[]
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
99
lean
example (n : ℕ) : n + 1 = nat.succ n := begin show nat.succ n = nat.succ n, reflexivity, end
d6753ec4e316a7ac9d7502a04a39a7c492c6c70f
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/class_bug1.lean
6f41d9debcc8f50bf319195fc23ab6f30b7bfc87
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
943
lean
import logic inductive category (ob : Type) (mor : ob → ob → Type) : Type := mk : Π (comp : Π⦃A B C : ob⦄, mor B C → mor A B → mor A C) (id : Π {A : ob}, mor A A), (Π {A B C D : ob} {f : mor A B} {g : mor B C} {h : mor C D}, comp h (comp g f) = comp (comp h g) f) → (Π {A B : ob} {f : mor A B}, comp f id = f) → (Π {A B : ob} {f : mor A B}, comp id f = f) → category ob mor class category namespace category context sec_cat parameter A : Type inductive foo := mk : A → foo class foo parameters {ob : Type} {mor : ob → ob → Type} {Cat : category ob mor} definition compose := rec (λ comp id assoc idr idl, comp) Cat definition id := rec (λ comp id assoc idr idl, id) Cat infixr `∘`:60 := compose inductive is_section {A B : ob} (f : mor A B) : Type := mk : ∀g, g ∘ f = id → is_section f end sec_cat end category
80e2f13b6c4ad7d44ce056f92dbd059844fae958
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/control/uliftable.lean
beec5018a276ec9c93e4337162a82c7e886c48a8
[ "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
5,577
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.monad.basic import control.monad.cont import control.monad.writer import data.equiv.basic import tactic.interactive /-! # Universe lifting for type families Some functors such as `option` and `list` are universe polymorphic. Unlike type polymorphism where `option α` is a function application and reasoning and generalizations that apply to functions can be used, `option.{u}` and `option.{v}` are not one function applied to two universe names but one polymorphic definition instantiated twice. This means that whatever works on `option.{u}` is hard to transport over to `option.{v}`. `uliftable` is an attempt at improving the situation. `uliftable option.{u} option.{v}` gives us a generic and composable way to use `option.{u}` in a context that requires `option.{v}`. It is often used in tandem with `ulift` but the two are purposefully decoupled. ## Main definitions * `uliftable` class ## Tags universe polymorphism functor -/ universes u₀ u₁ v₀ v₁ v₂ w w₀ w₁ /-- Given a universe polymorphic type family `M.{u} : Type u₁ → Type u₂`, this class convert between instantiations, from `M.{u} : Type u₁ → Type u₂` to `M.{v} : Type v₁ → Type v₂` and back -/ class uliftable (f : Type u₀ → Type u₁) (g : Type v₀ → Type v₁) := (congr [] {α β} : α ≃ β → f α ≃ g β) namespace uliftable /-- The most common practical use `uliftable` (together with `up`), this function takes `x : M.{u} α` and lifts it to M.{max u v} (ulift.{v} α) -/ @[reducible] def up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : f α → g (ulift α) := (uliftable.congr f g equiv.ulift.symm).to_fun /-- The most common practical use of `uliftable` (together with `up`), this function takes `x : M.{max u v} (ulift.{v} α)` and lowers it to `M.{u} α` -/ @[reducible] def down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} : g (ulift α) → f α := (uliftable.congr f g equiv.ulift.symm).inv_fun /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_up (F : Type v₀ → Type v₁) (G : Type (max v₀ u₀) → Type u₁) [uliftable F G] [monad G] {α β} (x : F α) (f : α → G β) : G β := up x >>= f ∘ ulift.down /-- convenient shortcut to avoid manipulating `ulift` -/ def adapt_down {F : Type (max u₀ v₀) → Type u₁} {G : Type v₀ → Type v₁} [L : uliftable G F] [monad F] {α β} (x : F α) (f : α → G β) : G β := @down.{v₀ v₁ (max u₀ v₀)} G F L β $ x >>= @up.{v₀ v₁ (max u₀ v₀)} G F L β ∘ f /-- map function that moves up universes -/ def up_map {F : Type u₀ → Type u₁} {G : Type.{max u₀ v₀} → Type v₁} [inst : uliftable F G] [functor G] {α β} (f : α → β) (x : F α) : G β := functor.map (f ∘ ulift.down) (up x) /-- map function that moves down universes -/ def down_map {F : Type.{max u₀ v₀} → Type u₁} {G : Type → Type v₁} [inst : uliftable G F] [functor F] {α β} (f : α → β) (x : F α) : G β := down (functor.map (ulift.up ∘ f) x : F (ulift β)) @[simp] lemma up_down {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : g (ulift α)) : up (down x : f α) = x := (uliftable.congr f g equiv.ulift.symm).right_inv _ @[simp] lemma down_up {f : Type u₀ → Type u₁} {g : Type (max u₀ v₀) → Type v₁} [uliftable f g] {α} (x : f α) : down (up x : g _) = x := (uliftable.congr f g equiv.ulift.symm).left_inv _ end uliftable open ulift instance : uliftable id id := { congr := λ α β F, F } /-- for specific state types, this function helps to create a uliftable instance -/ def state_t.uliftable' {s : Type u₀} {s' : Type u₁} {m : Type u₀ → Type v₀} {m' : Type u₁ → Type v₁} [uliftable m m'] (F : s ≃ s') : uliftable (state_t s m) (state_t s' m') := { congr := λ α β G, state_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ $ equiv.prod_congr G F } instance {s m m'} [uliftable m m'] : uliftable (state_t s m) (state_t (ulift s) m') := state_t.uliftable' equiv.ulift.symm /-- for specific reader monads, this function helps to create a uliftable instance -/ def reader_t.uliftable' {s s' m m'} [uliftable m m'] (F : s ≃ s') : uliftable (reader_t s m) (reader_t s' m') := { congr := λ α β G, reader_t.equiv $ equiv.Pi_congr F $ λ _, uliftable.congr _ _ G } instance {s m m'} [uliftable m m'] : uliftable (reader_t s m) (reader_t (ulift s) m') := reader_t.uliftable' equiv.ulift.symm /-- for specific continuation passing monads, this function helps to create a uliftable instance -/ def cont_t.uliftable' {r r' m m'} [uliftable m m'] (F : r ≃ r') : uliftable (cont_t r m) (cont_t r' m') := { congr := λ α β, cont_t.equiv (uliftable.congr _ _ F) } instance {s m m'} [uliftable m m'] : uliftable (cont_t s m) (cont_t (ulift s) m') := cont_t.uliftable' equiv.ulift.symm /-- for specific writer monads, this function helps to create a uliftable instance -/ def writer_t.uliftable' {w w' m m'} [uliftable m m'] (F : w ≃ w') : uliftable (writer_t w m) (writer_t w' m') := { congr := λ α β G, writer_t.equiv $ uliftable.congr _ _ $ equiv.prod_congr G F } instance {s m m'} [uliftable m m'] : uliftable (writer_t s m) (writer_t (ulift s) m') := writer_t.uliftable' equiv.ulift.symm
a3beffa7711b679e1ddf634c6a69f56ee92f6e6f
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/topologie-espaces-normés/cpge_ten_12.lean
d7321b9cfa2427103d46690ebf35e6575a19bb57
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
612
lean
import data.set.basic import topology.basic import algebra.module.basic import algebra.module.submodule import order.complete_lattice import analysis.normed_space.basic import linear_algebra.finite_dimensional -- Soient E un espace vectoriel normé, F un sous-espace fermé de E et G un -- sous-espace vectoriel de dimension finie de E. Montrer que F + G est fermé theorem exo {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] : forall (F G: submodule R E), (is_closed F.carrier) -> (finite_dimensional R G) -> (is_closed (F + G)) -- cannot find F + G ... :( := sorry
6d2933fb85ef38e7a2921a349397f2c76541a7aa
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/library/init/data/list/basic.lean
73b196c50000b617934a564d40aa8e2f95cdfa91
[ "Apache-2.0" ]
permissive
HGldJ1966/lean
e7f0068f8a69fde3593b77d8a44609ae446d7738
049d940167c419cd5935d12b459c0695d8615ae9
refs/heads/master
1,611,340,395,700
1,503,103,829,000
1,503,103,829,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,548
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.data.nat.basic init.data.bool.basic open decidable list universes u v w instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace list protected def append : list α → list α → list α | [] l := l | (h :: s) t := h :: (append s t) attribute [simp] list.append instance : has_append (list α) := ⟨list.append⟩ protected def mem : α → list α → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l instance : has_mem α (list α) := ⟨list.mem⟩ instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l) | [] := is_false not_false | (b::l) := if h₁ : a = b then is_true (or.inl h₁) else match decidable_mem l with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (not_or h₁ h₂) end instance : has_emptyc (list α) := ⟨list.nil⟩ protected def erase {α} [decidable_eq α] : list α → α → list α | [] b := [] | (a::l) b := if a = b then l else a :: erase l b protected def bag_inter {α} [decidable_eq α] : list α → list α → list α | [] _ := [] | _ [] := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: bag_inter l₁ (l₂.erase a) else bag_inter l₁ l₂ protected def diff {α} [decidable_eq α] : list α → list α → list α | l [] := l | l₁ (a::l₂) := if a ∈ l₁ then diff (l₁.erase a) l₂ else diff l₁ l₂ def length : list α → nat | [] := 0 | (a :: l) := length l + 1 attribute [simp] length def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n attribute [simp] nth def nth_le : Π (l : list α) (n), n < l.length → α | [] n h := absurd h (not_lt_zero n) | (a :: l) 0 h := a | (a :: l) (n+1) h := nth_le l n (le_of_succ_le_succ h) attribute [simp] nth_le def head [inhabited α] : list α → α | [] := default α | (a :: l) := a attribute [simp] head def tail : list α → list α | [] := [] | (a :: l) := l attribute [simp] tail def reverse_core : list α → list α → list α | [] r := r | (a::l) r := reverse_core l (a::r) def reverse : list α → list α := λ l, reverse_core l [] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l attribute [simp] map def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys attribute [simp] map₂ def join : list (list α) → list α | [] := [] | (l :: ls) := l ++ join ls def filter_map (f : α → option β) : list α → list β | [] := [] | (a::l) := match f a with | none := filter_map l | some b := b :: filter_map l end def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def partition (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::l) := let (l₁, l₂) := partition l in if p a then (a :: l₁, l₂) else (l₁, a :: l₂) def drop_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then drop_while l else a::l def span (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::xs) := if p a then let (l, r) := span xs in (a :: l, r) else ([], a::xs) def find_index (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (a::l) := if p a then 0 else succ (find_index l) def index_of [decidable_eq α] (a : α) : list α → nat := find_index (eq a) def remove_all [decidable_eq α] (xs ys : list α) : list α := filter (∉ ys) xs def update_nth : list α → ℕ → α → list α | (x::xs) 0 a := a :: xs | (x::xs) (i+1) a := x :: update_nth xs i a | [] _ _ := [] def remove_nth : list α → ℕ → list α | [] _ := [] | (x::xs) 0 := xs | (x::xs) (i+1) := x :: remove_nth xs i def drop : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := drop n r attribute [simp] drop def take : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: take n r attribute [simp] take def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l attribute [simp] foldl def foldr (f : α → β → β) (b : β) : list α → β | [] := b | (a :: l) := f a (foldr l) attribute [simp] foldr def any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l def all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def bor (l : list bool) : bool := any l id def band (l : list bool) : bool := all l id def zip_with (f : α → β → γ) : list α → list β → list γ | (x::xs) (y::ys) := f x y :: zip_with xs ys | _ _ := [] def zip : list α → list β → list (prod α β) := zip_with prod.mk def unzip : list (α × β) → list α × list β | [] := ([], []) | ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else a :: l instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ protected def union [decidable_eq α] (l₁ l₂ : list α) : list α := foldr insert l₂ l₁ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] (l₁ l₂ : list α) : list α := filter (∈ l₂) l₁ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n attribute [simp] repeat def range_core : ℕ → list ℕ → list ℕ | 0 l := l | (succ n) l := range_core n (n :: l) def range (n : ℕ) : list ℕ := range_core n [] def iota : ℕ → list ℕ | 0 := [] | (succ n) := succ n :: iota n def enum_from : ℕ → list α → list (ℕ × α) | n [] := nil | n (x :: xs) := (n, x) :: enum_from (n + 1) xs def enum : list α → list (ℕ × α) := enum_from 0 def last : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | [a] h := a | (a::b::l) h := last (b::l) (λ h, list.no_confusion h) attribute [simp] last def ilast [inhabited α] : list α → α | [] := arbitrary α | [a] := a | [a, b] := b | (a::b::l) := ilast l def init : list α → list α | [] := [] | [a] := [] | (a::l) := a::init l def intersperse (sep : α) : list α → list α | [] := [] | [x] := [x] | (x::xs) := x::sep::intersperse xs def intercalate (sep : list α) (xs : list (list α)) : list α := join (intersperse sep xs) @[inline] def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] def ret {α : Type u} (a : α) : list α := [a] end list namespace bin_tree private def to_list_aux : bin_tree α → list α → list α | empty as := as | (leaf a) as := a::as | (node l r) as := to_list_aux l (to_list_aux r as) def to_list (t : bin_tree α) : list α := to_list_aux t [] end bin_tree
0c0ea6eca51eb8c83aa8bb1c3ef08b2c9aedb467
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Arg.lean
08d1d8273c0e5aa383c450e7a026e5008c1430fa
[ "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
2,174
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term namespace Lean.Elab.Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg where | stx (val : Syntax) | expr (val : Expr) deriving Inhabited /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg where ref : Syntax := Syntax.missing name : Name val : Arg deriving Inhabited /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do if namedArgs.any (namedArg.name == ·.name) then throwError "argument '{namedArg.name}' was already set" return namedArgs.push namedArg partial def expandArgs (args : Array Syntax) (pattern := false) : TermElabM (Array NamedArg × Array Arg × Bool) := do let (args, ellipsis) := if args.isEmpty then (args, false) else if args.back.isOfKind ``Lean.Parser.Term.ellipsis then (args.pop, true) else (args, false) let (namedArgs, args) ← args.foldlM (init := (#[], #[])) fun (namedArgs, args) stx => do if stx.getKind == ``Lean.Parser.Term.namedArgument then -- trailing_tparser try ("(" >> ident >> " := ") >> termParser >> ")" let name := stx[1].getId.eraseMacroScopes let val := stx[3] let namedArgs ← addNamedArg namedArgs { ref := stx, name := name, val := Arg.stx val } return (namedArgs, args) else if stx.getKind == ``Lean.Parser.Term.ellipsis then throwErrorAt stx "unexpected '..'" else return (namedArgs, args.push $ Arg.stx stx) return (namedArgs, args, ellipsis) def expandApp (stx : Syntax) (pattern := false) : TermElabM (Syntax × Array NamedArg × Array Arg × Bool) := do let (namedArgs, args, ellipsis) ← expandArgs stx[1].getArgs return (stx[0], namedArgs, args, ellipsis) end Lean.Elab.Term
963e38ba81b985da1e37263c57806b9a32d10291
5a5e1bb8063d7934afac91f30aa17c715821040b
/lean3SOS/src/float/sqrt.lean
e5a4c85968ff5c6edb84a80c9b568eeb70ebcb37
[]
no_license
ramonfmir/leanSOS
1883392d73710db5c6e291a2abd03a6c5b44a42b
14b50713dc887f6d408b7b2bce1f8af5bb619958
refs/heads/main
1,683,348,826,105
1,622,056,982,000
1,622,056,982,000
341,232,766
1
0
null
null
null
null
UTF-8
Lean
false
false
1,202
lean
import data.int.sqrt import data.int.parity import data.rat.sqrt import float.basic namespace float_raw def sqrt (f : float_raw) : float_raw := if (even f.e) then ⟨int.sqrt f.m, f.e / 2⟩ else ⟨int.sqrt (f.m * 2), (f.e - 1) / 2⟩ end float_raw namespace float -- lemmas lemma to_rat.num_neg_exp (f : float_raw) (h : f.e < 0) : (to_rat f).num = f.m := begin simp [to_rat], suffices hsuff : (f.m * 2 ^ f.e : ℚ) = rat.mk f.m (2 ^ int.to_nat (-f.e)), { rw hsuff, -- num_div_eq_of_coprime if we assume x.m is odd? sorry, }, sorry, end lemma to_rat.sqrt {x y : float_raw} (h : to_rat x = to_rat y) : to_rat (float_raw.sqrt x) = to_rat (float_raw.sqrt y) := begin simp [float_raw.sqrt, to_rat] at *, split_ifs, { obtain ⟨kx, hkx⟩ := h_1, obtain ⟨ky, hky⟩ := h_2, rw [hkx, hky], rw [int.mul_div_cancel_left kx (by norm_num : (2 : int) ≠ 0)], rw [int.mul_div_cancel_left ky (by norm_num : (2 : int) ≠ 0)], replace h := congr_arg rat.sqrt h, sorry, }, { sorry, }, { sorry, }, { sorry, }, end def sqrt (f : float) : float := quotient.lift (λ x, ⟦float_raw.sqrt x⟧) (λ a b h, quotient.sound $ begin sorry end) end float
6940807e8dfe49d95c6bee4e1699bdf5844a0ad3
4727251e0cd73359b15b664c3170e5d754078599
/src/order/partition/finpartition.lean
820ff9b7ed432d38ea0cf01fd9a978830c4b7081
[ "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
18,573
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import algebra.big_operators.basic import order.atoms import order.locally_finite import order.sup_indep /-! # Finite partitions In this file, we define finite partitions. A finpartition of `a : α` is a finite set of pairwise disjoint parts `parts : finset α` which does not contain `⊥` and whose supremum is `a`. Finpartitions of a finset are at the heart of Szemerédi's regularity lemma. They are also studied purely order theoretically in Sperner theory. ## Constructions We provide many ways to build finpartitions: * `finpartition.of_erase`: Builds a finpartition by erasing `⊥` for you. * `finpartition.of_subset`: Builds a finpartition from a subset of the parts of a previous finpartition. * `finpartition.empty`: The empty finpartition of `⊥`. * `finpartition.indiscrete`: The indiscrete, aka trivial, aka pure, finpartition made of a single part. * `finpartition.discrete`: The discrete finpartition of `s : finset α` made of singletons. * `finpartition.bind`: Puts together the finpartitions of the parts of a finpartition into a new finpartition. * `finpartition.atomise`: Makes a finpartition of `s : finset α` by breaking `s` along all finsets in `F : finset (finset α)`. Two elements of `s` belong to the same part iff they belong to the same elements of `F`. `finpartition.indiscrete` and `finpartition.bind` together form the monadic structure of `finpartition`. ## Implementation notes Forbidding `⊥` as a part follows mathematical tradition and is a pragmatic choice concerning operations on `finpartition`. Not caring about `⊥` being a part or not breaks extensionality (it's not because the parts of `P` and the parts of `Q` have the same elements that `P = Q`). Enforcing `⊥` to be a part makes `finpartition.bind` uglier and doesn't rid us of the need of `finpartition.of_erase`. ## TODO Link `finpartition` and `setoid.is_partition`. The order is the wrong way around to make `finpartition a` a graded order. Is it bad to depart from the literature and turn the order around? -/ open finset function open_locale big_operators variables {α : Type*} /-- A finite partition of `a : α` is a pairwise disjoint finite set of elements whose supremum is `a`. We forbid `⊥` as a part. -/ @[ext, derive decidable_eq] structure finpartition [lattice α] [order_bot α] (a : α) := (parts : finset α) (sup_indep : parts.sup_indep id) (sup_parts : parts.sup id = a) (not_bot_mem : ⊥ ∉ parts) attribute [protected] finpartition.sup_indep namespace finpartition section lattice variables [lattice α] [order_bot α] /-- A `finpartition` constructor which does not insist on `⊥` not being a part. -/ @[simps] def of_erase [decidable_eq α] {a : α} (parts : finset α) (sup_indep : parts.sup_indep id) (sup_parts : parts.sup id = a) : finpartition a := { parts := parts.erase ⊥, sup_indep := sup_indep.subset (erase_subset _ _), sup_parts := (sup_erase_bot _).trans sup_parts, not_bot_mem := not_mem_erase _ _ } /-- A `finpartition` constructor from a bigger existing finpartition. -/ @[simps] def of_subset {a b : α} (P : finpartition a) {parts : finset α} (subset : parts ⊆ P.parts) (sup_parts : parts.sup id = b) : finpartition b := { parts := parts, sup_indep := P.sup_indep.subset subset, sup_parts := sup_parts, not_bot_mem := λ h, P.not_bot_mem (subset h) } /-- Changes the type of a finpartition to an equal one. -/ @[simps] def copy {a b : α} (P : finpartition a) (h : a = b) : finpartition b := { parts := P.parts, sup_indep := P.sup_indep, sup_parts := h ▸ P.sup_parts, not_bot_mem := P.not_bot_mem } variables (α) /-- The empty finpartition. -/ @[simps] protected def empty : finpartition (⊥ : α) := { parts := ∅, sup_indep := sup_indep_empty _, sup_parts := finset.sup_empty, not_bot_mem := not_mem_empty ⊥ } instance : inhabited (finpartition (⊥ : α)) := ⟨finpartition.empty α⟩ @[simp] lemma default_eq_empty : (default : finpartition (⊥ : α)) = finpartition.empty α := rfl variables {α} {a : α} /-- The finpartition in one part, aka indiscrete finpartition. -/ @[simps] def indiscrete (ha : a ≠ ⊥) : finpartition a := { parts := {a}, sup_indep := sup_indep_singleton _ _, sup_parts := finset.sup_singleton, not_bot_mem := λ h, ha (mem_singleton.1 h).symm } variables (P : finpartition a) protected lemma le {b : α} (hb : b ∈ P.parts) : b ≤ a := (le_sup hb).trans P.sup_parts.le lemma ne_bot {b : α} (hb : b ∈ P.parts) : b ≠ ⊥ := λ h, P.not_bot_mem $ h.subst hb protected lemma disjoint : (P.parts : set α).pairwise_disjoint id := P.sup_indep.pairwise_disjoint variables {P} lemma parts_eq_empty_iff : P.parts = ∅ ↔ a = ⊥ := begin simp_rw ←P.sup_parts, refine ⟨λ h, _, λ h, eq_empty_iff_forall_not_mem.2 (λ b hb, P.not_bot_mem _)⟩, { rw h, exact finset.sup_empty }, { rwa ←le_bot_iff.1 ((le_sup hb).trans h.le) } end lemma parts_nonempty_iff : P.parts.nonempty ↔ a ≠ ⊥ := by rw [nonempty_iff_ne_empty, not_iff_not, parts_eq_empty_iff] lemma parts_nonempty (P : finpartition a) (ha : a ≠ ⊥) : P.parts.nonempty := parts_nonempty_iff.2 ha instance : unique (finpartition (⊥ : α)) := { uniq := λ P, by { ext a, exact iff_of_false (λ h, P.ne_bot h $ le_bot_iff.1 $ P.le h) (not_mem_empty a) }, ..finpartition.inhabited α } /-- There's a unique partition of an atom. -/ @[reducible] -- See note [reducible non instances] def _root_.is_atom.unique_finpartition (ha : is_atom a) : unique (finpartition a) := { default := indiscrete ha.1, uniq := λ P, begin have h : ∀ b ∈ P.parts, b = a, { exact λ b hb, (eq_bot_or_eq_of_le_atom ha $ P.le hb).resolve_left (P.ne_bot hb) }, ext b, refine iff.trans ⟨h b, _⟩ mem_singleton.symm, rintro rfl, obtain ⟨c, hc⟩ := P.parts_nonempty ha.1, simp_rw ←h c hc, exact hc, end } instance [fintype α] [decidable_eq α] (a : α) : fintype (finpartition a) := @fintype.of_surjective {p : finset α // p.sup_indep id ∧ p.sup id = a ∧ ⊥ ∉ p} (finpartition a) _ (subtype.fintype _) (λ i, ⟨i.1, i.2.1, i.2.2.1, i.2.2.2⟩) (λ ⟨_, y, z, w⟩, ⟨⟨_, y, z, w⟩, rfl⟩) /-! ### Refinement order -/ section order /-- We say that `P ≤ Q` if `P` refines `Q`: each part of `P` is less than some part of `Q`. -/ instance : has_le (finpartition a) := ⟨λ P Q, ∀ ⦃b⦄, b ∈ P.parts → ∃ c ∈ Q.parts, b ≤ c⟩ instance : partial_order (finpartition a) := { le_refl := λ P b hb, ⟨b, hb, le_rfl⟩, le_trans := λ P Q R hPQ hQR b hb, begin obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hcd⟩ := hQR hc, exact ⟨d, hd, hbc.trans hcd⟩, end, le_antisymm := λ P Q hPQ hQP, begin ext b, refine ⟨λ hb, _, λ hb, _⟩, { obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hcd⟩ := hQP hc, rwa hbc.antisymm, rwa P.disjoint.eq_of_le hb hd (P.ne_bot hb) (hbc.trans hcd) }, { obtain ⟨c, hc, hbc⟩ := hQP hb, obtain ⟨d, hd, hcd⟩ := hPQ hc, rwa hbc.antisymm, rwa Q.disjoint.eq_of_le hb hd (Q.ne_bot hb) (hbc.trans hcd) } end, ..finpartition.has_le } instance [decidable (a = ⊥)] : order_top (finpartition a) := { top := if ha : a = ⊥ then (finpartition.empty α).copy ha.symm else indiscrete ha, le_top := λ P, begin split_ifs, { intros x hx, simpa [h, P.ne_bot hx] using P.le hx }, { exact λ b hb, ⟨a, mem_singleton_self _, P.le hb⟩ } end } lemma parts_top_subset (a : α) [decidable (a = ⊥)] : (⊤ : finpartition a).parts ⊆ {a} := begin intros b hb, change b ∈ finpartition.parts (dite _ _ _) at hb, split_ifs at hb, { simp only [copy_parts, empty_parts, not_mem_empty] at hb, exact hb.elim }, { exact hb } end lemma parts_top_subsingleton (a : α) [decidable (a = ⊥)] : ((⊤ : finpartition a).parts : set α).subsingleton := set.subsingleton_of_subset_singleton $ λ b hb, mem_singleton.1 $ parts_top_subset _ hb end order end lattice section distrib_lattice variables [distrib_lattice α] [order_bot α] section inf variables [decidable_eq α] {a b c : α} instance : has_inf (finpartition a) := ⟨λ P Q, of_erase ((P.parts.product Q.parts).image $ λ bc, bc.1 ⊓ bc.2) begin rw sup_indep_iff_disjoint_erase, simp only [mem_image, and_imp, exists_prop, forall_exists_index, id.def, prod.exists, mem_product, finset.disjoint_sup_right, mem_erase, ne.def], rintro _ x₁ y₁ hx₁ hy₁ rfl _ h x₂ y₂ hx₂ hy₂ rfl, rcases eq_or_ne x₁ x₂ with rfl | xdiff, { refine disjoint.mono inf_le_right inf_le_right (Q.disjoint hy₁ hy₂ _), intro t, simpa [t] using h }, exact disjoint.mono inf_le_left inf_le_left (P.disjoint hx₁ hx₂ xdiff), end begin rw [sup_image, comp.left_id, sup_product_left], transitivity P.parts.sup id ⊓ Q.parts.sup id, { simp_rw [finset.sup_inf_distrib_right, finset.sup_inf_distrib_left], refl }, { rw [P.sup_parts, Q.sup_parts, inf_idem] } end⟩ @[simp] lemma parts_inf (P Q : finpartition a) : (P ⊓ Q).parts = ((P.parts.product Q.parts).image $ λ bc : α × α, bc.1 ⊓ bc.2).erase ⊥ := rfl instance : semilattice_inf (finpartition a) := { inf_le_left := λ P Q b hb, begin obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb), rw mem_product at hc, exact ⟨c.1, hc.1, inf_le_left⟩, end, inf_le_right := λ P Q b hb, begin obtain ⟨c, hc, rfl⟩ := mem_image.1 (mem_of_mem_erase hb), rw mem_product at hc, exact ⟨c.2, hc.2, inf_le_right⟩, end, le_inf := λ P Q R hPQ hPR b hb, begin obtain ⟨c, hc, hbc⟩ := hPQ hb, obtain ⟨d, hd, hbd⟩ := hPR hb, have h := _root_.le_inf hbc hbd, refine ⟨c ⊓ d, mem_erase_of_ne_of_mem (ne_bot_of_le_ne_bot (P.ne_bot hb) h) (mem_image.2 ⟨(c, d), mem_product.2 ⟨hc, hd⟩, rfl⟩), h⟩, end, ..finpartition.partial_order, ..finpartition.has_inf } end inf lemma exists_le_of_le {a b : α} {P Q : finpartition a} (h : P ≤ Q) (hb : b ∈ Q.parts) : ∃ c ∈ P.parts, c ≤ b := begin by_contra' H, refine Q.ne_bot hb (disjoint_self.1 $ disjoint.mono_right (Q.le hb) _), rw [←P.sup_parts, finset.disjoint_sup_right], rintro c hc, obtain ⟨d, hd, hcd⟩ := h hc, refine (Q.disjoint hb hd _).mono_right hcd, rintro rfl, exact H _ hc hcd, end lemma card_mono {a : α} {P Q : finpartition a} (h : P ≤ Q) : Q.parts.card ≤ P.parts.card := begin classical, have : ∀ b ∈ Q.parts, ∃ c ∈ P.parts, c ≤ b := λ b, exists_le_of_le h, choose f hP hf using this, rw ←card_attach, refine card_le_card_of_inj_on (λ b, f _ b.2) (λ b _, hP _ b.2) (λ b hb c hc h, _), exact subtype.coe_injective (Q.disjoint.elim b.2 c.2 $ λ H, P.ne_bot (hP _ b.2) $ disjoint_self.1 $ H.mono (hf _ b.2) $ h.le.trans $ hf _ c.2), end variables [decidable_eq α] {a b c : α} section bind variables {P : finpartition a} {Q : Π i ∈ P.parts, finpartition i} /-- Given a finpartition `P` of `a` and finpartitions of each part of `P`, this yields the finpartition of `a` obtained by juxtaposing all the subpartitions. -/ @[simps] def bind (P : finpartition a) (Q : Π i ∈ P.parts, finpartition i) : finpartition a := { parts := P.parts.attach.bUnion (λ i, (Q i.1 i.2).parts), sup_indep := begin rw sup_indep_iff_pairwise_disjoint, rintro a ha b hb h, rw [finset.mem_coe, finset.mem_bUnion] at ha hb, obtain ⟨⟨A, hA⟩, -, ha⟩ := ha, obtain ⟨⟨B, hB⟩, -, hb⟩ := hb, obtain rfl | hAB := eq_or_ne A B, { exact (Q A hA).disjoint ha hb h }, { exact (P.disjoint hA hB hAB).mono ((Q A hA).le ha) ((Q B hB).le hb) } end, sup_parts := begin simp_rw [sup_bUnion, ←P.sup_parts], rw [eq_comm, ←finset.sup_attach], exact sup_congr rfl (λ b hb, (Q b.1 b.2).sup_parts.symm), end, not_bot_mem := λ h, begin rw finset.mem_bUnion at h, obtain ⟨⟨A, hA⟩, -, h⟩ := h, exact (Q A hA).not_bot_mem h, end } lemma mem_bind : b ∈ (P.bind Q).parts ↔ ∃ A hA, b ∈ (Q A hA).parts := begin rw [bind, mem_bUnion], split, { rintro ⟨⟨A, hA⟩, -, h⟩, exact ⟨A, hA, h⟩ }, { rintro ⟨A, hA, h⟩, exact ⟨⟨A, hA⟩, mem_attach _ ⟨A, hA⟩, h⟩ } end lemma card_bind (Q : Π i ∈ P.parts, finpartition i) : (P.bind Q).parts.card = ∑ A in P.parts.attach, (Q _ A.2).parts.card := begin apply card_bUnion, rintro ⟨b, hb⟩ - ⟨c, hc⟩ - hbc d, rw [inf_eq_inter, mem_inter], rintro ⟨hdb, hdc⟩, rw [ne.def, subtype.mk_eq_mk] at hbc, exact (Q b hb).ne_bot hdb (eq_bot_iff.2 $ (le_inf ((Q b hb).le hdb) $ (Q c hc).le hdc).trans $ P.disjoint hb hc hbc), end end bind /-- Adds `b` to a finpartition of `a` to make a finpartition of `a ⊔ b`. -/ @[simps] def extend (P : finpartition a) (hb : b ≠ ⊥) (hab : disjoint a b) (hc : a ⊔ b = c) : finpartition c := { parts := insert b P.parts, sup_indep := begin rw [sup_indep_iff_pairwise_disjoint, coe_insert], exact P.disjoint.insert (λ d hd hbd, hab.symm.mono_right $ P.le hd), end, sup_parts := by rwa [sup_insert, P.sup_parts, id, _root_.sup_comm], not_bot_mem := λ h, (mem_insert.1 h).elim hb.symm P.not_bot_mem } lemma card_extend (P : finpartition a) (b c : α) {hb : b ≠ ⊥} {hab : disjoint a b} {hc : a ⊔ b = c} : (P.extend hb hab hc).parts.card = P.parts.card + 1 := card_insert_of_not_mem $ λ h, hb $ hab.symm.eq_bot_of_le $ P.le h end distrib_lattice section generalized_boolean_algebra variables [generalized_boolean_algebra α] [decidable_eq α] {a : α} (P : finpartition a) /-- Restricts a finpartition to avoid a given element. -/ @[simps] def avoid (b : α) : finpartition (a \ b) := of_erase (P.parts.image (\ b)) (P.disjoint.image_finset_of_le $ λ a, sdiff_le).sup_indep (begin rw [sup_image, comp.left_id, finset.sup_sdiff_right], congr, exact P.sup_parts, end) end generalized_boolean_algebra end finpartition /-! ### Finite partitions of finsets -/ namespace finpartition variables [decidable_eq α] {s t : finset α} (P : finpartition s) lemma nonempty_of_mem_parts {a : finset α} (ha : a ∈ P.parts) : a.nonempty := nonempty_iff_ne_empty.2 $ P.ne_bot ha lemma exists_mem {a : α} (ha : a ∈ s) : ∃ t ∈ P.parts, a ∈ t := by { simp_rw ←P.sup_parts at ha, exact mem_sup.1 ha } lemma bUnion_parts : P.parts.bUnion id = s := (sup_eq_bUnion _ _).symm.trans P.sup_parts lemma sum_card_parts : ∑ i in P.parts, i.card = s.card := begin convert congr_arg finset.card P.bUnion_parts, rw card_bUnion P.sup_indep.pairwise_disjoint, refl, end /-- `⊥` is the partition in singletons, aka discrete partition. -/ instance (s : finset α) : has_bot (finpartition s) := ⟨{ parts := s.map ⟨singleton, singleton_injective⟩, sup_indep := set.pairwise_disjoint.sup_indep begin rw finset.coe_map, exact finset.pairwise_disjoint_range_singleton.subset (set.image_subset_range _ _), end, sup_parts := by rw [sup_map, comp.left_id, embedding.coe_fn_mk, finset.sup_singleton'], not_bot_mem := by simp }⟩ @[simp] lemma parts_bot (s : finset α) : (⊥ : finpartition s).parts = s.map ⟨singleton, singleton_injective⟩ := rfl lemma card_bot (s : finset α) : (⊥ : finpartition s).parts.card = s.card := finset.card_map _ lemma mem_bot_iff : t ∈ (⊥ : finpartition s).parts ↔ ∃ a ∈ s, {a} = t := mem_map instance (s : finset α) : order_bot (finpartition s) := { bot_le := λ P t ht, begin rw mem_bot_iff at ht, obtain ⟨a, ha, rfl⟩ := ht, obtain ⟨t, ht, hat⟩ := P.exists_mem ha, exact ⟨t, ht, singleton_subset_iff.2 hat⟩, end, ..finpartition.has_bot s } lemma card_parts_le_card (P : finpartition s) : P.parts.card ≤ s.card := by { rw ←card_bot s, exact card_mono bot_le } section atomise /-- Cuts `s` along the finsets in `F`: Two elements of `s` will be in the same part if they are in the same finsets of `F`. -/ def atomise (s : finset α) (F : finset (finset α)) : finpartition s := of_erase (F.powerset.image $ λ Q, s.filter (λ i, ∀ t ∈ F, t ∈ Q ↔ i ∈ t)) (set.pairwise_disjoint.sup_indep $ λ x hx y hy h z hz, h begin rw [mem_coe, mem_image] at hx hy, obtain ⟨Q, hQ, rfl⟩ := hx, obtain ⟨R, hR, rfl⟩ := hy, suffices h : Q = R, { subst h }, rw [id, id, inf_eq_inter, mem_inter, mem_filter, mem_filter] at hz, rw mem_powerset at hQ hR, ext i, refine ⟨λ hi, _, λ hi, _⟩, { rwa [hz.2.2 _ (hQ hi), ←hz.1.2 _ (hQ hi)] }, { rwa [hz.1.2 _ (hR hi), ←hz.2.2 _ (hR hi)] } end) (begin refine (finset.sup_le $ λ t ht, _).antisymm (λ a ha, _), { rw mem_image at ht, obtain ⟨A, hA, rfl⟩ := ht, exact s.filter_subset _ }, { rw [mem_sup], refine ⟨s.filter (λ i, ∀ t, t ∈ F → (t ∈ F.filter (λ u, a ∈ u) ↔ i ∈ t)), mem_image_of_mem _ (mem_powerset.2 $ filter_subset _ _), mem_filter.2 ⟨ha, λ t ht, _⟩⟩, rw mem_filter, exact and_iff_right ht } end) variables {F : finset (finset α)} lemma mem_atomise {t : finset α} : t ∈ (atomise s F).parts ↔ t.nonempty ∧ ∃ (Q ⊆ F), s.filter (λ i, ∀ u ∈ F, u ∈ Q ↔ i ∈ u) = t := by simp only [atomise, of_erase, bot_eq_empty, mem_erase, mem_image, nonempty_iff_ne_empty, mem_singleton, and_comm, mem_powerset, exists_prop] lemma atomise_empty (hs : s.nonempty) : (atomise s ∅).parts = {s} := begin simp only [atomise, powerset_empty, image_singleton, not_mem_empty, forall_false_left, implies_true_iff, filter_true], exact erase_eq_of_not_mem (not_mem_singleton.2 hs.ne_empty.symm), end lemma card_atomise_le : (atomise s F).parts.card ≤ 2^F.card := (card_le_of_subset $ erase_subset _ _).trans $ finset.card_image_le.trans (card_powerset _).le lemma bUnion_filter_atomise (t : finset α) (ht : t ∈ F) (hts : t ⊆ s) : ((atomise s F).parts.filter $ λ u, u ⊆ t).bUnion id = t := begin ext a, rw mem_bUnion, refine ⟨λ ⟨u, hu, ha⟩, (mem_filter.1 hu).2 ha, λ ha, _⟩, obtain ⟨u, hu, hau⟩ := (atomise s F).exists_mem (hts ha), refine ⟨u, mem_filter.2 ⟨hu, λ b hb, _⟩, hau⟩, obtain ⟨Q, hQ, rfl⟩ := (mem_atomise.1 hu).2, rw mem_filter at hau hb, rwa [←hb.2 _ ht, hau.2 _ ht] end end atomise end finpartition
4e65d2bffbec469953fca569c10e5b3498cf9668
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex30.lean
8ea5f7d507d6179059c1cf51bc54997b765fdc56
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
389
lean
theorem t1 (p q : Prop) : p → q → p := λ (hp : p) (hq : q), hp variables p q r s : Prop check t1 p q -- p → q → p check t1 r s -- r → s → r check t1 (r → s) (s → r) -- (r → s) → (s → r) → r → s variable h : r → s check t1 (r → s) (s → r) h -- (s → r) → r → s premise h' : r → s check t1 (r → s) (s → r) h'
d67ff6bf779ac8892edeba959b72a91863f5afd7
859855170b866e395d328ebb28c4e060aa5559e8
/src/solutions/05_sequence_limits.lean
c613fb9b7223083a37211c5c945d36b08128fe3c
[ "Apache-2.0" ]
permissive
bradheintz/tutorials
1be40c9e97a484441f268ea8504c3d74534162cf
02f15b400478de7278f4baa08935befd0f3986ef
refs/heads/master
1,688,028,802,367
1,627,863,284,000
1,627,863,284,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,635
lean
import data.real.basic import algebra.group.pi import tuto_lib notation `|`x`|` := abs x /- In this file we manipulate the elementary definition of limits of sequences of real numbers. mathlib has a much more general definition of limits, but here we want to practice using the logical operators and relations covered in the previous files. A sequence u is a function from ℕ to ℝ, hence Lean says u : ℕ → ℝ The definition we'll be using is: -- Definition of « u tends to l » def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε Note the use of `∀ ε > 0, ...` which is an abbreviation of `∀ ε, ε > 0 → ... ` In particular, a statement like `h : ∀ ε > 0, ...` can be specialized to a given ε₀ by `specialize h ε₀ hε₀` where hε₀ is a proof of ε₀ > 0. Also recall that, wherever Lean expects some proof term, we can start a tactic mode proof using the keyword `by` (followed by curly braces if you need more than one tactic invocation). For instance, if the local context contains: δ : ℝ δ_pos : δ > 0 h : ∀ ε > 0, ... then we can specialize h to the real number δ/2 using: `specialize h (δ/2) (by linarith)` where `by linarith` will provide the proof of `δ/2 > 0` expected by Lean. We'll take this opportunity to use two new tactics: `norm_num` will perform numerical normalization on the goal and `norm_num at h` will do the same in assumption `h`. This will get rid of trivial calculations on numbers, like replacing |l - l| by zero in the next exercise. `congr'` will try to prove equalities between applications of functions by recursively proving the arguments are the same. For instance, if the goal is `f x + g y = f z + g t` then congr will replace it by two goals: `x = z` and `y = t`. You can limit the recursion depth by specifying a natural number after `congr'`. For instance, in the above example, `congr' 1` will give new goals `f x = f z` and `g y = g t`, which only inspect arguments of the addition and not deeper. -/ variables (u v w : ℕ → ℝ) (l l' : ℝ) -- If u is constant with value l then u tends to l -- 0033 example : (∀ n, u n = l) → seq_limit u l := begin -- sorry intros h ε ε_pos, use 0, intros n hn, rw h, norm_num, linarith, -- sorry end /- When dealing with absolute values, we'll use lemmas: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub_comm (x y : ℝ) : |x - y| = |y - x| You should probably write them down on a sheet of paper that you keep at hand since they are used in many exercises. -/ -- Assume l > 0. Then u tends to l implies u n ≥ l/2 for large enough n -- 0034 example (hl : l > 0) : seq_limit u l → ∃ N, ∀ n ≥ N, u n ≥ l/2 := begin -- sorry intro h, cases h (l/2) (by linarith) with N hN, use N, intros n hn, specialize hN n hn, rw abs_le at hN, linarith, -- sorry end /- When dealing with max, you can use ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q You should probably add them to the sheet of paper where you wrote the `abs` lemmas since they are used in many exercises. Let's see an example. -/ -- If u tends to l and v tends l' then u+v tends to l+l' example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, cases ge_max_iff.mp hn with hn₁ hn₂, have fact₁ : |u n - l| ≤ ε/2, from hN₁ n (by linarith), -- note the use of `from`. -- This is an alias for `exact`, -- but reads nicer in this context have fact₂ : |v n - l'| ≤ ε/2, from hN₂ n (by linarith), calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith, end /- In the above proof, we used `have` to prepare facts for `linarith` consumption in the last line. Since we have direct proof terms for them, we can feed them directly to `linarith` as in the next proof of the same statement. Another variation we introduce is rewriting using `ge_max_iff` and letting `linarith` handle the conjunction, instead of creating two new assumptions. -/ example (hu : seq_limit u l) (hv : seq_limit v l') : seq_limit (u + v) (l + l') := begin intros ε ε_pos, cases hu (ε/2) (by linarith) with N₁ hN₁, cases hv (ε/2) (by linarith) with N₂ hN₂, use max N₁ N₂, intros n hn, rw ge_max_iff at hn, calc |(u + v) n - (l + l')| = |u n + v n - (l + l')| : rfl ... = |(u n - l) + (v n - l')| : by congr' 1 ; ring ... ≤ |u n - l| + |v n - l'| : by apply abs_add ... ≤ ε : by linarith [hN₁ n (by linarith), hN₂ n (by linarith)], end /- Let's do something similar: the squeezing theorem. -/ -- 0035 example (hu : seq_limit u l) (hw : seq_limit w l) (h : ∀ n, u n ≤ v n) (h' : ∀ n, v n ≤ w n) : seq_limit v l := begin -- sorry intros ε ε_pos, cases hu ε ε_pos with N hN, cases hw ε ε_pos with N' hN', use max N N', intros n hn, rw ge_max_iff at hn, specialize hN n (by linarith), specialize hN' n (by linarith), specialize h n, specialize h' n, rw abs_le at *, split, -- Here `linarith` can finish, but on paper we would write calc -ε ≤ u n - l : by linarith ... ≤ v n - l : by linarith, calc v n - l ≤ w n - l : by linarith ... ≤ ε : by linarith, -- sorry end /- What about < ε? -/ -- 0036 example (u l) : seq_limit u l ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| < ε := begin -- sorry split, { intros hyp ε ε_pos, cases hyp (ε/2) (by linarith) with N hN, use N, intros n hn, calc |u n - l| ≤ ε/2 : by exact hN n hn ... < ε : by linarith, }, { intros hyp ε ε_pos, cases hyp ε ε_pos with N hN, use N, intros n hn, specialize hN n hn, linarith, }, -- sorry end /- In the next exercise, we'll use eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y -/ -- A sequence admits at most one limit -- 0037 example : seq_limit u l → seq_limit u l' → l = l' := begin -- sorry intros hl hl', apply eq_of_abs_sub_le_all, intros ε ε_pos, cases hl (ε/2) (by linarith) with N hN, cases hl' (ε/2) (by linarith) with N' hN', calc |l - l'| = |(l-u (max N N')) + (u (max N N') -l')| : by ring_nf ... ≤ |l - u (max N N')| + |u (max N N') - l'| : by apply abs_add ... = |u (max N N') - l| + |u (max N N') - l'| : by rw abs_sub_comm ... ≤ ε : by linarith [hN (max N N') (le_max_left _ _), hN' (max N N') (le_max_right _ _)] -- sorry end /- Let's now practice deciphering definitions before proving. -/ def non_decreasing (u : ℕ → ℝ) := ∀ n m, n ≤ m → u n ≤ u m def is_seq_sup (M : ℝ) (u : ℕ → ℝ) := (∀ n, u n ≤ M) ∧ ∀ ε > 0, ∃ n₀, u n₀ ≥ M - ε -- 0038 example (M : ℝ) (h : is_seq_sup M u) (h' : non_decreasing u) : seq_limit u M := begin -- sorry intros ε ε_pos, cases h with inf_M sup_M_ep, cases sup_M_ep ε ε_pos with n₀ hn₀, use n₀, intros n hn, rw abs_le, split; linarith [inf_M n, h' n₀ n hn], -- sorry end
6feac587f22d43d94a20fa703d8592c798263ff0
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/algebra/uniform_ring.lean
727bf82e1678274f27f8be9383c460d3725ba3ca
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
7,494
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Theory of topological rings with uniform structure. -/ import topology.algebra.group_completion topology.algebra.ring open classical set lattice filter topological_space add_comm_group open_locale classical noncomputable theory namespace uniform_space.completion open dense_inducing uniform_space function variables (α : Type*) [ring α] [uniform_space α] instance : has_one (completion α) := ⟨(1:α)⟩ instance : has_mul (completion α) := ⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry' (*))⟩ @[elim_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl variables {α} [topological_ring α] @[move_cast] lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b := ((dense_inducing_coe.prod dense_inducing_coe).extend_eq_of_cont ((continuous_coe α).comp continuous_mul) (a, b)).symm variables [uniform_add_group α] lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) := begin haveI : is_Z_bilin ((coe ∘ uncurry' (*)) : α × α → completion α) := { add_left := begin introv, change coe ((a + a')*b) = coe (a*b) + coe (a'*b), rw_mod_cast add_mul end, add_right := begin introv, change coe (a*(b + b')) = coe (a*b) + coe (a*b'), rw_mod_cast mul_add end }, have : continuous ((coe ∘ uncurry' (*)) : α × α → completion α), from (continuous_coe α).comp continuous_mul, convert dense_inducing_coe.extend_Z_bilin dense_inducing_coe this, simp only [(*), curry, prod.mk.eta] end lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α} (hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) := continuous_mul.comp (continuous.prod_mk hf hg) instance : ring (completion α) := { one_mul := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, one_mul]), mul_one := assume a, completion.induction_on a (is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id) (assume a, by rw [← coe_one, ← coe_mul, mul_one]), mul_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.mul continuous_fst (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]), left_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul continuous_fst (continuous.add (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))) (continuous.add (continuous.mul continuous_fst (continuous_fst.comp continuous_snd)) (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]), right_distrib := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous.mul (continuous.add continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous.add (continuous.mul continuous_fst (continuous_snd.comp continuous_snd)) (continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]), ..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α } instance is_ring_hom_coe : is_ring_hom (coe : α → completion α) := ⟨coe_one α, assume a b, coe_mul a b, assume a b, coe_add a b⟩ universes u variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β] {f : α → β} [is_ring_hom f] (hf : continuous f) /-- The completion extension is a ring morphism. This cannot be an instance, since it depends on the continuity of `f`. -/ protected lemma is_ring_hom_extension [complete_space β] [separated β] : is_ring_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { map_one := by rw [← coe_one, extension_coe hf, is_ring_hom.map_one f], map_add := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, is_add_hom.map_add f]), map_mul := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_mul) ((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd))) (assume a b, by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, is_ring_hom.map_mul f]) } instance top_ring_compl : topological_ring (completion α) := { continuous_add := continuous_add, continuous_mul := continuous_mul, continuous_neg := continuous_neg } /-- The completion map is a ring morphism. This cannot be an instance, since it depends on the continuity of `f`. -/ protected lemma is_ring_hom_map : is_ring_hom (completion.map f) := (completion.is_ring_hom_extension $ (continuous_coe β).comp hf : _) variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R] instance : comm_ring (completion R) := { mul_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_fst.mul continuous_snd) (continuous_snd.mul continuous_fst)) (assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]), ..completion.ring } end uniform_space.completion namespace uniform_space variables {α : Type*} lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) := setoid.ext $ assume x y, group_separation_rel x y lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient := by rw [@ring_sep_rel α r]; refl def sep_quot_equiv_ring_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient := quotient.congr_right $ assume x y, group_separation_rel x y /- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/ instance [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : comm_ring (quotient (separation_setoid α)) := by rw ring_sep_quot α; apply_instance instance [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] : topological_ring (quotient (separation_setoid α)) := begin convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel}, simp [uniform_space.comm_ring] end end uniform_space
3018d9ffd46950f999430fa9f7b714b4fe6ff480
4fa161becb8ce7378a709f5992a594764699e268
/src/measure_theory/borel_space.lean
8c259c91cac66fc5c7e338ff985b48256b50724e
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
29,418
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.measurable_space import topology.instances.ennreal import analysis.normed_space.basic /-! # 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`, `ennreal`. ## Main statements * `is_open.is_measurable`, `is_closed.is_measurable`: 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`; * `measurable.ennreal*` : special cases for arithmetic operations on `ennreal`s. -/ noncomputable theory open classical set open_locale classical big_operators universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : 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 is_measurable.bUnion s.countable_encodable, intros x hx, apply is_measurable.of_compl, apply generate_measurable.basic, exact is_closed_singleton 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 @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.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 @is_measurable.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 borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : 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 α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (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 is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Ioi) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : Iio a = -Ioi a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Iio a = ⋃ x : v, -Ioi x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, 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'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end 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 := generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hf s hs) /-- 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 γ] [measurable_space δ] lemma is_open.is_measurable (h : is_open s) : is_measurable s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h lemma is_measurable_interior : is_measurable (interior s) := is_open_interior.is_measurable lemma is_closed.is_measurable (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ h.is_measurable lemma is_measurable_singleton [t1_space α] {x : α} : is_measurable ({x} : set α) := is_closed_singleton.is_measurable lemma is_measurable_eq [t1_space α] {a : α} : is_measurable {x | x = a} := is_measurable_singleton lemma is_measurable_closure : is_measurable (closure s) := is_closed_closure.is_measurable section order_closed_topology variables [preorder α] [order_closed_topology α] {a b : α} lemma is_measurable_Ici : is_measurable (Ici a) := is_closed_Ici.is_measurable lemma is_measurable_Iic : is_measurable (Iic a) := is_closed_Iic.is_measurable lemma is_measurable_Icc : is_measurable (Icc a b) := is_closed_Icc.is_measurable end order_closed_topology section order_closed_topology variables [linear_order α] [order_closed_topology α] {a b : α} lemma is_measurable_Iio : is_measurable (Iio a) := is_open_Iio.is_measurable lemma is_measurable_Ioi : is_measurable (Ioi a) := is_open_Ioi.is_measurable lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_open_Ioo.is_measurable lemma is_measurable_Ioc : is_measurable (Ioc a b) := is_measurable_Ioi.inter is_measurable_Iic lemma is_measurable_Ico : is_measurable (Ico a b) := is_measurable_Ici.inter is_measurable_Iio end order_closed_topology lemma is_measurable_interval [decidable_linear_order α] [order_closed_topology α] {a b : α} : is_measurable (interval a b) := is_measurable_Icc instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin refine ⟨_⟩, rcases is_open_generated_countable_inter α with ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩, rcases is_open_generated_countable_inter β with ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩, have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨u, hu, v, hv, rfl⟩, have hu : is_open u, by { rw [ha₅], exact generate_open.basic _ hu }, have hv : is_open v, by { rw [hb₅], exact generate_open.basic _ hv }, exact hu.is_measurable.prod hv.is_measurable end /-- 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 homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv {α : Type*} {β : Type*} [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] (h : α ≃ₜ β) : measurable_equiv α β := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {x | x ≠ a}) : measurable f := measurable_of_measurable_on_compl_singleton a is_measurable_singleton (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 measurable.smul [semiring α] [second_countable_topology α] [add_comm_monoid γ] [second_countable_topology γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → α} {g : δ → γ} (hf : measurable f) (hg : measurable g) : measurable (λ c, f c • g c) := continuous_smul.measurable2 hf hg lemma measurable.const_smul {α : Type*} [topological_space α] [semiring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} (hf : measurable f) (c : α) : measurable (λ x, c • f x) := (continuous_const.smul continuous_id).measurable.comp hf lemma measurable_const_smul_iff {α : Type*} [topological_space α] [division_ring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} {c : α} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.const_smul c⁻¹, λ h, h.const_smul c⟩ lemma is_measurable_le' [partial_order α] [order_closed_topology α] [second_countable_topology α] : is_measurable {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.is_measurable lemma is_measurable_le [partial_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := (hf.prod_mk hg).preimage is_measurable_le' lemma measurable.max [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, max (f a) (g a)) := measurable.if (is_measurable_le hf hg) hg hf lemma measurable.min [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, min (f a) (g a)) := measurable.if (is_measurable_le hf hg) hf hg 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 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 prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ @[to_additive] lemma measurable_mul [monoid α] [topological_monoid α] [second_countable_topology α] : measurable (λ p : α × α, p.1 * p.2) := continuous_mul.measurable @[to_additive] lemma measurable.mul [monoid α] [topological_monoid α] [second_countable_topology α] {f : δ → α} {g : δ → α} : measurable f → measurable g → measurable (λa, f a * g a) := continuous_mul.measurable2 @[to_additive] lemma finset.measurable_prod {ι : Type*} [comm_monoid α] [topological_monoid α] [second_countable_topology α] {f : ι → δ → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, ∏ i in s, f i a) := finset.induction_on s (by simp only [finset.prod_empty, measurable_const]) (assume i s his ih, by simpa [his] using (hf i).mul ih) @[to_additive] lemma measurable_inv [group α] [topological_group α] : measurable (has_inv.inv : α → α) := continuous_inv.measurable @[to_additive] lemma measurable.inv [group α] [topological_group α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv.comp hf lemma measurable_inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] : measurable (has_inv.inv : α → α) := measurable_of_continuous_on_compl_singleton 0 normed_field.continuous_on_inv lemma measurable.inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv'.comp hf @[to_additive] lemma measurable.of_inv [group α] [topological_group α] {f : δ → α} (hf : measurable (λ a, (f a)⁻¹)) : measurable f := by simpa only [inv_inv] using hf.inv @[to_additive] lemma measurable_inv_iff [group α] [topological_group α] {f : δ → α} : measurable (λ a, (f a)⁻¹) ↔ measurable f := ⟨measurable.of_inv, measurable.inv⟩ lemma measurable.sub [add_group α] [topological_add_group α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x - g x) := hf.add hg.neg lemma measurable.is_lub [linear_order α] [order_topology α] [second_countable_topology α] {ι} [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 only [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_lt' _).is_measurable) end lemma measurable.is_glb [linear_order α] [order_topology α] [second_countable_topology α] {ι} [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 only [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_gt' _).is_measurable) end lemma measurable_supr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable_infi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi 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) 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) lemma measurable_bsupr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i (hi : p i), f i b) := measurable_supr $ λ i, (hf i).supr_Prop (p i) lemma measurable_binfi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i (hi : p i), f i b) := measurable_infi $ λ i, (hf i).infi_Prop (p i) /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : measurable_equiv α β := { 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 nnreal := borel nnreal instance nnreal.borel_space : borel_space nnreal := ⟨rfl⟩ instance ennreal.measurable_space : measurable_space ennreal := borel ennreal instance ennreal.borel_space : borel_space ennreal := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ℝ} lemma is_measurable_ball : is_measurable (metric.ball x ε) := metric.is_open_ball.is_measurable lemma is_measurable_closed_ball : is_measurable (metric.closed_ball x ε) := metric.is_closed_ball.is_measurable lemma measurable_dist [second_countable_topology α] : measurable (λp:α×α, dist p.1 p.2) := continuous_dist.measurable lemma measurable.dist [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := continuous_dist.measurable2 hf hg lemma measurable_nndist [second_countable_topology α] : measurable (λp:α×α, nndist p.1 p.2) := continuous_nndist.measurable lemma measurable.nndist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, nndist (f b) (g b)) := continuous_nndist.measurable2 end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ennreal} lemma is_measurable_eball : is_measurable (emetric.ball x ε) := emetric.is_open_ball.is_measurable lemma measurable_edist [second_countable_topology α] : measurable (λp:α×α, edist p.1 p.2) := continuous_edist.measurable lemma measurable.edist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, edist (f b) (g b)) := continuous_edist.measurable2 end emetric_space namespace real open measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 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.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_open_Iio.is_measurable } end end real lemma measurable.sub_nnreal [measurable_space α] {f g : α → nnreal} : measurable f → measurable g → measurable (λ a, f a - g a) := nnreal.continuous_sub.measurable2 lemma measurable.nnreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, nnreal.of_real (f x)) := nnreal.continuous_of_real.measurable.comp hf lemma measurable.nnreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := nnreal.continuous_coe.measurable.comp hf lemma measurable.ennreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ennreal)) := (ennreal.continuous_coe.2 continuous_id).measurable.comp hf lemma measurable.ennreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ennreal` numbers is `measurable_equiv` to `nnreal`. -/ def measurable_equiv.ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r ≠ ⊤} nnreal := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal open filter lemma measurable_coe : measurable (coe : nnreal → ennreal) := measurable_id.ennreal_coe lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α} (h : measurable (λp:nnreal, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ⊤ is_measurable_singleton (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ennreal` is `measurable_equiv` to `nnreal ⊕ unit`. -/ def ennreal_equiv_sum : measurable_equiv ennreal (nnreal ⊕ unit) := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤), .. equiv.option_equiv_sum_punit nnreal } lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β] (f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal} (h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2)) (h₂ : measurable (λr:nnreal, f ⊤ r)) (h₃ : measurable (λr:nnreal, f r ⊤)) (hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) := let e : measurable_equiv (ennreal × ennreal) (((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) := (measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans (measurable_equiv.sum_prod_sum _ _ _ _) in have measurable (λp:ennreal×ennreal, f p.1 p.2), begin refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)), { show measurable (λp:nnreal × nnreal, f p.1 p.2), exact h₁ }, { show measurable (λp:nnreal × unit, f p.1 ⊤), exact h₃.comp (measurable.fst measurable_id) }, { show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)), exact h₂.comp (measurable.snd measurable_id) }, { show measurable (λp:unit × unit, f ⊤ ⊤), exact measurable_const } end, this.comp (measurable.prod_mk hg hh) lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable end ennreal lemma measurable.ennreal_mul {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a * g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (*) _ _ _, { simp only [ennreal.coe_mul.symm], exact ennreal.measurable_coe.comp measurable_mul }, { simp [ennreal.top_mul], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const }, { simp [ennreal.mul_top], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const } end lemma measurable.ennreal_add {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a + g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (+) _ _ _, { simp only [ennreal.coe_add.symm], exact ennreal.measurable_coe.comp measurable_add }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable.ennreal_sub {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a - g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _, { simp only [ennreal.coe_sub.symm], exact ennreal.measurable_coe.comp nnreal.continuous_sub.measurable }, { simp [measurable_const] }, { simp [measurable_const] } end section normed_group variables [measurable_space α] [normed_group α] [opens_measurable_space α] [measurable_space β] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) := measurable_norm.comp hf lemma measurable_nnnorm : measurable (nnnorm : α → nnreal) := continuous_nnnorm.measurable lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) := measurable_nnnorm.comp hf lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) := hf.nnnorm.ennreal_coe end normed_group
92432cb2beeef7f6e9bbeb15dd1cb9f907a8524b
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/tactic/finish.lean
f5867bb2c4986754b3215ecf8d63241185b92ed1
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,468
lean
/- Copyright (c) 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad These tactics do straightforward things: they call the simplifier, split conjunctive assumptions, eliminate existential quantifiers on the left, and look for contradictions. They rely on ematching and congruence closure to try to finish off a goal at the end. The procedures *do* split on disjunctions and recreate the smt state for each terminal call, so they are only meant to be used on small, straightforward problems. We provide the following tactics: finish -- solves the goal or fails clarify -- makes as much progress as possible while not leaving more than one goal safe -- splits freely, finishes off whatever subgoals it can, and leaves the rest All accept an optional list of simplifier rules, typically definitions that should be expanded. (The equations and identities should not refer to the local context.) The variants ifinish, iclarify, and isafe restrict to intuitionistic logic. They do not work well with the current heuristic instantiation method used by ematch, so they should be revisited when the API changes. -/ import logic.basic declare_trace auto.done declare_trace auto.finish -- TODO(Jeremy): move these namespace tactic /- call (assert n t) with a fresh name n. -/ meta def assert_fresh (t : expr) : tactic expr := do n ← get_unused_name `h none, assert n t /- call (assertv n t v) with a fresh name n. -/ meta def assertv_fresh (t : expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, assertv h t v -- returns the number of hypotheses reverted meta def revert_all : tactic ℕ := do ctx ← local_context, revert_lst ctx namespace interactive meta def revert_all := tactic.revert_all end interactive end tactic open tactic expr namespace auto /- Utilities -/ meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible -- stolen from interactive.lean meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns /- Configuration information for the auto tactics. -/ structure auto_config : Type := (use_simp := tt) -- call the simplifier (classical := tt) -- use classical logic (max_ematch_rounds := 20) -- for the "done" tactic /- Preprocess goal. We want to move everything to the left of the sequent arrow. For intuitionistic logic, we replace the goal p with ∀ f, (p → f) → f and introduce. -/ theorem by_contradiction_trick (p : Prop) (h : ∀ f : Prop, (p → f) → f) : p := h p id meta def preprocess_goal (cfg : auto_config) : tactic unit := do repeat (intro1 >> skip), tgt ← target >>= whnf_reducible, if (¬ (is_false tgt)) then if cfg.classical then (mk_mapp ``classical.by_contradiction [some tgt]) >>= apply >> intro1 >> skip else (mk_mapp ``decidable.by_contradiction [some tgt, none] >>= apply >> intro1 >> skip) <|> applyc ``by_contradiction_trick >> intro1 >> intro1 >> skip else skip /- Normalize hypotheses. Bring conjunctions to the outside (for splitting), bring universal quantifiers to the outside (for ematching). The classical normalizer eliminates a → b in favor of ¬ a ∨ b. For efficiency, we push negations inwards from the top down. (For example, consider simplifying ¬ ¬ (p ∨ q).) -/ section universe u variable {α : Type u} variables (p q : Prop) variable (s : α → Prop) local attribute [instance] classical.prop_decidable theorem not_not_eq : (¬ ¬ p) = p := propext not_not theorem not_and_eq : (¬ (p ∧ q)) = (¬ p ∨ ¬ q) := propext not_and_distrib theorem not_or_eq : (¬ (p ∨ q)) = (¬ p ∧ ¬ q) := propext not_or_distrib theorem not_forall_eq : (¬ ∀ x, s x) = (∃ x, ¬ s x) := propext not_forall theorem not_exists_eq : (¬ ∃ x, s x) = (∀ x, ¬ s x) := propext not_exists theorem not_implies_eq : (¬ (p → q)) = (p ∧ ¬ q) := propext not_imp theorem classical.implies_iff_not_or : (p → q) ↔ (¬ p ∨ q) := imp_iff_not_or end def common_normalize_lemma_names : list name := [``bex_def, ``forall_and_distrib, ``exists_imp_distrib] def classical_normalize_lemma_names : list name := common_normalize_lemma_names ++ [``classical.implies_iff_not_or] -- optionally returns an equivalent expression and proof of equivalence private meta def transform_negation_step (cfg : auto_config) (e : expr) : tactic (option (expr × expr)) := do e ← whnf_reducible e, match e with | `(¬ %%ne) := (do ne ← whnf_reducible ne, match ne with | `(¬ %%a) := do pr ← mk_app ``not_not_eq [a], return (some (a, pr)) | `(%%a ∧ %%b) := do pr ← mk_app ``not_and_eq [a, b], return (some (`(¬ %%a ∨ ¬ %%b), pr)) | `(%%a ∨ %%b) := do pr ← mk_app ``not_or_eq [a, b], return (some (`(¬ %%a ∧ ¬ %%b), pr)) | `(Exists %%p) := do pr ← mk_app ``not_exists_eq [p], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) | (pi n bi d p) := if ¬ cfg.classical then return none else if p.has_var then do pr ← mk_app ``not_forall_eq [lam n bi d (expr.abstract_local p n)], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) else do pr ← mk_app ``not_implies_eq [d, p], `(%%_ = %%e') ← infer_type pr, return (some (e', pr)) | _ := return none end) | _ := return none end -- given an expr 'e', returns a new expression and a proof of equality private meta def transform_negation (cfg : auto_config) : expr → tactic (option (expr × expr)) := λ e, do opr ← transform_negation_step cfg e, match opr with | (some (e', pr)) := do opr' ← transform_negation e', match opr' with | none := return (some (e', pr)) | (some (e'', pr')) := do pr'' ← mk_eq_trans pr pr', return (some (e'', pr'')) end | none := return none end meta def normalize_negations (cfg : auto_config) (h : expr) : tactic unit := do t ← infer_type h, (_, e, pr) ← simplify_top_down () (λ _, λ e, do oepr ← transform_negation cfg e, match oepr with | (some (e', pr)) := return ((), e', pr) | none := do pr ← mk_eq_refl e, return ((), e, pr) end) t, replace_hyp h e pr, skip meta def normalize_hyp (cfg : auto_config) (simps : simp_lemmas) (h : expr) : tactic unit := (do h ← simp_hyp simps [] h, try (normalize_negations cfg h)) <|> try (normalize_negations cfg h) meta def normalize_hyps (cfg : auto_config) : tactic unit := do simps ← if cfg.classical then add_simps simp_lemmas.mk classical_normalize_lemma_names else add_simps simp_lemmas.mk common_normalize_lemma_names, local_context >>= monad.mapm' (normalize_hyp cfg simps) /- Eliminate existential quantifiers. -/ -- eliminate an existential quantifier if there is one meta def eelim : tactic unit := do ctx ← local_context, first $ ctx.map $ λ h, do t ← infer_type h >>= whnf_reducible, guard (is_app_of t ``Exists), tgt ← target, to_expr ``(@exists.elim _ _ %%tgt %%h) >>= apply, intros, clear h -- eliminate all existential quantifiers, fails if there aren't any meta def eelims : tactic unit := eelim >> repeat eelim /- Substitute if there is a hypothesis x = t or t = x. -/ -- carries out a subst if there is one, fails otherwise meta def do_subst : tactic unit := do ctx ← local_context, first $ ctx.map $ λ h, do t ← infer_type h >>= whnf_reducible, match t with | `(%%a = %%b) := subst h | _ := failed end meta def do_substs : tactic unit := do_subst >> repeat do_subst /- Split all conjunctions. -/ -- Assumes pr is a proof of t. Adds the consequences of t to the context -- and returns tt if anything nontrivial has been added. meta def add_conjuncts : expr → expr → tactic bool := λ pr t, let assert_consequences := λ e t, mcond (add_conjuncts e t) skip (assertv_fresh t e >> skip) in do t' ← whnf_reducible t, match t' with | `(%%a ∧ %%b) := do e₁ ← mk_app ``and.left [pr], assert_consequences e₁ a, e₂ ← mk_app ``and.right [pr], assert_consequences e₂ b, return tt | `(true) := do return tt | _ := return ff end -- return tt if any progress is made meta def split_hyp (h : expr) : tactic bool := do t ← infer_type h, mcond (add_conjuncts h t) (clear h >> return tt) (return ff) -- return tt if any progress is made meta def split_hyps_aux : list expr → tactic bool | [] := return ff | (h :: hs) := do b₁ ← split_hyp h, b₂ ← split_hyps_aux hs, return (b₁ || b₂) -- fail if no progress is made meta def split_hyps : tactic unit := local_context >>= split_hyps_aux >>= guardb /- Eagerly apply all the preprocessing rules. -/ meta def preprocess_hyps (cfg : auto_config) : tactic unit := do repeat (intro1 >> skip), preprocess_goal cfg, normalize_hyps cfg, repeat (do_substs <|> split_hyps <|> eelim /-<|> self_simplify_hyps-/) /- The terminal tactic, used to try to finish off goals: - Call the contradiction tactic. - Open an SMT state, and use ematching and congruence closure, with all the universal statements in the context. TODO(Jeremy): allow users to specify attribute for ematching lemmas? -/ meta def mk_hinst_lemmas : list expr → smt_tactic hinst_lemmas | [] := -- return hinst_lemmas.mk do get_hinst_lemmas_for_attr `ematch | (h :: hs) := do his ← mk_hinst_lemmas hs, t ← infer_type h, match t with | (pi _ _ _ _) := do t' ← infer_type t, if t' = `(Prop) then (do new_lemma ← hinst_lemma.mk h, return (hinst_lemmas.add his new_lemma)) <|> return his else return his | _ := return his end meta def done (cfg : auto_config := {}) : tactic unit := do when_tracing `auto.done (trace "entering done" >> trace_state), contradiction <|> (solve1 $ (do revert_all, using_smt (do smt_tactic.intros, ctx ← local_context, hs ← mk_hinst_lemmas ctx, smt_tactic.repeat_at_most cfg.max_ematch_rounds (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close)))) /- Tactics that perform case splits. -/ inductive case_option | force -- fail unless all goals are solved | at_most_one -- leave at most one goal | accept -- leave as many goals as necessary private meta def case_cont (s : case_option) (cont : case_option → tactic unit) : tactic unit := do match s with | case_option.force := cont case_option.force >> cont case_option.force | case_option.at_most_one := -- if the first one succeeds, commit to it, and try the second (mcond (cont case_option.force >> return tt) (cont case_option.at_most_one) skip) <|> -- otherwise, try the second (swap >> cont case_option.force >> cont case_option.at_most_one) | case_option.accept := focus [cont case_option.accept, cont case_option.accept] end -- three possible outcomes: -- finds something to case, the continuations succeed ==> returns tt -- finds something to case, the continutations fail ==> fails -- doesn't find anything to case ==> returns ff meta def case_hyp (h : expr) (s : case_option) (cont : case_option → tactic unit) : tactic bool := do t ← infer_type h, match t with | `(%%a ∨ %%b) := cases h >> case_cont s cont >> return tt | _ := return ff end meta def case_some_hyp_aux (s : case_option) (cont : case_option → tactic unit) : list expr → tactic bool | [] := return ff | (h::hs) := mcond (case_hyp h s cont) (return tt) (case_some_hyp_aux hs) meta def case_some_hyp (s : case_option) (cont : case_option → tactic unit) : tactic bool := local_context >>= case_some_hyp_aux s cont /- The main tactics. -/ meta def safe_core (s : simp_lemmas × list name) (cfg : auto_config) : case_option → tactic unit := λ co, focus1 $ do when_tracing `auto.finish (trace "entering safe_core" >> trace_state), if cfg.use_simp then do when_tracing `auto.finish (trace "simplifying hypotheses"), simp_all s.1 s.2 { fail_if_unchanged := ff }, when_tracing `auto.finish (trace "result:" >> trace_state) else skip, tactic.done <|> do when_tracing `auto.finish (trace "preprocessing hypotheses"), preprocess_hyps cfg, when_tracing `auto.finish (trace "result:" >> trace_state), done cfg <|> (mcond (case_some_hyp co safe_core) skip (match co with | case_option.force := done cfg | case_option.at_most_one := try (done cfg) | case_option.accept := try (done cfg) end)) meta def clarify (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.at_most_one meta def safe (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.accept meta def finish (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.force meta def iclarify (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := clarify s {cfg with classical := false} meta def isafe (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := safe s {cfg with classical := false} meta def ifinish (s : simp_lemmas × list name) (cfg : auto_config := {}) : tactic unit := finish s {cfg with classical := false} end auto /- interactive versions -/ open auto namespace tactic namespace interactive open lean lean.parser interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def clarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.clarify s cfg meta def safe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.safe s cfg meta def finish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.finish s cfg meta def iclarify (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.iclarify s cfg meta def isafe (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.isafe s cfg meta def ifinish (hs : parse simp_arg_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set ff [] hs, auto.ifinish s cfg end interactive end tactic
de88a1a4372dde72ad29a2822ebbc91213811e76
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/eliminatorImplicitTargets.lean
83548111f87d3a521a862da020dd1b2859c485be
[ "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
494
lean
inductive Equality {α : Type u} : α → α → Type u | refl {a : α} : Equality a a open Equality @[eliminator] def ind {α : Type u} (motive : ∀ (a b : α) (p : Equality a b), Sort v) {a : α} (πrefl : motive a a refl) {b : α} (p : Equality a b) : motive a b p := @Equality.casesOn α a (λ b p => motive a a refl → motive a b p) b p (λ (ε : motive a a refl) => ε) πrefl def symm {α : Type u} {a b : α} (p : Equality a b) : Equality b a := by { induction p; apply refl }
e06095d6d05e78bd509b275509b5e414b326d2a4
c777c32c8e484e195053731103c5e52af26a25d1
/src/category_theory/abelian/injective.lean
bf89fc5c7b7ca7ca941902ff093d051649a7a61c
[ "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
1,503
lean
/- Copyright (c) 2022 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import category_theory.abelian.exact import category_theory.preadditive.injective import category_theory.preadditive.yoneda.limits import category_theory.preadditive.yoneda.injective /-! # Injective objects in abelian categories * Objects in an abelian categories are injective if and only if the preadditive Yoneda functor on them preserves finite colimits. -/ noncomputable theory open category_theory open category_theory.limits open category_theory.injective open opposite universes v u namespace category_theory variables {C : Type u} [category.{v} C] [abelian C] /-- The preadditive Yoneda functor on `J` preserves colimits if `J` is injective. -/ def preserves_finite_colimits_preadditive_yoneda_obj_of_injective (J : C) [hP : injective J] : preserves_finite_colimits (preadditive_yoneda_obj J) := begin letI := (injective_iff_preserves_epimorphisms_preadditive_yoneda_obj' J).mp hP, apply functor.preserves_finite_colimits_of_preserves_epis_and_kernels, end /-- An object is injective if its preadditive Yoneda functor preserves finite colimits. -/ lemma injective_of_preserves_finite_colimits_preadditive_yoneda_obj (J : C) [hP : preserves_finite_colimits (preadditive_yoneda_obj J)] : injective J := begin rw injective_iff_preserves_epimorphisms_preadditive_yoneda_obj', apply_instance end end category_theory
96fc0cadc11fdd8ff58b37c45bc18635f3f3b1cd
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Elab/Tactic/Conv.lean
637998311ecf7588121b0e94d7dadf68734149e2
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
378
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Conv.Basic import Lean.Elab.Tactic.Conv.Congr import Lean.Elab.Tactic.Conv.Rewrite import Lean.Elab.Tactic.Conv.Change import Lean.Elab.Tactic.Conv.Simp import Lean.Elab.Tactic.Conv.Pattern
26109c0588cd69ecdd289b7ec96c5d7eab47b1a8
91b8df3b248df89472cc0b753fbe2bac750aefea
/experiments/lean/src/ddl/host/formation.lean
5e669dbacc528bef3e369545818c05becc1c9936
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yeslogic/fathom
eabe5c4112d3b4d5ec9096a57bb502254ddbdf15
3960a9466150d392c2cb103c5cb5fcffa0200814
refs/heads/main
1,685,349,769,736
1,675,998,621,000
1,675,998,621,000
28,993,871
214
11
Apache-2.0
1,694,044,276,000
1,420,764,938,000
Rust
UTF-8
Lean
false
false
1,303
lean
import ddl.host.typing namespace ddl.host open ddl open ddl.host namespace type variables {ℓ : Type} [decidable_eq ℓ] inductive struct : type ℓ → Prop | nil {} : struct struct_nil | cons {l t₁ t₂} : struct (struct_cons l t₁ t₂) inductive union : type ℓ → Prop | nil {} : union union_nil | cons {l t₁ t₂} : union (union_cons l t₁ t₂) inductive well_formed : type ℓ → Prop | bool {} : well_formed bool | nat {} : well_formed nat | union_nil {} : well_formed union_nil | union_cons {l t₁ t₂} : well_formed t₁ → well_formed t₂ → union t₂ → well_formed (union_cons l t₁ t₂) | struct_nil {} : well_formed struct_nil | struct_cons {l t₁ t₂} : well_formed t₁ → well_formed t₂ → struct t₂ → well_formed (struct_cons l t₁ t₂) | array {t} : well_formed t → well_formed (array t) lemma well_formed_lookup : Π {l : ℓ} {tr tf : type ℓ}, well_formed tr → lookup l tr = some tf → well_formed tf := begin admit end end type end ddl.host
5e4a139690248d306354f635553c2ac3360e57e8
618003631150032a5676f229d13a079ac875ff77
/src/tactic/omega/nat/main.lean
06d462e48775e6430d3575d982f69e41f6e9b574
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,998
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Main procedure for linear natural number arithmetic. -/ import tactic.omega.prove_unsats import tactic.omega.nat.dnf import tactic.omega.nat.neg_elim import tactic.omega.nat.sub_elim open tactic namespace omega namespace nat open_locale omega.nat run_cmd mk_simp_attr `sugar_nat attribute [sugar_nat] ne not_le not_lt nat.lt_iff_add_one_le nat.succ_eq_add_one or_false false_or and_true true_and ge gt mul_add add_mul mul_comm one_mul mul_one classical.imp_iff_not_or classical.iff_iff_not_or_and_or_not meta def desugar := `[try {simp only with sugar_nat at *}] lemma univ_close_of_unsat_neg_elim_not (m) (p : preform) : (neg_elim (¬* p)).unsat → univ_close p (λ _, 0) m := begin intro h1, apply univ_close_of_valid, apply valid_of_unsat_not, intro h2, apply h1, apply preform.sat_of_implies_of_sat implies_neg_elim h2, end /-- Return expr of proof that argument is free of subtractions -/ meta def preterm.prove_sub_free : preterm → tactic expr | (& m) := return `(trivial) | (m ** n) := return `(trivial) | (t +* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (_ -* _) := failed /-- Return expr of proof that argument is free of negations -/ meta def prove_neg_free : preform → tactic expr | (t =* s) := return `(trivial) | (t ≤* s) := return `(trivial) | (p ∨* q) := do x ← prove_neg_free p, y ← prove_neg_free q, return `(@and.intro (preform.neg_free %%`(p)) (preform.neg_free %%`(q)) %%x %%y) | (p ∧* q) := do x ← prove_neg_free p, y ← prove_neg_free q, return `(@and.intro (preform.neg_free %%`(p)) (preform.neg_free %%`(q)) %%x %%y) | _ := failed /-- Return expr of proof that argument is free of subtractions -/ meta def prove_sub_free : preform → tactic expr | (t =* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (t ≤* s) := do x ← preterm.prove_sub_free t, y ← preterm.prove_sub_free s, return `(@and.intro (preterm.sub_free %%`(t)) (preterm.sub_free %%`(s)) %%x %%y) | (¬*p) := prove_sub_free p | (p ∨* q) := do x ← prove_sub_free p, y ← prove_sub_free q, return `(@and.intro (preform.sub_free %%`(p)) (preform.sub_free %%`(q)) %%x %%y) | (p ∧* q) := do x ← prove_sub_free p, y ← prove_sub_free q, return `(@and.intro (preform.sub_free %%`(p)) (preform.sub_free %%`(q)) %%x %%y) /-- Given a p : preform, return the expr of a term t : p.unsat, where p is subtraction- and negation-free. -/ meta def prove_unsat_sub_free (p : preform) : tactic expr := do x ← prove_neg_free p, y ← prove_sub_free p, z ← prove_unsats (dnf p), return `(unsat_of_unsat_dnf %%`(p) %%x %%y %%z) /-- Given a p : preform, return the expr of a term t : p.unsat, where p is negation-free. -/ meta def prove_unsat_neg_free : preform → tactic expr | p := match p.sub_terms with | none := prove_unsat_sub_free p | (some (t,s)) := do x ← prove_unsat_neg_free (sub_elim t s p), return `(unsat_of_unsat_sub_elim %%`(t) %%`(s) %%`(p) %%x) end /-- Given a (m : nat) and (p : preform), return the expr of (t : univ_close m p). -/ meta def prove_univ_close (m : nat) (p : preform) : tactic expr := do x ← prove_unsat_neg_free (neg_elim (¬*p)), to_expr ``(univ_close_of_unsat_neg_elim_not %%`(m) %%`(p) %%x) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprterm : expr → tactic exprterm | `(%%x * %%y) := do m ← eval_expr' nat y, return (exprterm.exp m x) | `(%%t1x + %%t2x) := do t1 ← to_exprterm t1x, t2 ← to_exprterm t2x, return (exprterm.add t1 t2) | `(%%t1x - %%t2x) := do t1 ← to_exprterm t1x, t2 ← to_exprterm t2x, return (exprterm.sub t1 t2) | x := ( do m ← eval_expr' nat x, return (exprterm.cst m) ) <|> ( return $ exprterm.exp 1 x ) /-- Reification to imtermediate shadow syntax that retains exprs -/ meta def to_exprform : expr → tactic exprform | `(%%tx1 = %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.eq t1 t2) | `(%%tx1 ≤ %%tx2) := do t1 ← to_exprterm tx1, t2 ← to_exprterm tx2, return (exprform.le t1 t2) | `(¬ %%px) := do p ← to_exprform px, return (exprform.not p) | `(%%px ∨ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.or p q) | `(%%px ∧ %%qx) := do p ← to_exprform px, q ← to_exprform qx, return (exprform.and p q) | `(_ → %%px) := to_exprform px | x := trace "Cannot reify expr : " >> trace x >> failed /-- List of all unreified exprs -/ meta def exprterm.exprs : exprterm → list expr | (exprterm.cst _) := [] | (exprterm.exp _ x) := [x] | (exprterm.add t s) := list.union t.exprs s.exprs | (exprterm.sub t s) := list.union t.exprs s.exprs /-- List of all unreified exprs -/ meta def exprform.exprs : exprform → list expr | (exprform.eq t s) := list.union t.exprs s.exprs | (exprform.le t s) := list.union t.exprs s.exprs | (exprform.not p) := p.exprs | (exprform.or p q) := list.union p.exprs q.exprs | (exprform.and p q) := list.union p.exprs q.exprs /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprterm.to_preterm (xs : list expr) : exprterm → tactic preterm | (exprterm.cst k) := return & k | (exprterm.exp k x) := let m := xs.index_of x in if m < xs.length then return (k ** m) else failed | (exprterm.add xa xb) := do a ← xa.to_preterm, b ← xb.to_preterm, return (a +* b) | (exprterm.sub xa xb) := do a ← xa.to_preterm, b ← xb.to_preterm, return (a -* b) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms -/ meta def exprform.to_preform (xs : list expr) : exprform → tactic preform | (exprform.eq xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a =* b) | (exprform.le xa xb) := do a ← xa.to_preterm xs, b ← xb.to_preterm xs, return (a ≤* b) | (exprform.not xp) := do p ← xp.to_preform, return ¬* p | (exprform.or xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∨* q) | (exprform.and xp xq) := do p ← xp.to_preform, q ← xq.to_preform, return (p ∧* q) /-- Reification to an intermediate shadow syntax which eliminates exprs, but still includes non-canonical terms. -/ meta def to_preform (x : expr) : tactic (preform × nat) := do xf ← to_exprform x, let xs := xf.exprs, f ← xf.to_preform xs, return (f, xs.length) /-- Return expr of proof of current LNA goal -/ meta def prove : tactic expr := do (p,m) ← target >>= to_preform, trace_if_enabled `omega p, prove_univ_close m p /-- Succeed iff argument is expr of ℕ -/ meta def eq_nat (x : expr) : tactic unit := if x = `(nat) then skip else failed /-- Check whether argument is expr of a well-formed formula of LNA-/ meta def wff : expr → tactic unit | `(¬ %%px) := wff px | `(%%px ∨ %%qx) := wff px >> wff qx | `(%%px ∧ %%qx) := wff px >> wff qx | `(%%px ↔ %%qx) := wff px >> wff qx | `(%%(expr.pi _ _ px qx)) := monad.cond (if expr.has_var px then return tt else is_prop px) (wff px >> wff qx) (eq_nat px >> wff qx) | `(@has_lt.lt %%dx %%h _ _) := eq_nat dx | `(@has_le.le %%dx %%h _ _) := eq_nat dx | `(@eq %%dx _ _) := eq_nat dx | `(@ge %%dx %%h _ _) := eq_nat dx | `(@gt %%dx %%h _ _) := eq_nat dx | `(@ne %%dx _ _) := eq_nat dx | `(true) := skip | `(false) := skip | _ := failed /-- Succeed iff argument is expr of term whose type is wff -/ meta def wfx (x : expr) : tactic unit := infer_type x >>= wff /-- Intro all universal quantifiers over nat -/ meta def intro_nats_core : tactic unit := do x ← target, match x with | (expr.pi _ _ `(nat) _) := intro_fresh >> intro_nats_core | _ := skip end meta def intro_nats : tactic unit := do (expr.pi _ _ `(nat) _) ← target, intro_nats_core /-- If the goal has universal quantifiers over natural, introduce all of them. Otherwise, revert all hypotheses that are formulas of linear natural number arithmetic. -/ meta def preprocess : tactic unit := intro_nats <|> (revert_cond_all wfx >> desugar) end nat end omega open omega.nat /-- The core omega tactic for natural numbers. -/ meta def omega_nat (is_manual : bool) : tactic unit := desugar ; (if is_manual then skip else preprocess) ; prove >>= apply >> skip
f6b67b89d353ff152b623e2bf82c70554af5635a
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/problem_sheets/sheet1.lean
e2154fbd7855b8286fed0681aee23b14b1225a7d
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
3,048
lean
/- Math40001 : Introduction to university mathematics. Problem Sheet 1, October 2020. This is a Lean file. It can be read with the Lean theorem prover. You can work on this file online at the following URL: or you can install Lean and its maths library following the instructions at https://leanprover-community.github.io/get_started.html There are advantages to installing Lean on your own computer (for example it's faster), but it's more hassle than just using it online. In the below, delete "sorry" and replace it with some tactics which prove the result. -/ /- Question 1. Let P and Q be Propositions (that is, true/false statements). Prove that P ∨ Q → Q ∨ P. -/ lemma question_one (P Q : Prop) : P ∨ Q → Q ∨ P := begin sorry end /- For question 2, comment out one option (or just delete it) and prove the other one. -/ -- Part (a): is → symmetric? lemma question_2a_true : ∀ P Q : Prop, (P → Q) → (Q → P) := begin sorry end lemma question_2a_false : ¬ (∀ P Q : Prop, (P → Q) → (Q → P)) := begin sorry end -- Part (b) : is ↔ symmetric? lemma question_2b_true (P Q : Prop) : (P ↔ Q) → (Q ↔ P) := begin sorry end lemma question_2b_false : ¬ (∀ P Q : Prop, (P ↔ Q) → (Q ↔ P)) := begin sorry end /- Question 3. Say P, Q and R are propositions, and we know: 1) if Q is true then P is true 2) If Q is false then R is false. Can we deduce that R implies P? Comment out one option and prove the other. Hint: if you're stuck, "apply classical.by_contradiction" sometimes helps. classical.by_contradiction is the theorem that ¬ ¬ P → P. -/ lemma question_3_true (P Q R : Prop) (h1 : Q → P) (h2 : ¬ Q → ¬ R) : R → P := begin sorry end lemma question_3_false : ¬ (∀ P Q R : Prop, (Q → P) → (¬ Q → ¬ R) → R → P) := begin sorry end /- Question 4. Is it possible to find three true-false statements P , Q and R, such that (P ∨ Q ∨ R) ∧ (¬P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬R) is true? -/ lemma question_4_true : ∃ (P Q R : Prop), (P ∨ Q ∨ R) ∧ (¬P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬R) := begin sorry end lemma question_4_false : ∀ (P Q R : Prop), ¬ ((P ∨ Q ∨ R) ∧ (¬P ∨ Q ∨ R) ∧ (¬P ∨ ¬Q ∨ R) ∧ (¬P ∨ ¬Q ∨ ¬R)) := begin sorry end /- Question 5. Say that for every integer n we have a proposition P n. Say we know P n → P (n + 8) for all n, and P n → P (n -3) for all n. Prove that the P n are either all true, or all false. This question is harder than the others. -/ lemma question_5 (P : ℤ → Prop) (h8 : ∀ n, P n → P (n + 8)) (h3 : ∀ n, P n → P (n - 3)) : (∀ n, P n) ∨ (∀ n, ¬ (P n)) := begin sorry end /- The first four of these questions can be solved using only the following tactics: intro apply (or, better, refine) left, right, cases, split assumption (or, better, exact) have, simp, use, contradiction (or, better, false.elim) The fifth question is harder. -/
d3e01666fc0cb2c3f5eb7714192469b6dd7b6d7b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/natural_isomorphism.lean
2c2098d562bf9936f1a41a7b880921ffd5d65467
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
5,438
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor_category import category_theory.isomorphism open category_theory universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open nat_trans /-- The application of a natural isomorphism to an object. We put this definition in a different namespace, so that we can use α.app -/ @[simp, reducible] def iso.app {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {F G : C ⥤ D} (α : F ≅ G) (X : C) : F.obj X ≅ G.obj X := { hom := α.hom.app X, inv := α.inv.app X, hom_inv_id' := begin rw [← comp_app, iso.hom_inv_id], refl end, inv_hom_id' := begin rw [← comp_app, iso.inv_hom_id], refl end } namespace nat_iso open category_theory.category category_theory.functor variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒞 𝒟 @[simp] lemma trans_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : (α ≪≫ β).app X = α.app X ≪≫ β.app X := rfl lemma app_hom {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).hom = α.hom.app X := rfl lemma app_inv {F G : C ⥤ D} (α : F ≅ G) (X : C) : (α.app X).inv = α.inv.app X := rfl @[simp] lemma hom_inv_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 (F.obj X) := congr_fun (congr_arg app α.hom_inv_id) X @[simp] lemma inv_hom_id_app {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 (G.obj X) := congr_fun (congr_arg app α.inv_hom_id) X variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.hom.app X) := { inv := α.inv.app X, hom_inv_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso (α.inv.app X) := { inv := α.hom.app X, hom_inv_id' := begin rw [←comp_app, iso.inv_hom_id, ←id_app] end, inv_hom_id' := begin rw [←comp_app, iso.hom_inv_id, ←id_app] end } lemma hom_app_inv_app_id (α : F ≅ G) (X : C) : α.hom.app X ≫ α.inv.app X = 𝟙 _ := hom_inv_id_app _ _ lemma inv_app_hom_app_id (α : F ≅ G) (X : C) : α.inv.app X ≫ α.hom.app X = 𝟙 _ := inv_hom_id_app _ _ variables {X Y : C} lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : (α.inv.app X) ≫ (F.map f) ≫ (α.hom.app Y) = G.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : (α.hom.app X) ≫ (G.map f) ≫ (α.inv.app Y) = F.map f := begin erw [naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def is_iso_of_is_iso_app (α : F ⟶ G) [∀ X : C, is_iso (α.app X)] : is_iso α := { inv := { app := λ X, inv (α.app X), naturality' := λ X Y f, begin have h := congr_arg (λ f, inv (α.app X) ≫ (f ≫ inv (α.app Y))) (α.naturality f).symm, simp only [is_iso.inv_hom_id_assoc, is_iso.hom_inv_id, assoc, comp_id, cancel_mono] at h, exact h end } } instance is_iso_of_is_iso_app' (α : F ⟶ G) [H : ∀ X : C, is_iso (nat_trans.app α X)] : is_iso α := @nat_iso.is_iso_of_is_iso_app _ _ _ _ _ _ α H -- TODO can we make this an instance? def is_iso_app_of_is_iso (α : F ⟶ G) [is_iso α] (X) : is_iso (α.app X) := { inv := (inv α).app X, hom_inv_id' := congr_fun (congr_arg nat_trans.app (is_iso.hom_inv_id α)) X, inv_hom_id' := congr_fun (congr_arg nat_trans.app (is_iso.inv_hom_id α)) X } def of_components (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y).hom) = ((app X).hom) ≫ (G.map f)) : F ≅ G := as_iso { app := λ X, (app X).hom } @[simp] lemma of_components.app (app' : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app' naturality).app X = app' X := by tidy @[simp] lemma of_components.hom_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).hom.app X = (app X).hom := rfl @[simp] lemma of_components.inv_app (app : ∀ X : C, (F.obj X) ≅ (G.obj X)) (naturality) (X) : (of_components app naturality).inv.app X = (app X).inv := rfl include ℰ def hcomp {F G : C ⥤ D} {H I : D ⥤ E} (α : F ≅ G) (β : H ≅ I) : F ⋙ H ≅ G ⋙ I := begin refine ⟨α.hom ◫ β.hom, α.inv ◫ β.inv, _, _⟩, { ext, rw [←nat_trans.exchange], simp, refl }, ext, rw [←nat_trans.exchange], simp, refl end omit ℰ -- declare local notation for nat_iso.hcomp localized "infix ` ■ `:80 := category_theory.nat_iso.hcomp" in category end nat_iso namespace functor variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def ulift_down_up : ulift_down.{v₁} C ⋙ ulift_up C ≅ 𝟭 (ulift.{u₂} C) := { hom := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X }, inv := { app := λ X, @category_struct.id (ulift.{u₂} C) _ X } } def ulift_up_down : ulift_up.{v₁} C ⋙ ulift_down C ≅ 𝟭 C := { hom := { app := λ X, 𝟙 X }, inv := { app := λ X, 𝟙 X } } end functor end category_theory
d9ce57387b0e6dbabf13c2a038ed57c78fc81b21
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/discrete_valuation_ring/tfae.lean
bae86b2c29902dea1f2c1855efec835b9f0deef6
[ "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,403
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.ideal.cotangent import ring_theory.dedekind_domain.basic import ring_theory.valuation.valuation_ring import ring_theory.nakayama /-! # Equivalent conditions for DVR In `discrete_valuation_ring.tfae`, we show that the following are equivalent for a noetherian local domain `(R, m, k)`: - `R` is a discrete valuation ring - `R` is a valuation ring - `R` is a dedekind domain - `R` is integrally closed with a unique prime ideal - `m` is principal - `dimₖ m/m² = 1` - Every nonzero ideal is a power of `m`. -/ variables (R : Type*) [comm_ring R] (K : Type*) [field K] [algebra R K] [is_fraction_ring R K] open_locale discrete_valuation open local_ring open_locale big_operators lemma exists_maximal_ideal_pow_eq_of_principal [is_noetherian_ring R] [local_ring R] [is_domain R] (h : ¬ is_field R) (h' : (maximal_ideal R).is_principal) (I : ideal R) (hI : I ≠ ⊥) : ∃ n : ℕ, I = (maximal_ideal R) ^ n := begin classical, unfreezingI { obtain ⟨x, hx : _ = ideal.span _⟩ := h' }, by_cases hI' : I = ⊤, { use 0, rw [pow_zero, hI', ideal.one_eq_top] }, have H : ∀ r : R, ¬ (is_unit r) ↔ x ∣ r := λ r, (set_like.ext_iff.mp hx r).trans ideal.mem_span_singleton, have : x ≠ 0, { rintro rfl, apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, simp [hx] }, have hx' := discrete_valuation_ring.irreducible_of_span_eq_maximal_ideal x this hx, have H' : ∀ r : R, r ≠ 0 → r ∈ nonunits R → ∃ (n : ℕ), associated (x ^ n) r, { intros r hr₁ hr₂, obtain ⟨f, hf₁, rfl, hf₂⟩ := (wf_dvd_monoid.not_unit_iff_exists_factors_eq r hr₁).mp hr₂, have : ∀ b ∈ f, associated x b, { intros b hb, exact irreducible.associated_of_dvd hx' (hf₁ b hb) ((H b).mp (hf₁ b hb).1) }, clear hr₁ hr₂ hf₁, induction f using multiset.induction with fa fs fh, { exact (hf₂ rfl).elim }, rcases eq_or_ne fs ∅ with rfl|hf', { use 1, rw [pow_one, multiset.prod_cons, multiset.empty_eq_zero, multiset.prod_zero, mul_one], exact this _ (multiset.mem_cons_self _ _) }, { obtain ⟨n, hn⟩ := fh hf' (λ b hb, this _ (multiset.mem_cons_of_mem hb)), use n + 1, rw [pow_add, multiset.prod_cons, mul_comm, pow_one], exact associated.mul_mul (this _ (multiset.mem_cons_self _ _)) hn } }, have : ∃ n : ℕ, x ^ n ∈ I, { obtain ⟨r, hr₁, hr₂⟩ : ∃ r : R, r ∈ I ∧ r ≠ 0, { by_contra h, push_neg at h, apply hI, rw eq_bot_iff, exact h }, obtain ⟨n, u, rfl⟩ := H' r hr₂ (le_maximal_ideal hI' hr₁), use n, rwa [← I.unit_mul_mem_iff_mem u.is_unit, mul_comm] }, use nat.find this, apply le_antisymm, { change ∀ s ∈ I, s ∈ _, by_contra hI'', push_neg at hI'', obtain ⟨s, hs₁, hs₂⟩ := hI'', apply hs₂, by_cases hs₃ : s = 0, { rw hs₃, exact zero_mem _ }, obtain ⟨n, u, rfl⟩ := H' s hs₃ (le_maximal_ideal hI' hs₁), rw [mul_comm, ideal.unit_mul_mem_iff_mem _ u.is_unit] at ⊢ hs₁, apply ideal.pow_le_pow (nat.find_min' this hs₁), apply ideal.pow_mem_pow, exact (H _).mpr (dvd_refl _) }, { rw [hx, ideal.span_singleton_pow, ideal.span_le, set.singleton_subset_iff], exact nat.find_spec this } end lemma maximal_ideal_is_principal_of_is_dedekind_domain [local_ring R] [is_domain R] [is_dedekind_domain R] : (maximal_ideal R).is_principal := begin classical, by_cases ne_bot : maximal_ideal R = ⊥, { rw ne_bot, apply_instance }, obtain ⟨a, ha₁, ha₂⟩ : ∃ a ∈ maximal_ideal R, a ≠ (0 : R), { by_contra h', push_neg at h', apply ne_bot, rwa eq_bot_iff }, have hle : ideal.span {a} ≤ maximal_ideal R, { rwa [ideal.span_le, set.singleton_subset_iff] }, have : (ideal.span {a}).radical = maximal_ideal R, { rw ideal.radical_eq_Inf, apply le_antisymm, { exact Inf_le ⟨hle, infer_instance⟩ }, { refine le_Inf (λ I hI, (eq_maximal_ideal $ is_dedekind_domain.dimension_le_one _ (λ e, ha₂ _) hI.2).ge), rw [← ideal.span_singleton_eq_bot, eq_bot_iff, ← e], exact hI.1 } }, have : ∃ n, maximal_ideal R ^ n ≤ ideal.span {a}, { rw ← this, apply ideal.exists_radical_pow_le_of_fg, exact is_noetherian.noetherian _ }, cases hn : nat.find this, { have := nat.find_spec this, rw [hn, pow_zero, ideal.one_eq_top] at this, exact (ideal.is_maximal.ne_top infer_instance (eq_top_iff.mpr $ this.trans hle)).elim }, obtain ⟨b, hb₁, hb₂⟩ : ∃ b ∈ maximal_ideal R ^ n, ¬ b ∈ ideal.span {a}, { by_contra h', push_neg at h', rw nat.find_eq_iff at hn, exact hn.2 n n.lt_succ_self (λ x hx, not_not.mp (h' x hx)) }, have hb₃ : ∀ m ∈ maximal_ideal R, ∃ k : R, k * a = b * m, { intros m hm, rw ← ideal.mem_span_singleton', apply nat.find_spec this, rw [hn, pow_succ'], exact ideal.mul_mem_mul hb₁ hm }, have hb₄ : b ≠ 0, { rintro rfl, apply hb₂, exact zero_mem _ }, let K := fraction_ring R, let x : K := algebra_map R K b / algebra_map R K a, let M := submodule.map (algebra.of_id R K).to_linear_map (maximal_ideal R), have ha₃ : algebra_map R K a ≠ 0 := is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂, by_cases hx : ∀ y ∈ M, x * y ∈ M, { have := is_integral_of_smul_mem_submodule M _ _ x hx, { obtain ⟨y, e⟩ := is_integrally_closed.algebra_map_eq_of_integral this, refine (hb₂ (ideal.mem_span_singleton'.mpr ⟨y, _⟩)).elim, apply is_fraction_ring.injective R K, rw [map_mul, e, div_mul_cancel _ ha₃] }, { rw submodule.ne_bot_iff, refine ⟨_, ⟨a, ha₁, rfl⟩, _⟩, exact is_fraction_ring.to_map_eq_zero_iff.not.mpr ha₂ }, { apply submodule.fg.map, exact is_noetherian.noetherian _ } }, { have : (M.map (distrib_mul_action.to_linear_map R K x)).comap (algebra.of_id R K).to_linear_map = ⊤, { by_contra h, apply hx, rintros m' ⟨m, hm, (rfl : algebra_map R K m = m')⟩, obtain ⟨k, hk⟩ := hb₃ m hm, have hk' : x * algebra_map R K m = algebra_map R K k, { rw [← mul_div_right_comm, ← map_mul, ← hk, map_mul, mul_div_cancel _ ha₃] }, exact ⟨k, le_maximal_ideal h ⟨_, ⟨_, hm, rfl⟩, hk'⟩, hk'.symm⟩ }, obtain ⟨y, hy₁, hy₂⟩ : ∃ y ∈ maximal_ideal R, b * y = a, { rw [ideal.eq_top_iff_one, submodule.mem_comap] at this, obtain ⟨_, ⟨y, hy, rfl⟩, hy' : x * algebra_map R K y = algebra_map R K 1⟩ := this, rw [map_one, ← mul_div_right_comm, div_eq_one_iff_eq ha₃, ← map_mul] at hy', exact ⟨y, hy, is_fraction_ring.injective R K hy'⟩ }, refine ⟨⟨y, _⟩⟩, apply le_antisymm, { intros m hm, obtain ⟨k, hk⟩ := hb₃ m hm, rw [← hy₂, mul_comm, mul_assoc] at hk, rw [← mul_left_cancel₀ hb₄ hk, mul_comm], exact ideal.mem_span_singleton'.mpr ⟨_, rfl⟩ }, { rwa [submodule.span_le, set.singleton_subset_iff] } } end lemma discrete_valuation_ring.tfae [is_noetherian_ring R] [local_ring R] [is_domain R] (h : ¬ is_field R) : tfae [discrete_valuation_ring R, valuation_ring R, is_dedekind_domain R, is_integrally_closed R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ P.is_prime, (maximal_ideal R).is_principal, finite_dimensional.finrank (residue_field R) (cotangent_space R) = 1, ∀ I ≠ ⊥, ∃ n : ℕ, I = (maximal_ideal R) ^ n] := begin have ne_bot := ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, classical, rw finrank_eq_one_iff', tfae_have : 1 → 2, { introI _, apply_instance }, tfae_have : 2 → 1, { introI _, haveI := is_bezout.to_gcd_domain R, haveI : unique_factorization_monoid R := ufm_of_gcd_of_wf_dvd_monoid, apply discrete_valuation_ring.of_ufd_of_unique_irreducible, { obtain ⟨x, hx₁, hx₂⟩ := ring.exists_not_is_unit_of_not_is_field h, obtain ⟨p, hp₁, hp₂⟩ := wf_dvd_monoid.exists_irreducible_factor hx₂ hx₁, exact ⟨p, hp₁⟩ }, { exact valuation_ring.unique_irreducible } }, tfae_have : 1 → 4, { introI H, exact ⟨infer_instance, ((discrete_valuation_ring.iff_pid_with_one_nonzero_prime R).mp H).2⟩ }, tfae_have : 4 → 3, { rintros ⟨h₁, h₂⟩, exact ⟨infer_instance, λ I hI hI', unique_of_exists_unique h₂ ⟨ne_bot, infer_instance⟩ ⟨hI, hI'⟩ ▸ maximal_ideal.is_maximal R, h₁⟩ }, tfae_have : 3 → 5, { introI h, exact maximal_ideal_is_principal_of_is_dedekind_domain R }, tfae_have : 5 → 6, { rintro ⟨x, hx⟩, have : x ∈ maximal_ideal R := by { rw hx, exact submodule.subset_span (set.mem_singleton x) }, let x' : maximal_ideal R := ⟨x, this⟩, use submodule.quotient.mk x', split, { intro e, rw submodule.quotient.mk_eq_zero at e, apply ring.ne_bot_of_is_maximal_of_not_is_field (maximal_ideal.is_maximal R) h, apply submodule.eq_bot_of_le_smul_of_le_jacobson_bot (maximal_ideal R), { exact ⟨{x}, (finset.coe_singleton x).symm ▸ hx.symm⟩ }, { conv_lhs { rw hx }, rw submodule.mem_smul_top_iff at e, rwa [submodule.span_le, set.singleton_subset_iff] }, { rw local_ring.jacobson_eq_maximal_ideal (⊥ : ideal R) bot_ne_top, exact le_refl _ } }, { refine λ w, quotient.induction_on' w $ λ y, _, obtain ⟨y, hy⟩ := y, rw [hx, submodule.mem_span_singleton] at hy, obtain ⟨a, rfl⟩ := hy, exact ⟨ideal.quotient.mk _ a, rfl⟩ } }, tfae_have : 6 → 5, { rintro ⟨x, hx, hx'⟩, induction x using quotient.induction_on', use x, apply le_antisymm, swap, { rw [submodule.span_le, set.singleton_subset_iff], exact x.prop }, have h₁ : (ideal.span {x} : ideal R) ⊔ maximal_ideal R ≤ ideal.span {x} ⊔ (maximal_ideal R) • (maximal_ideal R), { refine sup_le le_sup_left _, rintros m hm, obtain ⟨c, hc⟩ := hx' (submodule.quotient.mk ⟨m, hm⟩), induction c using quotient.induction_on', rw ← sub_sub_cancel (c * x) m, apply sub_mem _ _, { apply_instance }, { refine ideal.mem_sup_left (ideal.mem_span_singleton'.mpr ⟨c, rfl⟩) }, { have := (submodule.quotient.eq _).mp hc, rw [submodule.mem_smul_top_iff] at this, exact ideal.mem_sup_right this } }, have h₂ : maximal_ideal R ≤ (⊥ : ideal R).jacobson, { rw local_ring.jacobson_eq_maximal_ideal, exacts [le_refl _, bot_ne_top] }, have := submodule.smul_sup_eq_smul_sup_of_le_smul_of_le_jacobson (is_noetherian.noetherian _) h₂ h₁, rw [submodule.bot_smul, sup_bot_eq] at this, rw [← sup_eq_left, eq_comm], exact le_sup_left.antisymm (h₁.trans $ le_of_eq this) }, tfae_have : 5 → 7, { exact exists_maximal_ideal_pow_eq_of_principal R h }, tfae_have : 7 → 2, { rw valuation_ring.iff_ideal_total, intro H, constructor, intros I J, by_cases hI : I = ⊥, { subst hI, left, exact bot_le }, by_cases hJ : J = ⊥, { subst hJ, right, exact bot_le }, obtain ⟨n, rfl⟩ := H I hI, obtain ⟨m, rfl⟩ := H J hJ, cases le_total m n with h' h', { left, exact ideal.pow_le_pow h' }, { right, exact ideal.pow_le_pow h' } }, tfae_finish, end
3d7fddf53f50d908adaf5ce8b1423dc27a6d045b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/server/init_exit_worker.lean
1032ffc90873156edaae71ea31b5d7fa37ec0c3c
[ "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
446
lean
import Lean.Data.Lsp open IO Lean Lsp def main : IO Unit := do Ipc.runWith (←IO.appPath) #["--worker"] do let hIn ← Ipc.stdin hIn.write (←FS.readBinFile "init_vscode_1_47_2.log") hIn.flush hIn.write (←FS.readBinFile "open_empty.log") hIn.flush let diags ← Ipc.collectDiagnostics 1 "file:///empty" 1 assert! diags.length >= 1 Ipc.writeNotification ⟨"exit", Json.null⟩ discard Ipc.waitForExit
4e18716c2d1b6783ded533f33f301e96a760df3b
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/tactic/alias.lean
c487c439f9e98e58e8332338ae47cc04ee5c7754
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
4,414
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro This file defines an alias command, which can be used to create copies of a theorem or definition with different names. Syntax: / -- doc string - / alias my_theorem ← alias1 alias2 ... This produces defs or theorems of the form: / -- doc string - / @[alias] theorem alias1 : <type of my_theorem> := my_theorem / -- doc string - / @[alias] theorem alias2 : <type of my_theorem> := my_theorem Iff alias syntax: alias A_iff_B ↔ B_of_A A_of_B alias A_iff_B ↔ .. This gets an existing biconditional theorem A_iff_B and produces the one-way implications B_of_A and A_of_B (with no change in implicit arguments). A blank _ can be used to avoid generating one direction. The .. notation attempts to generate the 'of'-names automatically when the input theorem has the form A_iff_B or A_iff_B_left etc. -/ import data.buffer.parser open lean.parser tactic interactive parser namespace tactic.alias @[user_attribute] meta def alias_attr : user_attribute := { name := `alias, descr := "This definition is an alias of another." } meta def alias_direct (d : declaration) (doc : string) (al : name) : tactic unit := do updateex_env $ λ env, env.add (match d.to_definition with | declaration.defn n ls t _ _ _ := declaration.defn al ls t (expr.const n (level.param <$> ls)) reducibility_hints.abbrev tt | declaration.thm n ls t _ := declaration.thm al ls t $ task.pure $ expr.const n (level.param <$> ls) | _ := undefined end), alias_attr.set al () tt, add_doc_string al doc meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → tactic expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := pure $ @expr.const tt iffmp [] a b (f 0) | _ f := fail "Target theorem must have the form `Π x y z, a ↔ b`" meta def alias_iff (d : declaration) (doc : string) (al : name) (iffmp : name) : tactic unit := (if al = `_ then skip else get_decl al >> skip) <|> do let ls := d.univ_params, let t := d.type, v ← mk_iff_mp_app iffmp t (λ_, expr.const d.to_name (level.param <$> ls)), t' ← infer_type v, updateex_env $ λ env, env.add (declaration.thm al ls t' $ task.pure v), alias_attr.set al () tt, add_doc_string al doc meta def make_left_right : name → tactic (name × name) | (name.mk_string s p) := do let buf : char_buffer := s.to_char_buffer, sum.inr parts ← pure $ run (sep_by1 (ch '_') (many_char (sat (≠ '_')))) s.to_char_buffer, (left, _::right) ← pure $ parts.span (≠ "iff"), let pfx (a b : string) := a.to_list.is_prefix_of b.to_list, (suffix', right') ← pure $ right.reverse.span (λ s, pfx "left" s ∨ pfx "right" s), let right := right'.reverse, let suffix := suffix'.reverse, pure (p <.> "_".intercalate (right ++ "of" :: left ++ suffix), p <.> "_".intercalate (left ++ "of" :: right ++ suffix)) | _ := failed @[user_command] meta def alias_cmd (meta_info : decl_meta_info) (_ : parse $ tk "alias") : lean.parser unit := do old ← ident, d ← (do old ← resolve_constant old, get_decl old) <|> fail ("declaration " ++ to_string old ++ " not found"), let doc := λ al : name, meta_info.doc_string.get_or_else $ "**Alias** of `" ++ to_string old ++ "`.", do { tk "←" <|> tk "<-", aliases ← many ident, ↑(aliases.mmap' $ λ al, alias_direct d (doc al) al) } <|> do { tk "↔" <|> tk "<->", (left, right) ← mcond ((tk "." *> tk "." >> pure tt) <|> pure ff) (make_left_right old <|> fail "invalid name for automatic name generation") (prod.mk <$> types.ident_ <*> types.ident_), alias_iff d (doc left) left `iff.mp, alias_iff d (doc right) right `iff.mpr } meta def get_lambda_body : expr → expr | (expr.lam _ _ _ b) := get_lambda_body b | a := a meta def get_alias_target (n : name) : tactic (option name) := do attr ← try_core (has_attribute `alias n), option.cases_on attr (pure none) $ λ_, do d ← get_decl n, let (head, args) := (get_lambda_body d.value).get_app_fn_args, let head := if head.is_constant_of `iff.mp ∨ head.is_constant_of `iff.mpr then expr.get_app_fn (head.ith_arg 2) else head, guardb $ head.is_constant, pure $ head.const_name end tactic.alias
37d2e7dc112fa68bfa902c8f99fb2d400685d8a6
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love09_hoare_logic_exercise_sheet.lean
19a5979845bf618e424a2a2457d00d1b38bf55bd
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,982
lean
import .love09_hoare_logic_demo /- # LoVe Exercise 9: Hoare Logic -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1: Program Verification The following WHILE program is intended to compute the Gaussian sum up to `n`, leaving the result in `r`. -/ def GAUSS : stmt := stmt.assign "r" (λs, 0) ;; stmt.while (λs, s "n" ≠ 0) (stmt.assign "r" (λs, s "r" + s "n") ;; stmt.assign "n" (λs, s "n" - 1)) /- The summation function: -/ def sum_upto : ℕ → ℕ | 0 := 0 | (n + 1) := n + 1 + sum_upto n /- 1.1. Prove the correctness of `GAUSS` using `vcg`. The main challenge is to figure out which invariant to use for the while loop. The invariant should capture both the work that has been done already (the intermediate result) and the work that remains to be done. -/ lemma GAUSS_correct (n₀ : ℕ) : {* λs, s "n" = n₀ *} GAUSS {* λs, s "r" = sum_upto n₀ *} := sorry /- 1.2. The following WHILE program is intended to compute the product of `n` and `m`, leaving the result in `r`. Prove its correctness using `vcg`. Hint: If a variable `x` does not change in a program, it might be useful to record this in the invariant, by adding a conjunct `s "x" = x₀`. -/ def MUL : stmt := stmt.assign "r" (λs, 0) ;; stmt.while (λs, s "n" ≠ 0) (stmt.assign "r" (λs, s "r" + s "m") ;; stmt.assign "n" (λs, s "n" - 1)) lemma MUL_correct (n₀ m₀ : ℕ) : {* λs, s "n" = n₀ ∧ s "m" = m₀ *} MUL {* λs, s "r" = n₀ * m₀ *} := sorry /- ## Question 2: Hoare Triples for Total Correctness -/ def total_hoare (P : state → Prop) (S : stmt) (Q : state → Prop) : Prop := ∀s, P s → ∃t, (S, s) ⟹ t ∧ Q t notation `[* ` P : 1 ` *] ` S : 1 ` [* ` Q : 1 ` *]` := total_hoare P S Q namespace total_hoare /- 2.1. Prove the consequence rule. -/ lemma consequence {P P' Q Q' : state → Prop} {S} (hS : [* P *] S [* Q *]) (hP : ∀s, P' s → P s) (hQ : ∀s, Q s → Q' s) : [* P' *] S [* Q' *] := sorry /- 2.2. Prove the rule for `skip`. -/ lemma skip_intro {P} : [* P *] stmt.skip [* P *] := sorry /- 2.3. Prove the rule for `assign`. -/ lemma assign_intro {P : state → Prop} {x} {a : state → ℕ} : [* λs, P (s{x ↦ a s}) *] stmt.assign x a [* P *] := sorry /- 2.4. Prove the rule for `seq`. -/ lemma seq_intro {P Q R S T} (hS : [* P *] S [* Q *]) (hT : [* Q *] T [* R *]) : [* P *] S ;; T [* R *] := sorry /- 2.5. Complete the proof of the rule for `ite`. Hint: This requires a case distinction on the truth value of `b s`. -/ lemma ite_intro {b P Q : state → Prop} {S T} (hS : [* λs, P s ∧ b s *] S [* Q *]) (hT : [* λs, P s ∧ ¬ b s *] T [* Q *]) : [* P *] stmt.ite b S T [* Q *] := sorry /- 2.6 (**optional**). Try to prove the rule for `while`. The rule is parameterized by a loop invariant `I` and by a variant `V` that decreases with each iteration of the loop body. Before we prove the desired lemma, we introduce an auxiliary lemma. Its proof requires well-founded induction. When using `while_var_intro_aux` as induction hypothesis we recommend to do it directly after proving that the argument is less than `v₀`: have ih : ∃u, (stmt.while b S, t) ⟹ u ∧ I u ∧ ¬ b u := have V t < v₀ := …, while_var_intro_aux (V t) …, Similarly to `ite`, the proof requires a case distinction on `b s ∨ ¬ b s`. -/ lemma while_var_intro_aux {b : state → Prop} (I : state → Prop) (V : state → ℕ) {S} (h_inv : ∀v₀, [* λs, I s ∧ b s ∧ V s = v₀ *] S [* λs, I s ∧ V s < v₀ *]) : ∀v₀ s, V s = v₀ → I s → ∃t, (stmt.while b S, s) ⟹ t ∧ I t ∧ ¬ b t | v₀ s V_eq hs := sorry lemma while_var_intro {b : state → Prop} (I : state → Prop) (V : state → ℕ) {S} (hinv : ∀v₀, [* λs, I s ∧ b s ∧ V s = v₀ *] S [* λs, I s ∧ V s < v₀ *]) : [* I *] stmt.while b S [* λs, I s ∧ ¬ b s *] := sorry end total_hoare end LoVe
2c52b94b7e0855f4e5597c66fef646e5bca7ee6d
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/order/basic.lean
c76161715b015f75a28923e23568c8f0d3d4c63b
[ "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
23,946
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import data.subtype import data.prod open function /-! # Basic definitions about `≤` and `<` ## Definitions ### Predicates on functions - `monotone f`: a function between two types equipped with `≤` is monotone if `a ≤ b` implies `f a ≤ f b`. - `strict_mono f` : a function between two types equipped with `<` is strictly monotone if `a < b` implies `f a < f b`. - `order_dual α` : a type tag reversing the meaning of all inequalities. ### Transfering orders - `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α` using a function `f : α → β`. - `partial_order.lift`, `linear_order.lift`: transfer a partial (resp., linear) order on `β` to a partial (resp., linear) order on `α` using an injective function `f`. ### Extra classes - `no_top_order`, `no_bot_order`: an order without a maximal/minimal element. - `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists `c`, `a<c<b`. ## Main theorems - `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone; - `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone. ## TODO - expand module docs - automatic construction of dual definitions / theorems ## See also - `algebra.order` for basic lemmas about orders, and projection notation for orders ## Tags preorder, order, partial order, linear order, monotone, strictly monotone -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} @[simp] lemma lt_self_iff_false [preorder α] (a : α) : a < a ↔ false := by simp [lt_irrefl a] theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin casesI A, casesI B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := preorder.ext H, casesI A, casesI B, injection this, congr' } theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by { haveI this := partial_order.ext H, casesI A, casesI B, injection this, congr' } /-- Given a relation `R` on `β` and a function `f : α → β`, the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique relation on `α` making `f` a `rel_embedding` (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n ihn, ihn.comp hf) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma monotone.reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } /-- If `f` is a monotone function from `ℕ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_nat {α} [preorder α] {f : ℕ → α} (hf : monotone f) (x x' : ℕ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact nat.le_of_lt_succ (hf.reflect_lt h2) } /-- If `f` is a monotone function from `ℤ` to a preorder such that `y` lies between `f x` and `f (x + 1)`, then `y` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_int {α} [preorder α] {f : ℤ → α} (hf : monotone f) (x x' : ℤ) {y : α} (h1 : f x < y) (h2 : y < f (x + 1)) : f x' ≠ y := by { rintro rfl, apply (hf.reflect_lt h1).not_le, exact int.le_of_lt_add_one (hf.reflect_lt h2) } end monotone /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id /-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies `f x < f y`. -/ def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f x < f y /-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies `f y < f x`. -/ def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ t) ⦃y⦄ (hy : y ∈ t), x < y → f y < f x /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [h : subsingleton α] : subsingleton (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl lemma dual_compares [has_lt α] {a b : α} {o : ordering} : @ordering.compares (order_dual α) _ o a b ↔ @ordering.compares α _ o b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, hbc.trans hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.partial_order α } instance : Π [inhabited α], inhabited (order_dual α) := id theorem preorder.dual_dual (α : Type*) [H : preorder α] : order_dual.preorder (order_dual α) = H := preorder.ext $ λ _ _, iff.rfl theorem partial_order.dual_dual (α : Type*) [H : partial_order α] : order_dual.partial_order (order_dual α) = H := partial_order.ext $ λ _ _, iff.rfl theorem linear_order.dual_dual (α : Type*) [H : linear_order α] : order_dual.linear_order (order_dual α) = H := linear_order.ext $ λ _ _, iff.rfl theorem cmp_le_flip {α} [has_le α] [@decidable_rel α (≤)] (x y : α) : @cmp_le (order_dual α) _ _ x y = cmp_le y x := rfl end order_dual namespace strict_mono_incr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_incr_on f s) : @strict_mono_incr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_incr_on f s) : @strict_mono_decr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ x ≤ y := ⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H hy hx h') h, λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H hx hy h')) (λ h', h' ▸ le_refl _)⟩ lemma lt_iff_lt (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ x < y := by simp only [H.le_iff_le, hx, hy, lt_iff_le_not_le] protected theorem compares (H : strict_mono_incr_on f s) (hx : x ∈ s) (hy : y ∈ s) : ∀ {o}, ordering.compares o (f x) (f y) ↔ ordering.compares o x y | ordering.lt := H.lt_iff_lt hx hy | ordering.eq := ⟨λ h, le_antisymm ((H.le_iff_le hx hy).1 h.le) ((H.le_iff_le hy hx).1 h.symm.le), congr_arg _⟩ | ordering.gt := H.lt_iff_lt hy hx end strict_mono_incr_on namespace strict_mono_decr_on section dual variables [preorder α] [preorder β] {f : α → β} {s : set α} protected lemma dual (H : strict_mono_decr_on f s) : @strict_mono_decr_on (order_dual α) (order_dual β) _ _ f s := λ x hx y hy, H hy hx protected lemma dual_right (H : strict_mono_decr_on f s) : @strict_mono_incr_on α (order_dual β) _ _ f s := H end dual variables [linear_order α] [preorder β] {f : α → β} {s : set α} {x y : α} lemma le_iff_le (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≤ f y ↔ y ≤ x := H.dual_right.le_iff_le hy hx lemma lt_iff_lt (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x < f y ↔ y < x := H.dual_right.lt_iff_lt hy hx protected theorem compares (H : strict_mono_decr_on f s) (hx : x ∈ s) (hy : y ∈ s) {o : ordering} : ordering.compares o (f x) (f y) ↔ ordering.compares o y x := order_dual.dual_compares.trans $ H.dual_right.compares hy hx end strict_mono_decr_on namespace strict_mono open ordering function protected lemma strict_mono_incr_on [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) (s : set α) : strict_mono_incr_on f s := λ x hx y hy hxy, hf hxy lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β} (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf) lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n)) protected lemma ite' [preorder α] [has_lt β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → f x < g y) : strict_mono (λ x, if p x then f x else g x) := begin intros x y h, by_cases hy : p y, { have hx : p x := hp h hy, simpa [hx, hy] using hf h }, { by_cases hx : p x, { simpa [hx, hy] using hfg hx hy h }, { simpa [hx, hy] using hg h} } end protected lemma ite [preorder α] [preorder β] {f g : α → β} (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, f x ≤ g x) : strict_mono (λ x, if p x then f x else g x) := hf.ite' hg hp $ λ x y hx hy h, (hf h).trans_le (hfg y) section variables [linear_order α] [preorder β] {f : α → β} lemma lt_iff_lt (H : strict_mono f) {a b} : f a < f b ↔ a < b := (H.strict_mono_incr_on set.univ).lt_iff_lt trivial trivial protected theorem compares (H : strict_mono f) {a b} {o} : compares o (f a) (f b) ↔ compares o a b := (H.strict_mono_incr_on set.univ).compares trivial trivial lemma injective (H : strict_mono f) : injective f := λ x y h, show compares eq x y, from H.compares.1 h lemma le_iff_le (H : strict_mono f) {a b} : f a ≤ f b ↔ a ≤ b := (H.strict_mono_incr_on set.univ).le_iff_le trivial trivial lemma top_preimage_top (H : strict_mono f) {a} (h_top : ∀ p, p ≤ f a) (x : α) : x ≤ a := H.le_iff_le.mp (h_top (f x)) lemma bot_preimage_bot (H : strict_mono f) {a} (h_bot : ∀ p, f a ≤ p) (x : α) : a ≤ x := H.le_iff_le.mp (h_bot (f x)) end protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f := by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact ih.trans (h _) } -- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation, -- then `strict_mono f` is vacuously true. lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f := λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl) end strict_mono section open function lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y k, contrapose k, rw [←ne.def, ne_iff_lt_or_gt] at k, cases k, { apply h _ _ k }, { rw eq_comm, apply h _ _ k } end lemma strict_mono_of_monotone_of_injective [partial_order α] [partial_order β] {f : α → β} (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, begin rw lt_iff_le_and_ne at ⊢ h, exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩ end lemma monotone.strict_mono_iff_injective [linear_order α] [partial_order β] {f : α → β} (h : monotone f) : strict_mono f ↔ injective f := ⟨λ h, h.injective, strict_mono_of_monotone_of_injective h⟩ lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f := λ a b, by simp [lt_iff_le_not_le, h] {contextual := tt} end /-! ### Order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } lemma pi.le_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x ≤ y ↔ ∀ i, x i ≤ y i := iff.rfl lemma pi.lt_def {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] {x y : Π i, α i} : x < y ↔ x ≤ y ∧ ∃ i, x i < y i := by simp [lt_iff_le_not_le, pi.le_def] {contextual := tt} lemma le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : x ≤ function.update y i a ↔ x i ≤ a ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, x j ≤ z) lemma update_le_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a : α i} : function.update x i a ≤ y ↔ a ≤ y i ∧ ∀ j ≠ i, x j ≤ y j := function.forall_update_iff _ (λ j z, z ≤ y j) lemma update_le_update_iff {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] [decidable_eq ι] {x y : Π i, α i} {i : ι} {a b : α i} : function.update x i a ≤ function.update y i b ↔ a ≤ b ∧ ∀ j ≠ i, x j ≤ y j := by simp [update_le_iff] {contextual := tt} instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) : @monotone (order_dual α) (order_dual γ) _ _ f := λ x y hxy, hf hxy theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) : @strict_mono (order_dual α) (order_dual β) _ _ f := λ x y hxy, hf hxy /-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/ def preorder.lift {α β} [preorder β] (f : α → β) : preorder α := { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } /-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective function `f : α → β`. -/ def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) : partial_order α := { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f } /-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective function `f : α → β`. -/ def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) : linear_order α := { le_total := λx y, le_total (f x) (f y), decidable_le := λ x y, (infer_instance : decidable (f x ≤ f y)), decidable_lt := λ x y, (infer_instance : decidable (f x < f y)), decidable_eq := λ x y, decidable_of_iff _ inj.eq_iff, .. partial_order.lift f inj } instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val @[simp] lemma subtype.mk_le_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) ≤ ⟨y, hy⟩ ↔ x ≤ y := iff.rfl @[simp] lemma subtype.mk_lt_mk {α} [preorder α] {p : α → Prop} {x y : α} {hx : p x} {hy : p y} : (⟨x, hx⟩ : subtype p) < ⟨y, hy⟩ ↔ x < y := iff.rfl @[simp, norm_cast] lemma subtype.coe_le_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) ≤ y ↔ x ≤ y := iff.rfl @[simp, norm_cast] lemma subtype.coe_lt_coe {α} [preorder α] {p : α → Prop} {x y : subtype p} : (x : α) < y ↔ x < y := iff.rfl instance subtype.partial_order {α} [partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective lemma subtype.mono_coe [preorder α] (t : set α) : monotone (coe : (subtype t) → α) := λ x y, id lemma subtype.strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) := λ x y, id instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /-! ### Additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) : nonempty {x // a < x} := nonempty_subtype.2 (no_top a) /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) : nonempty {x // x < a} := nonempty_subtype.2 (no_bot a) /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma exists_between [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@exists_between α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃<a₁, a₃ ≤ a₂) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := exists_between ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₃ ≤ a₂) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a₂ ≤ a) ∧ (∀a<a₂, a ≤ a₁)) := or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ variables {s : β → β → Prop} {t : γ → γ → Prop} /-- Type synonym to create an instance of `linear_order` from a `partial_order` and `[is_total α (≤)]` -/ def as_linear_order (α : Type u) := α instance {α} [inhabited α] : inhabited (as_linear_order α) := ⟨ (default α : α) ⟩ noncomputable instance as_linear_order.linear_order {α} [partial_order α] [is_total α (≤)] : linear_order (as_linear_order α) := { le_total := @total_of α (≤) _, decidable_le := classical.dec_rel _, .. (_ : partial_order α) }
929cc606269eecfaa8846b19ce63e08af2c085dc
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/finsupp.lean
3eddf5eb1660ac7d5cf4ed7f8892ef4940b51ced
[ "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,096
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 -/ import data.finsupp.basic import linear_algebra.basic /-! # Properties of the semimodule `α →₀ M` Given an `R`-semimodule `M`, the `R`-semimodule structure on `α →₀ M` is defined in `data.finsupp.basic`. In this file we define `finsupp.supported s` to be the set `{f : α →₀ M | f.support ⊆ s}` interpreted as a submodule of `α →₀ M`. We also define `linear_map` versions of various maps: * `finsupp.lsingle a : M →ₗ[R] ι →₀ M`: `finsupp.single a` as a linear map; * `finsupp.lapply a : (ι →₀ M) →ₗ[R] M`: the map `λ f, f a` as a linear map; * `finsupp.lsubtype_domain (s : set α) : (α →₀ M) →ₗ[R] (s →₀ M)`: restriction to a subtype as a linear map; * `finsupp.restrict_dom`: `finsupp.filter` as a linear map to `finsupp.supported s`; * `finsupp.lsum`: `finsupp.sum` or `finsupp.lift_add_hom` as a `linear_map`; * `finsupp.total α M R (v : ι → M)`: sends `l : ι → R` to the linear combination of `v i` with coefficients `l i`; * `finsupp.total_on`: a restricted version of `finsupp.total` with domain `finsupp.supported R R s` and codomain `submodule.span R (v '' s)`; * `finsupp.supported_equiv_finsupp`: a linear equivalence between the functions `α →₀ M` supported on `s` and the functions `s →₀ M`; * `finsupp.lmap_domain`: a linear map version of `finsupp.map_domain`; * `finsupp.dom_lcongr`: a `linear_equiv` version of `finsupp.dom_congr`; * `finsupp.congr`: if the sets `s` and `t` are equivalent, then `supported M R s` is equivalent to `supported M R t`; * `finsupp.lcongr`: a `linear_equiv`alence between `α →₀ M` and `β →₀ N` constructed using `e : α ≃ β` and `e' : M ≃ₗ[R] N`. ## Tags function with finite support, semimodule, linear algebra -/ noncomputable theory open set linear_map submodule open_locale classical big_operators namespace finsupp variables {α : Type*} {M : Type*} {N : Type*} {R : Type*} {S : Type*} variables [semiring R] [semiring S] [add_comm_monoid M] [semimodule R M] variables [add_comm_monoid N] [semimodule R N] /-- Interpret `finsupp.single a` as a linear map. -/ def lsingle (a : α) : M →ₗ[R] (α →₀ M) := { map_smul' := assume a b, (smul_single _ _ _).symm, ..finsupp.single_add_hom a } /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. -/ lemma lhom_ext ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a b, φ (single a b) = ψ (single a b)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `finsupp X M` which agree on each `single x y` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' ⦃φ ψ : (α →₀ M) →ₗ[R] N⦄ (h : ∀ a, φ.comp (lsingle a) = ψ.comp (lsingle a)) : φ = ψ := lhom_ext $ λ a, linear_map.congr_fun (h a) /-- Interpret `λ (f : α →₀ M), f a` as a linear map. -/ def lapply (a : α) : (α →₀ M) →ₗ[R] M := { map_smul' := assume a b, rfl, ..finsupp.apply_add_hom a } section lsubtype_domain variables (s : set α) /-- Interpret `finsupp.subtype_domain s` as a linear map. -/ def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot_of_injective (single_injective a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl_right) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) /-- `finsupp.supported M R s` is the `R`-submodule of all `p : α →₀ M` such that `p.support ⊆ s`. -/ def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) /-- Interpret `finsupp.filter s` as a linear map from `α →₀ M` to `supported M R s`. -/ def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), map_add' := λ l₁ l₂, filter_add, map_smul' := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l a, by_cases a ∈ s; simp [h], exact ((mem_supported' R l.1).1 l.2 a h).symm end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := submodule.ext $ λ x, by simp [mem_supported, subset_Inter_iff] theorem supported_inter (s t : set α) : supported M R (s ∩ t) = supported M R s ⊓ supported M R t := by rw [set.inter_eq_Inter, supported_Inter, infi_bool_eq]; refl theorem disjoint_supported_supported {s t : set α} (h : disjoint s t) : disjoint (supported M R s) (supported M R t) := disjoint_iff.2 $ by rw [← supported_inter, disjoint_iff_inter_eq_empty.1 h, supported_empty] theorem disjoint_supported_supported_iff [nontrivial M] {s t : set α} : disjoint (supported M R s) (supported M R t) ↔ disjoint s t := begin refine ⟨λ h x hx, _, disjoint_supported_supported⟩, rcases exists_ne (0 : M) with ⟨y, hy⟩, have := h ⟨single_mem_supported R y hx.1, single_mem_supported R y hx.2⟩, rw [mem_bot, single_eq_zero] at this, exact hy this end /-- Interpret `finsupp.restrict_support_equiv` as a linear equivalence between `supported M R s` and `s →₀ M`. -/ def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := begin let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M, refine F.to_linear_equiv _, have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))) := rfl, rw this, exact linear_map.is_linear _ end section lsum variables (S) [semimodule S N] [smul_comm_class R S N] /-- Lift a family of linear maps `M →ₗ[R] N` indexed by `x : α` to a linear map from `α →₀ M` to `N` using `finsupp.sum`. This is an upgraded version of `finsupp.lift_add_hom`. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ def lsum : (α → M →ₗ[R] N) ≃ₗ[S] ((α →₀ M) →ₗ[R] N) := { to_fun := λ F, { to_fun := λ d, d.sum (λ i, F i), map_add' := (lift_add_hom (λ x, (F x).to_add_monoid_hom)).map_add, map_smul' := λ c f, by simp [sum_smul_index', smul_sum] }, inv_fun := λ F x, F.comp (lsingle x), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp }, map_smul' := λ F G, by { ext x y, simp } } @[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum S f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) : finsupp.lsum S f l = l.sum (λ b, f b) := rfl theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) : finsupp.lsum S f (finsupp.single i m) = f i m := finsupp.sum_single_index (f i).map_zero theorem lsum_symm_apply (f : (α →₀ M) →ₗ[R] N) (x : α) : (lsum S).symm f x = f.comp (lsingle x) := rfl end lsum section variables (M) (R) (X : Type*) /-- A slight rearrangement from `lsum` gives us the bijection underlying the free-forgetful adjunction for R-modules. -/ noncomputable def lift : (X → M) ≃+ ((X →₀ R) →ₗ[R] M) := (add_equiv.arrow_congr (equiv.refl X) (ring_lmap_equiv_self R M ℕ).to_add_equiv.symm).trans (lsum _ : _ ≃ₗ[ℕ] _).to_add_equiv @[simp] lemma lift_symm_apply (f) (x) : ((lift M R X).symm f) x = f (single x 1) := rfl @[simp] lemma lift_apply (f) (g) : ((lift M R X) f) g = g.sum (λ x r, r • f x) := rfl end section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) /-- Interpret `finsupp.map_domain` as a linear map. -/ def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_monoid M'] [semimodule R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ[R] M := finsupp.lsum ℕ (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl theorem total_apply_of_mem_supported {l : α →₀ R} {s : finset α} (hs : l ∈ supported R R (↑s : set α)) : finsupp.total α M R v l = s.sum (λ i, l i • v i) := finset.sum_subset hs $ λ x _ hxg, show l x • v x = 0, by rw [not_mem_support_iff.1 hxg, zero_smul] @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_unique [unique α] (l : α →₀ R) (v) : finsupp.total α M R v l = l (default α) • v (default α) := by rw [← total_single, ← unique_single l] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) /-- `finsupp.total_on M v s` interprets `p : α →₀ R` as a linear combination of a subset of the vectors in `v`, mapping it to the span of those vectors. The subset is indicated by a set `s : set α` of indices. -/ protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl lemma total_on_finset {s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s): finsupp.total α M R g (finsupp.on_finset s f hf) = finset.sum s (λ (x : α), f x • g x) := begin simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset], rw finset.sum_filter_of_ne, intros x hx h, contrapose! h, simp [h], end end total /-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/ protected def dom_lcongr {α₁ α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e : (α₁ →₀ M) ≃+ (α₂ →₀ M)).to_linear_equiv (lmap_domain M R e).map_smul @[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) : (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m := by simp [finsupp.dom_lcongr, finsupp.dom_congr, map_domain_single] /-- An equivalence of sets induces a linear equivalence of `finsupp`s supported on those sets. -/ noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end /-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the corresponding finitely supported functions. -/ def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) := (finsupp.dom_lcongr e₁).trans { to_fun := map_range e₂ e₂.map_zero, inv_fun := map_range e₂.symm e₂.symm.map_zero, left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add, map_range_single, map_range_single, e₂.symm_apply_apply, ih], right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih, by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add, map_range_single, map_range_single, e₂.apply_symm_apply, ih], map_add' := map_range_add e₂.map_add, map_smul' := λ c f, finsupp.induction f (by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih, by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih, map_range_add e₂.map_add, smul_add, map_range_single, smul_single] } @[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) (i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) := by simp [lcongr] end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N] [semimodule R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe], apply N.sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end lemma mem_span_finset {s : finset M} {x : M} : x ∈ span R (↑s : set M) ↔ ∃ f : M → R, ∑ i in s, f i • i = x := ⟨λ hx, let ⟨v, hvs, hvx⟩ := (finsupp.mem_span_iff_total _).1 (show x ∈ span R (id '' (↑s : set M)), by rwa set.image_id) in ⟨v, hvx ▸ (finsupp.total_apply_of_mem_supported _ hvs).symm⟩, λ ⟨f, hf⟩, hf ▸ sum_mem _ (λ i hi, smul_mem _ _ $ subset_span hi)⟩ /-- An element `m ∈ M` is contained in the `R`-submodule spanned by a set `s ⊆ M`, if and only if `m` can be written as a finite `R`-linear combination of elements of `s`. The implementation uses `finsupp.sum`. -/ lemma mem_span_set {m : M} {s : set M} : m ∈ submodule.span R s ↔ ∃ c : M →₀ R, (c.support : set M) ⊆ s ∧ c.sum (λ mi r, r • mi) = m := begin conv_lhs { rw ←set.image_id s }, simp_rw ←exists_prop, exact finsupp.mem_span_iff_total R, end
3c1305199376fa19f75d0fa0141092639889340a
995658a556256a6694fe5c98b91f7f6f6c11bb77
/src/basic.lean
ab1608cef250b3fb1bd7cba2d51e0b2d452f07c5
[ "MIT" ]
permissive
bhgomes/lean-riemann-hypothesis
d803047f27ea21f03414bbfb59395608ed0bc05f
c36b744a2dc4a7a50c7de770096bd9a051f42ab9
refs/heads/master
1,678,533,614,591
1,614,755,910,000
1,614,755,910,000
275,204,877
16
3
null
null
null
null
UTF-8
Lean
false
false
37,083
lean
/- ------------------------------------------------------------------------- -| | @project: riemann_hypothesis | | @file: basic.lean | | @authors: Brandon H. Gomes, Alex Kontorovich | | @affil: Rutgers University | |- ------------------------------------------------------------------------- -/ /-! -/ namespace riemann_hypothesis --——————————————————————————————————————————————————————————-- variables {α : Type*} {β : Type*} /-- -/ def const (b : β) := λ _ : α, b notation `↓`:max b:max := const b section pointwise_classes --—————————————————————————————————————————————————————————————-- /-- -/ instance pointwise.has_le [has_le β] : has_le (α → β) := ⟨λ f g, Π x, f x ≤ g x⟩ /-- -/ instance pointwise.has_zero [has_zero β] : has_zero (α → β) := ⟨↓0⟩ end pointwise_classes --—————————————————————————————————————————————————————————————————-- namespace algebra --—————————————————————————————————————————————————————————————————————-- variables (α) (β) /-- -/ class has_left_add_distributivity [has_add α] [has_mul α] := (eq : Π x y z : α, x * (y + z) = x * y + x * z) /-- -/ class has_right_add_distributivity [has_add α] [has_mul α] := (eq : Π x y z : α, (y + z) * x = y * x + z * x) /-- -/ class has_left_sub_distributivity [has_sub α] [has_mul α] := (eq : Π x y z : α, x * (y - z) = x * y - x * z) /-- -/ class has_right_sub_distributivity [has_sub α] [has_mul α] := (eq : Π x y z : α, (y - z) * x = y * x - z * x) /-- -/ class has_lift_add_comm [has_lift_t α β] [has_add α] [has_add β] := (eq : Π x y : α, (↑(x + y) : β) = ↑x + ↑y) /-- -/ class has_lift_sub_comm [has_lift_t α β] [has_sub α] [has_sub β] := (eq : Π x y : α, (↑(x - y) : β) = ↑x - ↑y) /-- -/ class has_lift_mul_comm [has_lift_t α β] [has_mul α] [has_mul β] := (eq : Π x y : α, (↑(x * y) : β) = ↑x * ↑y) /-- -/ class has_lift_inv_comm [has_lift_t α β] [has_inv α] [has_inv β] := (eq : Π a : α, (↑(a⁻¹) : β) = (↑a)⁻¹) /-- -/ class has_right_unit [has_one α] [has_mul α] := (eq : Π a : α, a * 1 = a) /-- -/ class has_left_unit [has_one α] [has_mul α] := (eq : Π a : α, 1 * a = a) /-- -/ class has_add_le_add [has_le α] [has_add α] := (le : Π {a b c d : α}, a ≤ b → c ≤ d → a + c ≤ b + d) /-- -/ class has_add_lt_add [has_lt α] [has_add α] := (lt : Π {a b c d : α}, a < b → c < d → a + c < b + d) /-- -/ class has_le_add_of_nonneg_of_le [has_le α] [has_zero α] [has_add α] := (le : Π {a b c : α}, 0 ≤ a → b ≤ c → b ≤ a + c) /-- -/ class has_lt_add_of_le_of_pos [has_le α] [has_lt α] [has_zero α] [has_add α] := (lt : Π {a b c : α}, 0 < a → b ≤ c → b < a + c) /-- -/ class has_add_nonneg [has_le α] [has_zero α] [has_add α] := (le : Π {a b : α}, 0 ≤ a → 0 ≤ b → 0 ≤ a + b) /-- -/ class has_zero_mul_is_zero [has_zero α] [has_mul α] := (eq : Π a : α, 0 * a = 0) /-- -/ class has_mul_zero_is_zero [has_zero α] [has_mul α] := (eq : Π a : α, a * 0 = 0) /-- -/ class has_lift_zero_same [has_lift_t α β] [has_zero α] [has_zero β] := (eq : ↑(0 : α) = (0 : β)) /-- -/ class has_lift_one_same [has_lift_t α β] [has_one α] [has_one β] := (eq : ↑(1 : α) = (1 : β)) /-- -/ class has_zero_right_add_cancel [has_zero α] [has_add α] := (eq : Π a : α, a + 0 = a) /-- -/ class has_zero_left_add_cancel [has_zero α] [has_add α] := (eq : Π a : α, 0 + a = a) /-- -/ class has_sub_self_is_zero [has_zero α] [has_sub α] := (eq : Π a : α, a - a = 0) /-- -/ class has_mul_assoc [has_mul α] := (eq : Π a b c : α, (a * b) * c = a * (b * c)) /-- -/ class has_add_sub_assoc [has_add α] [has_sub α] := (eq : Π a b c : α, (a + b) - c = a + (b - c)) /-- -/ class has_le_sub_add_le [has_le α] [has_sub α] [has_add α] := (le : Π {a b c : α}, a ≤ c - b → a + b ≤ c) /-- -/ class has_le_pos_mul_preserves_right [has_lt α] [has_le α] [has_zero α] [has_mul α] := (le : Π {a b c : α}, 0 < c → a ≤ b → a * c ≤ b * c) /-- -/ class has_le_pos_mul_preserves_left [has_lt α] [has_le α] [has_zero α] [has_mul α] := (le : Π {a b c : α}, 0 < c → a ≤ b → c * a ≤ c * b) /-- -/ class has_lt_pos_mul_preserves_right [has_lt α] [has_zero α] [has_mul α] := (lt : Π {a b c : α}, 0 < c → a < b → a * c < b * c) /-- -/ class has_le_nonneg_mul_preserves_left [has_lt α] [has_le α] [has_zero α] [has_mul α] := (le : Π {a b c : α}, 0 ≤ c → a ≤ b → c * a ≤ c * b) /-- -/ class has_le_nonneg_mul_preserves_right [has_lt α] [has_le α] [has_zero α] [has_mul α] := (le : Π {a b c : α}, 0 ≤ c → a ≤ b → a * c ≤ b * c) /-- -/ class has_lift_le_comm [has_lift_t α β] [has_le α] [has_le β] := (le : Π {x y : α}, x ≤ y → ↑x ≤ (↑y : β)) /-- -/ class has_lift_lt_comm [has_lift_t α β] [has_lt α] [has_lt β] := (lt : Π {x y : α}, x < y → ↑x < (↑y : β)) /-- -/ class has_lift_ne_comm [has_lift_t α β] := (ne : Π {x y : α}, x ≠ y → ↑x ≠ (↑y : β)) /-- -/ class has_sub_add_sub_cancel [has_sub α] [has_add α] := (eq : Π a b c : α, a - b + (b - c) = a - c) /-- -/ class has_double_sub_cancel [has_sub α] := (eq : Π a b : α, a - (a - b) = b) /-- -/ class has_inv_mul_right_cancel_self [has_zero α] [has_one α] [has_inv α] [has_mul α] := (eq : Π a : α, a ≠ 0 → a * a⁻¹ = 1) /-- -/ class has_inv_mul_left_cancel_self [has_zero α] [has_one α] [has_inv α] [has_mul α] := (eq : Π a : α, a ≠ 0 → a⁻¹ * a = 1) /-- -/ class has_add_sub_exchange [has_add α] [has_sub α] := (eq : Π a b c d : α, (a - b) + (c - d) = (c - b) + (a - d)) /-- -/ class has_zero_sub_is_neg [has_zero α] [has_neg α] [has_sub α] := (eq : Π a : α, 0 - a = -a) /-- -/ class has_inv_right_mul_lt_pos [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, 0 < b → a < c * b → a * b⁻¹ < c) /-- -/ class has_right_mul_inv_lt_pos [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, 0 < b → c < b⁻¹ * a → b * c < a) /-- -/ class has_left_mul_inv_lt_pos [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, 0 < b → c < a * b⁻¹ → c * b < a) /-- -/ class has_left_mul_inv_lt_neg [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, b < 0 → a * b⁻¹ < c → b * c < a) /-- -/ class has_sub_ne_zero_of_ne [has_zero α] [has_sub α] := (ne : Π {a b : α}, a ≠ b → a - b ≠ 0) /-- -/ class has_lt_sub_neg [has_lt α] [has_zero α] [has_sub α] := (lt : Π {a b : α}, a < b → a - b < 0) /-- -/ class has_zero_lt_one [has_lt α] [has_zero α] [has_one α] := (lt : 0 < (1 : α)) /-- -/ class has_pos_mul_neg_is_neg [has_lt α] [has_zero α] [has_mul α] := (lt : Π {a b : α}, 0 < a → b < 0 → a * b < 0) /-- -/ class has_nonneg_mul_nonneg_is_nonneg [has_le α] [has_zero α] [has_mul α] := (le : Π {a b : α}, 0 ≤ a → 0 ≤ b → 0 ≤ a * b) /-- -/ class has_squared_le_monotonic [has_le α] [has_zero α] [has_mul α] := (le : Π {a b : α}, 0 ≤ a → a ≤ b → a * a ≤ b * b) /-- -/ class has_sub_pos [has_lt α] [has_zero α] [has_sub α] := (lt : Π {a b : α}, a < b → 0 < b - a) /-- -/ class has_sub_sub [has_add α] [has_sub α] := (eq : Π a b c : α, a - (b - c) = (a - b) + c) /-- -/ class has_add_left_lt [has_lt α] [has_add α] := (lt : Π a b c : α, a < b → c + a < c + b) /-- -/ class has_left_inv_pos_lt [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, 0 < c → a < b → c⁻¹ * a < c⁻¹ * b) /-- -/ class has_right_inv_pos_lt [has_lt α] [has_zero α] [has_mul α] [has_inv α] := (lt : Π {a b c : α}, 0 < c → a < b → a * c⁻¹ < b * c⁻¹) /-- -/ class has_mul_pos [has_lt α] [has_zero α] [has_mul α] := (lt : Π {a b : α}, 0 < a → 0 < b → 0 < a * b) /-- -/ class has_inv_pos [has_lt α] [has_zero α] [has_inv α] := (lt : Π {a : α}, 0 < a → 0 < a⁻¹) /-- -/ class has_inv_reverses_le [has_le α] [has_inv α] := (le : Π {a b : α}, a ≤ b → b⁻¹ ≤ a⁻¹) /-- -/ class has_inv_reverses_lt [has_lt α] [has_inv α] := (lt : Π {a b : α}, a < b → b⁻¹ < a⁻¹) /-- -/ class has_inv_mul_reverse [has_inv α] [has_mul α] := (eq : Π a b : α, (a * b)⁻¹ = b⁻¹ * a⁻¹) /-- -/ structure Half [has_lt α] [has_zero α] [has_add α] := (map : α → α) (preserve_pos : Π {x}, 0 < x → 0 < map x) (doubled_inv : Π (x), map x + map x = x) /-- -/ structure LiftCeil [has_lift_t nat α] [has_lt α] := (map : α → nat) (lift_lt : Π {a n}, map a < n → a < ↑n) section lemmas --————————————————————————————————————————————————————————————————————————-- variables {α β} /-- -/ def inv_sub_inv_lemma [has_zero α] [has_one α] [has_inv α] [has_mul α] [has_sub α] [has_right_unit α] [has_left_unit α] [has_inv_mul_right_cancel_self α] [has_mul_assoc α] [has_right_sub_distributivity α] {a b : α} (a_ne_0 : a ≠ 0) : a⁻¹ - b⁻¹ = (1 - b⁻¹ * a) * a⁻¹ := begin rw has_right_sub_distributivity.eq, rw has_mul_assoc.eq, rw has_inv_mul_right_cancel_self.eq _ a_ne_0, rw has_left_unit.eq, rw has_right_unit.eq, end /-- -/ def inv_sub_inv_lemma' [has_zero α] [has_one α] [has_inv α] [has_mul α] [has_sub α] [has_right_unit α] [has_left_unit α] [has_inv_mul_left_cancel_self α] [has_mul_assoc α] [has_left_sub_distributivity α] {a b : α} (a_ne_0 : a ≠ 0) : a⁻¹ - b⁻¹ = a⁻¹ * (1 - a * b⁻¹) := begin rw has_left_sub_distributivity.eq, rw ← has_mul_assoc.eq, rw has_inv_mul_left_cancel_self.eq _ a_ne_0, rw has_left_unit.eq, rw has_right_unit.eq, end /-- -/ def mul_inv_add_one_lemma [has_lift_t nat α] [has_zero α] [has_one α] [has_sub α] [has_mul α] [has_inv α] [has_left_unit α] [has_inv_mul_right_cancel_self α] [has_right_sub_distributivity α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_sub_comm nat α] [has_lift_ne_comm nat α] (n : nat) : (↑n : α) * (↑n.succ)⁻¹ = 1 - (↑n.succ)⁻¹ := begin rw ← has_left_unit.eq (↑n.succ : α)⁻¹, have succ_non_zero : ↑n.succ ≠ (0 : α), rw (_ : 0 = (↑0 : α)), refine has_lift_ne_comm.ne (nat.succ_ne_zero _), rw has_lift_zero_same.eq, rw ← has_inv_mul_right_cancel_self.eq _ succ_non_zero, rw ← has_right_sub_distributivity.eq, rw has_inv_mul_right_cancel_self.eq _ succ_non_zero, rw has_left_unit.eq, rw (_ : 1 = (↑1 : α)), rw ← has_lift_sub_comm.eq, rw nat.succ_sub_one, rw has_lift_one_same.eq, end /-- -/ def two_mul_lemma [has_one α] [has_add α] [has_mul α] [has_right_add_distributivity α] [has_left_unit α] (a : α) : 2 * a = a + a := begin refine (has_right_add_distributivity.eq _ _ _).trans _, rw has_left_unit.eq, end /-- -/ def two_mul_lemma' [has_one α] [has_add α] [has_mul α] [has_left_add_distributivity α] [has_right_unit α] (a : α) : a * 2 = a + a := begin refine (has_left_add_distributivity.eq _ _ _).trans _, rw has_right_unit.eq, end /-- -/ def two_squares_is_four_lemma [has_one α] [has_add α] [has_mul α] [has_left_unit α] [has_left_add_distributivity α] [has_right_add_distributivity α] [has_mul_assoc α] (a : α) : 4 * (a * a) = (a + a) * (a + a) := begin rw has_left_add_distributivity.eq, rw has_right_add_distributivity.eq, rw ← two_mul_lemma, rw ← two_mul_lemma, rw ← has_mul_assoc.eq, rw ← has_mul_assoc.eq, rw two_mul_lemma, rw has_mul_assoc.eq, refine rfl, end /-- -/ def two_squares_is_four_lemma' [has_one α] [has_add α] [has_mul α] [has_right_unit α] [has_left_add_distributivity α] [has_right_add_distributivity α] [has_mul_assoc α] (a : α) : (a * a) * 4 = (a + a) * (a + a) := begin rw has_right_add_distributivity.eq, rw has_left_add_distributivity.eq, rw ← two_mul_lemma', rw ← two_mul_lemma', rw has_mul_assoc.eq, rw has_mul_assoc.eq, rw two_mul_lemma', rw has_mul_assoc.eq, refine rfl, end /-- -/ def nat_mul_commute_lemma [has_zero α] [has_one α] [has_add α] [has_mul α] [has_zero_mul_is_zero α] [has_mul_zero_is_zero α] [has_right_unit α] [has_left_unit α] [has_left_add_distributivity α] [has_right_add_distributivity α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_add_comm nat α] (a : α) (n : nat) : a * ↑n = ↑n * a := begin induction n with n hn, rw has_lift_zero_same.eq, rw has_zero_mul_is_zero.eq, rw has_mul_zero_is_zero.eq, rw nat.succ_eq_add_one, rw has_lift_add_comm.eq, rw has_left_add_distributivity.eq, rw has_right_add_distributivity.eq, rw hn, rw has_lift_one_same.eq, rw has_left_unit.eq, rw has_right_unit.eq, end section lifted_lemmas --—————————————————————————————————————————————————————————————————-- variables (α β) /-- -/ def zero_is_lifted_zero_lemma [has_zero α] [has_zero β] [has_lift_t α β] [has_lift_zero_same α β] : (0 : β) = ↑(0 : α) := by rw has_lift_zero_same.eq --———————————————————————————————————————————————————————————————————————————————————————-- variables [has_one α] [has_one β] [has_lift_t α β] [has_lift_one_same α β] /-- -/ def one_is_lifted_one_lemma : (1 : β) = ↑(1 : α) := by rw has_lift_one_same.eq --———————————————————————————————————————————————————————————————————————————————————————-- variables [has_add α] [has_add β] [has_lift_add_comm α β] /-- -/ def two_is_lifted_two_lemma : (2 : β) = ↑(2 : α) := begin rw (_ : (2 : β) = ↑(1 : α) + ↑(1 : α)), rw ← has_lift_add_comm.eq, refine rfl, rw has_lift_one_same.eq, refine rfl, end /-- -/ def three_is_lifted_three_lemma : (3 : β) = ↑(3 : α) := begin rw (_ : (3 : β) = ↑(1 : α) + ↑(1 : α) + ↑(1 : α)), rw [← has_lift_add_comm.eq, ← has_lift_add_comm.eq], refine rfl, rw has_lift_one_same.eq, refine rfl, end /-- -/ def four_is_lifted_four_lemma : (4 : β) = ↑(4 : α) := begin rw (_ : (4 : β) = ↑(1 : α) + ↑(1 : α) + (↑(1 : α) + ↑(1 : α))), rw [← has_lift_add_comm.eq, ← has_lift_add_comm.eq], refine rfl, rw has_lift_one_same.eq, refine rfl, end end lifted_lemmas --—————————————————————————————————————————————————————————————————————-- end lemmas --————————————————————————————————————————————————————————————————————————————-- end algebra --———————————————————————————————————————————————————————————————————————————-- open algebra namespace nat --—————————————————————————————————————————————————————————————————————————-- /-- -/ def of_le_succ {n m : nat} (n_le_m_succ : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le n_le_m_succ).imp nat.le_of_lt_succ id /-- -/ def sub_sub_sub_cancel_right {a b c} (c_le_b : c ≤ b) : a - c - (b - c) = a - b := by rw [nat.sub_sub, ← nat.add_sub_assoc c_le_b, nat.add_sub_cancel_left] /-- -/ def le_sub_right_of_add_le {m n k} : m + k ≤ n → m ≤ n - k := begin intros h, rw ← nat.add_sub_cancel m k, refine nat.sub_le_sub_right h _, end /-- -/ def le_sub_left_of_add_le {k m n} (h : k + m ≤ n) : m ≤ n - k := le_sub_right_of_add_le (by { rw ← nat.add_comm, refine h }) /-- -/ def le_add_of_sub_le_right {k m n} : n - k ≤ m → n ≤ m + k := begin intros h, rw ← nat.add_sub_cancel m k at h, refine (nat.sub_le_sub_right_iff _ _ _ (nat.le_add_left _ _)).mp h, end /-- -/ def add_lt_add_of_le_of_lt {a b c d} (h₁ : a ≤ b) (h₂ : c < d) : a + c < b + d := lt_of_le_of_lt (nat.add_le_add_right h₁ c) (nat.add_lt_add_left h₂ b) /-- -/ def lt_add_of_le_of_pos {a b c} (b_le_c : b ≤ c) (zero_lt_a : 0 < a) : b < c + a := nat.add_zero b ▸ nat.add_lt_add_of_le_of_lt b_le_c zero_lt_a /-- -/ def neg_right_swap {a b c} (c_le_b : c ≤ b) : a - (b - c) = (a + c) - b := begin rw ← nat.add_sub_cancel a _, rw nat.sub_sub_sub_cancel_right c_le_b, rw nat.add_sub_assoc (le_refl _), rw nat.sub_self, rw nat.add_zero, end /-- -/ def sub_mono_left_strict {x y z : nat} (z_le_x : z ≤ x) (x_lt_y : x < y) : x - z < y - z := begin refine @nat.lt_of_add_lt_add_left z _ _ _, rw nat.add_sub_of_le (le_trans z_le_x (le_of_lt x_lt_y)), rw nat.add_sub_of_le z_le_x, refine x_lt_y, end /-- -/ def mul_two (n) : n * 2 = n + n := begin refine (nat.left_distrib _ _ _).trans _, rw nat.mul_one, end /-- -/ def pow_two_ge_one (n : nat) : 1 ≤ 2 ^ n := begin induction n with n hn, refine le_refl _, refine le_trans hn (nat.le_add_left _ _), end /-- -/ def pow_two_monotonic (n : nat) : 2 ^ n < 2 ^ n.succ := lt_add_of_le_of_pos (nat.le_add_left _ _) (pow_two_ge_one _) /-- -/ def smallest_positive_even (n : nat) : 2 ≤ 2 * n.succ := begin induction n with n hn, rw nat.mul_one, refine le_trans hn (nat.le.intro rfl), end /-- -/ def successive_difference (u : nat → nat) (n : nat) := u n.succ - u n /-- -/ def power [has_one α] [has_mul α] (a : α) : nat → α | (nat.zero ) := 1 | (nat.succ n) := power n * a namespace power --———————————————————————————————————————————————————————————————————————-- variables [has_one α] [has_mul α] /-- -/ def mul_commute [has_one β] [has_mul β] (map : α → β) (map_one : map 1 = 1) (map_mul : Π x y, map (x * y) = map x * map y) (a : α) (n) : map (power a n) = power (map a) n := begin induction n with n hn, rw [power, power], rw map_one, rw [power, power], rw map_mul, rw hn, end end power --—————————————————————————————————————————————————————————————————————————————-- namespace lift --————————————————————————————————————————————————————————————————————————-- variables (α) /-- -/ def succ_pos [has_lt α] [has_zero α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_lt_comm nat α] (n : nat) : 0 < (↑n.succ : α) := begin rw zero_is_lifted_zero_lemma nat α, refine has_lift_lt_comm.lt (nat.succ_pos _), end /-- -/ def succ_nonzero [preorder α] [has_zero α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_lt_comm nat α] (n : nat) : (↑n.succ : α) ≠ 0 := (ne_of_gt (nat.lift.succ_pos α _)) /-- -/ def zero_lt_one [has_lt α] [has_zero α] [has_one α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_lt_comm nat α] : (0 : α) < 1 := begin rw one_is_lifted_one_lemma nat α, refine nat.lift.succ_pos α _, end /-- -/ instance zero_lt_one_instance [has_lt α] [has_zero α] [has_one α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_lt_comm nat α] : has_zero_lt_one α := ⟨zero_lt_one α⟩ end lift --——————————————————————————————————————————————————————————————————————————————-- end nat --———————————————————————————————————————————————————————————————————————————————-- section sequences --—————————————————————————————————————————————————————————————————————-- /-- -/ def strictly_increasing [has_lt α] (seq : nat → α) := Π n, seq n < seq n.succ /-- -/ def increasing [has_le α] (seq : nat → α) := Π n, seq n ≤ seq n.succ /-- -/ def strictly_increasing.as_increasing [preorder α] (seq : nat → α) : strictly_increasing seq → increasing seq := begin intros sinc _, refine le_of_lt (sinc _), end /-- -/ def increasing_strong [has_le α] (seq : nat → α) := Π i j, i ≤ j → seq i ≤ seq j /-- -/ def increasing.as_increasing_strong [preorder α] (seq : nat → α) : increasing seq → increasing_strong seq := begin intros inc i j i_le_j, induction j with j hj, cases i_le_j, refine le_refl _, cases nat.of_le_succ i_le_j, refine le_trans (hj h) (inc _), rw h, end /-- -/ def strictly_increasing.as_increasing_strong [preorder α] (seq : nat → α) : strictly_increasing seq → increasing_strong seq := λ s, increasing.as_increasing_strong _ (strictly_increasing.as_increasing _ s) /-- -/ def non_increasing [has_le α] (seq : nat → α) := Π n, seq (nat.succ n) ≤ seq n /-- -/ def non_increasing_strong [has_le α] (seq : nat → α) (k) := Π n, seq (n + k) ≤ seq n /-- -/ def non_increasing.as_non_increasing_strong [preorder α] (seq : nat → α) : non_increasing seq → Π k, non_increasing_strong seq k := begin intros noninc k _, induction k with k hk, refine le_refl _, refine le_trans (noninc _) hk, end /-- -/ def strictly_increasing.ge_index (seq) (sinc : strictly_increasing seq) (k) : k ≤ seq k := begin induction k with _ hk, refine nat.zero_le _, rw nat.succ_eq_add_one, refine le_trans (nat.add_le_add hk (le_refl _)) (sinc _), end /-- -/ def nonneg_compose_preserve [has_zero α] [has_le α] (seq : nat → α) (φ : nat → nat) : 0 ≤ seq → 0 ≤ seq ∘ φ := λ p _, p (φ _) /-- -/ def translate (seq : nat → α) (k) (n) := seq (k + n) /-- -/ def translate.preserve_nonneg [has_zero α] [has_le α] (seq : nat → α) : 0 ≤ seq → 0 ≤ translate seq := λ p _ _, p _ /-- -/ def translate.monotonicity [has_le α] {a b : nat → α} : a ≤ b → translate a ≤ translate b := λ p _ _, p _ /-- -/ def translate.combine (seq : nat → α) (i j) : translate (translate seq i) j = translate seq (i + j) := funext (λ _, by rw [translate, translate, translate, nat.add_assoc]) /-- -/ def translate.compose_commute (seq : nat → α) (f : α → β) (n k) : f (translate seq n k) = translate (f ∘ seq) n k := by rw [translate, translate] /-- -/ def translate.compose_commute.funext (seq : nat → α) (f : α → β) (n) : f ∘ (translate seq n) = translate (f ∘ seq) n := funext (translate.compose_commute seq f n) end sequences --—————————————————————————————————————————————————————————————————————————-- section series --————————————————————————————————————————————————————————————————————————-- variables [has_zero α] [has_add α] /-- -/ def partial_sum (seq : nat → α) : nat → α | (nat.zero ) := 0 | (nat.succ n) := seq n + partial_sum n /-- -/ def partial_sum.preserve_nonneg [preorder α] [has_add_nonneg α] (seq : nat → α) : 0 ≤ seq → 0 ≤ partial_sum seq := begin intros nonneg k, induction k with k hk, refine le_refl _, refine has_add_nonneg.le (nonneg _) hk, end /-- -/ def partial_sum.left_mul_commute [has_mul α] [has_mul_zero_is_zero α] [has_left_add_distributivity α] (seq : nat → α) (C) : partial_sum (λ k, C * seq k) = λ n, C * partial_sum seq n := begin refine funext _, intros n, induction n with n hn, rw partial_sum, rw partial_sum, rw has_mul_zero_is_zero.eq, rw partial_sum, rw partial_sum, rw hn, rw has_left_add_distributivity.eq, end /-- -/ def partial_sum.right_mul_commute [has_mul α] [has_zero_mul_is_zero α] [has_right_add_distributivity α] (seq : nat → α) (C) : partial_sum (λ k, seq k * C) = λ n, partial_sum seq n * C := begin refine funext _, intros n, induction n with n hn, rw partial_sum, rw partial_sum, rw has_zero_mul_is_zero.eq, rw partial_sum, rw partial_sum, rw hn, rw has_right_add_distributivity.eq, end /-- -/ def partial_sum.from_mul [has_one α] [has_mul α] [has_zero_mul_is_zero α] [has_left_unit α] [has_right_add_distributivity α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_add_comm nat α] (a : α) (n : nat) : ↑n * a = partial_sum ↓a n := begin induction n with n hn, rw partial_sum, rw has_lift_zero_same.eq, rw has_zero_mul_is_zero.eq, rw partial_sum, rw nat.succ_eq_add_one, rw nat.add_comm, rw has_lift_add_comm.eq, rw has_right_add_distributivity.eq, rw has_lift_one_same.eq, rw has_left_unit.eq, rw hn, rw const, end /-- -/ def partial_sum.from_mul' [has_one α] [has_mul α] [has_mul_zero_is_zero α] [has_right_unit α] [has_left_add_distributivity α] [has_lift_t nat α] [has_lift_zero_same nat α] [has_lift_one_same nat α] [has_lift_add_comm nat α] (a : α) (n : nat) : a * ↑n = partial_sum ↓a n := begin induction n with n hn, rw partial_sum, rw has_lift_zero_same.eq, rw has_mul_zero_is_zero.eq, rw partial_sum, rw nat.succ_eq_add_one, rw nat.add_comm, rw has_lift_add_comm.eq, rw has_left_add_distributivity.eq, rw has_lift_one_same.eq, rw has_right_unit.eq, rw hn, rw const, end /-- -/ def partial_sum.monotonicity [preorder α] [has_add_le_add α] {a b : nat → α} : a ≤ b → partial_sum a ≤ partial_sum b := begin intros a_le_b n, induction n with _ hn, refine le_refl _, refine has_add_le_add.le (a_le_b _) hn, end /-- -/ def partial_sum.index_monotonicity [preorder α] [has_le_add_of_nonneg_of_le α] (seq : nat → α) (nonneg : 0 ≤ seq) {m n} : m ≤ n → partial_sum seq m ≤ partial_sum seq n := begin intros m_le_n, induction n with n hn, cases m_le_n, refine le_refl _, cases nat.of_le_succ m_le_n, refine has_le_add_of_nonneg_of_le.le (nonneg _) (hn h), rw ← h, end /-- -/ def partial_sum.double_monotonicity [preorder α] [has_le_add_of_nonneg_of_le α] [has_add_le_add α] (a : nat → α) (na) (b : nat → α) (nb) : 0 ≤ a → a ≤ b → na ≤ nb → partial_sum a na ≤ partial_sum b nb := begin intros zero_le_a a_le_b na_le_nb, induction nb with _ hnb, cases na_le_nb, refine le_refl _, cases nat.of_le_succ na_le_nb, refine has_le_add_of_nonneg_of_le.le (le_trans (zero_le_a _) (a_le_b _)) (hnb h), rw h, refine has_add_le_add.le (a_le_b _) (partial_sum.monotonicity a_le_b _), end /-- -/ def partial_sum.sub_as_translate [has_sub α] [has_sub_self_is_zero α] [has_add_sub_assoc α] (seq : nat → α) {m n} (m_le_n : m ≤ n) : partial_sum seq n - partial_sum seq m = partial_sum (translate seq m) (n - m) := begin induction n with n hn, cases m_le_n, refine has_sub_self_is_zero.eq _, cases m_le_n with _ m_le_n, rw has_sub_self_is_zero.eq, rw nat.sub_self, rw partial_sum, rw partial_sum, rw has_add_sub_assoc.eq, rw hn m_le_n, rw nat.succ_sub m_le_n, rw partial_sum, rw translate, rw nat.add_sub_of_le m_le_n, end /-- -/ def partial_sum.lower_differences.bottom [has_sub α] [has_add_sub_assoc α] [has_sub_self_is_zero α] [preorder α] [has_le_add_of_nonneg_of_le α] (seq : nat → α) (nonneg : 0 ≤ seq) {m n} (m_le_n : m ≤ n) : 0 ≤ partial_sum seq n - partial_sum seq m := begin induction n with n hn, cases m_le_n, rw has_sub_self_is_zero.eq, cases nat.of_le_succ m_le_n, rw partial_sum, rw has_add_sub_assoc.eq, refine has_le_add_of_nonneg_of_le.le (nonneg _) (hn h), rw ← h, rw has_sub_self_is_zero.eq, end /-- -/ def partial_sum.lower_differences [has_sub α] [has_sub_self_is_zero α] [has_add_sub_assoc α] [preorder α] [has_add_le_add α] [has_le_add_of_nonneg_of_le α] (seq : nat → α) (nonneg : 0 ≤ seq) {k m n} (k_le_m : k ≤ m) (m_le_n : m ≤ n) : partial_sum seq n - partial_sum seq m ≤ partial_sum seq n - partial_sum seq k := begin induction n with n hn, cases m_le_n, cases k_le_m, refine le_refl _, cases nat.of_le_succ m_le_n, rw partial_sum, rw has_add_sub_assoc.eq, rw has_add_sub_assoc.eq, refine has_add_le_add.le (le_refl _) (hn h), rw ← h, rw has_sub_self_is_zero.eq, refine partial_sum.lower_differences.bottom _ nonneg k_le_m, end --———————————————————————————————————————————————————————————————————————————————————————-- variables [has_sub α] /-- -/ def shape_sum (seq : nat → α) (φ : nat → nat) (n : nat) := partial_sum seq (φ n.succ) - partial_sum seq (φ n) /-- -/ def shape_sum.unfold [has_sub_self_is_zero α] [has_add_sub_assoc α] [has_sub_add_sub_cancel α] (seq : nat → α) (φ) (sinc_φ : strictly_increasing φ) {m n} (m_le_n : m ≤ n) : partial_sum (translate (shape_sum seq φ) m) (n - m) = partial_sum (translate seq (φ m)) (φ n - φ m) := begin let strong_inc := strictly_increasing.as_increasing_strong _ sinc_φ, induction n with n hn, cases m_le_n, rw [nat.sub_self, nat.sub_self, partial_sum, partial_sum], cases nat.of_le_succ m_le_n, rw nat.succ_sub h, rw partial_sum, rw hn h, rw translate, rw nat.add_sub_of_le h, rw shape_sum, rw ← partial_sum.sub_as_translate seq (strong_inc _ _ h), rw ← partial_sum.sub_as_translate seq (strong_inc _ _ m_le_n), rw has_sub_add_sub_cancel.eq, rw h, rw [nat.sub_self, nat.sub_self, partial_sum, partial_sum], end end series --————————————————————————————————————————————————————————————————————————————-- section absolute_value --————————————————————————————————————————————————————————————————-- variables [has_zero α] [has_add α] /-- -/ def triangle_inequality [has_zero β] [has_add β] [preorder β] [has_add_le_add β] (abs : α → β) (abs_zero : abs 0 = 0) (abs_triangle : Π x y, abs (x + y) ≤ abs x + abs y) (seq) (n) : abs (partial_sum seq n) ≤ partial_sum (abs ∘ seq) n := begin induction n with _ hn, rw [partial_sum, partial_sum], rw abs_zero, refine le_trans (abs_triangle _ _) (has_add_le_add.le (le_refl _) hn), end /-- -/ def triangle_equality [preorder α] [has_add_nonneg α] (abs : α → α) (nonneg_to_abs : Π z, 0 ≤ z → abs z = z) (seq nonneg) (n) : abs (partial_sum seq n) = partial_sum seq n := nonneg_to_abs _ (partial_sum.preserve_nonneg _ nonneg _) end absolute_value --————————————————————————————————————————————————————————————————————-- end riemann_hypothesis --————————————————————————————————————————————————————————————————--
6d0730509f5b69ed499c8e56ce1e3fd1220e4bdb
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/wf.lean
cbcb0468509498baea5e76b7fcc48af7a0f30c75
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
7,351
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 -/ prelude import init.data.nat.basic init.data.prod universes u v inductive acc {α : Sort u} (r : α → α → Prop) : α → Prop | intro (x : α) (h : ∀ y, r y x → acc y) : acc x namespace acc variables {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y := acc.rec_on h₁ (λ x₁ ac₁ ih h₂, ac₁ y h₂) h₂ end acc /-- A relation `r : α → α → Prop` is well-founded when `∀ x, (∀ y, r y x → P y → P x) → P x` for all predicates `P`. Once you know that a relation is well_founded, you can use it to define fixpoint functions on `α`.-/ inductive well_founded {α : Sort u} (r : α → α → Prop) : Prop | intro (h : ∀ a, acc r a) : well_founded class has_well_founded (α : Sort u) : Type u := (r : α → α → Prop) (wf : well_founded r) namespace well_founded def apply {α : Sort u} {r : α → α → Prop} (wf : well_founded r) : ∀ a, acc r a := assume a, well_founded.rec_on wf (λ p, p) a section parameters {α : Sort u} {r : α → α → Prop} local infix `≺`:50 := r parameter hwf : well_founded r lemma recursion {C : α → Sort v} (a : α) (h : Π x, (Π y, y ≺ x → C y) → C x) : C a := acc.rec_on (apply hwf a) (λ x₁ ac₁ ih, h x₁ ih) lemma induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a := recursion a h variable {C : α → Sort v} variable F : Π x, (Π y, y ≺ x → C y) → C x def fix_F (x : α) (a : acc r x) : C x := acc.rec_on a (λ x₁ ac₁ ih, F x₁ ih) lemma fix_F_eq (x : α) (acx : acc r x) : fix_F F x acx = F x (λ (y : α) (p : y ≺ x), fix_F F y (acc.inv acx p)) := acc.drec (λ x r ih, rfl) acx end variables {α : Sort u} {C : α → Sort v} {r : α → α → Prop} /-- Well-founded fixpoint -/ def fix (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : C x := fix_F F x (apply hwf x) /-- Well-founded fixpoint satisfies fixpoint equation -/ lemma fix_eq (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (λ y h, fix hwf F y) := fix_F_eq F x (apply hwf x) end well_founded open well_founded /-- Empty relation is well-founded -/ def empty_wf {α : Sort u} : well_founded empty_relation := well_founded.intro (λ (a : α), acc.intro a (λ (b : α) (lt : false), false.rec _ lt)) /- Subrelation of a well-founded relation is well-founded -/ namespace subrelation section parameters {α : Sort u} {r Q : α → α → Prop} parameters (h₁ : subrelation Q r) parameters (h₂ : well_founded r) def accessible {a : α} (ac : acc r a) : acc Q a := acc.rec_on ac (λ x ax ih, acc.intro x (λ (y : α) (lt : Q y x), ih y (h₁ lt))) def wf : well_founded Q := ⟨λ a, accessible (apply h₂ a)⟩ end end subrelation -- The inverse image of a well-founded relation is well-founded namespace inv_image section parameters {α : Sort u} {β : Sort v} {r : β → β → Prop} parameters (f : α → β) parameters (h : well_founded r) private def acc_aux {b : β} (ac : acc r b) : ∀ (x : α), f x = b → acc (inv_image r f) x := acc.rec_on ac (λ x acx ih z e, acc.intro z (λ y lt, eq.rec_on e (λ acx ih, ih (f y) lt y rfl) acx ih)) def accessible {a : α} (ac : acc r (f a)) : acc (inv_image r f) a := acc_aux ac a rfl def wf : well_founded (inv_image r f) := ⟨λ a, accessible (apply h (f a))⟩ end end inv_image -- The transitive closure of a well-founded relation is well-founded namespace tc section parameters {α : Sort u} {r : α → α → Prop} local notation `r⁺` := tc r def accessible {z : α} (ac : acc r z) : acc (tc r) z := acc.rec_on ac (λ x acx ih, acc.intro x (λ y rel, tc.rec_on rel (λ a b rab acx ih, ih a rab) (λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab) acx ih)) def wf (h : well_founded r) : well_founded r⁺ := ⟨λ a, accessible (apply h a)⟩ end end tc /-- less-than is well-founded -/ def nat.lt_wf : well_founded nat.lt := ⟨nat.rec (acc.intro 0 (λ n h, absurd h (nat.not_lt_zero n))) (λ n ih, acc.intro (nat.succ n) (λ m h, or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h)) (λ e, eq.substr e ih) (acc.inv ih)))⟩ def measure {α : Sort u} : (α → ℕ) → α → α → Prop := inv_image (<) def measure_wf {α : Sort u} (f : α → ℕ) : well_founded (measure f) := inv_image.wf f nat.lt_wf def sizeof_measure (α : Sort u) [has_sizeof α] : α → α → Prop := measure sizeof def sizeof_measure_wf (α : Sort u) [has_sizeof α] : well_founded (sizeof_measure α) := measure_wf sizeof instance has_well_founded_of_has_sizeof (α : Sort u) [has_sizeof α] : has_well_founded α := {r := sizeof_measure α, wf := sizeof_measure_wf α} namespace prod open well_founded section variables {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive lex : α × β → α × β → Prop | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive rprod : α × β → α × β → Prop | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : rprod (a₁, b₁) (a₂, b₂) end section parameters {α : Type u} {β : Type v} parameters {ra : α → α → Prop} {rb : β → β → Prop} local infix `≺`:50 := lex ra rb def lex_accessible {a} (aca : acc ra a) (acb : ∀ b, acc rb b): ∀ b, acc (lex ra rb) (a, b) := acc.rec_on aca (λ xa aca iha b, acc.rec_on (acb b) (λ xb acb ihb, acc.intro (xa, xb) (λ p lt, have aux : xa = xa → xb = xb → acc (lex ra rb) p, from @prod.lex.rec_on α β ra rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex ra rb) p₁) p (xa, xb) lt (λ a₁ b₁ a₂ b₂ h (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), iha a₁ (eq.rec_on eq₂ h) b₁) (λ a b₁ b₂ h (eq₂ : a = xa) (eq₃ : b₂ = xb), eq.rec_on eq₂.symm (ihb b₁ (eq.rec_on eq₃ h))), aux rfl rfl))) -- The lexicographical order of well founded relations is well-founded def lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) := ⟨λ p, cases_on p (λ a b, lex_accessible (apply ha a) (well_founded.apply hb) b)⟩ -- relational product is a subrelation of the lex def rprod_sub_lex : ∀ a b, rprod ra rb a b → lex ra rb a b := λ a b h, prod.rprod.rec_on h (λ a₁ b₁ a₂ b₂ h₁ h₂, lex.left rb b₁ b₂ h₁) -- The relational product of well founded relations is well-founded def rprod_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) := subrelation.wf (rprod_sub_lex) (lex_wf ha hb) end instance has_well_founded {α : Type u} {β : Type v} [s₁ : has_well_founded α] [s₂ : has_well_founded β] : has_well_founded (α × β) := {r := lex s₁.r s₂.r, wf := lex_wf s₁.wf s₂.wf} end prod
fae8f244cc187c490b8d89ede10956a4dab545e1
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/multiset/antidiagonal.lean
ce060a90e14e17ee07028247fb507c3f273e8bcd
[ "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
2,987
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.powerset /-! # The antidiagonal on a multiset. The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ namespace multiset open list variables {α β : Type*} /-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)` such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/ def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem antidiagonal_coe (l : list α) : @antidiagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem antidiagonal_coe' (l : list α) : @antidiagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' /-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s` if and only if `t₁ + t₂ = s`. -/ @[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} : x ∈ antidiagonal s ↔ x.1 + x.2 = s := quotient.induction_on s $ λ l, begin simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], cases x with x₁ x₂, exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩ end @[simp] theorem antidiagonal_map_fst (s : multiset α) : (antidiagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_map_snd (s : multiset α) : (antidiagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0) ::ₘ 0 := rfl @[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a ::ₘ s) = map (prod.map id (cons a)) (antidiagonal s) + map (prod.map (cons a) id) (antidiagonal s) := quotient.induction_on s $ λ l, begin simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe, coe_map, antidiagonal_coe', coe_add], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_antidiagonal (s : multiset α) : card (antidiagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← antidiagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm], cc }, end end multiset
536829aeee6f1fe840e0937fb9951d9fdd59c25e
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/measure_theory/measurable_space.lean
d8b122e6c95b5e396830f1178ddaa01051cd1709
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,182
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 data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import order.filter.basic /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ local attribute [instance] classical.prop_decidable open set encodable function open_locale classical filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort x} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type u) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable' (f i)) → is_measurable' (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } end @[ext] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀s:set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable sᶜ | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable (⋃₀ (measurable_space.is_measurable' '' ms)) s := begin change @is_measurable' _ (generate_from _) _ ↔ _, dsimp [generate_from], rw (show (⨆ (b : measurable_space α) (H : b ∈ ms), set_of (@is_measurable _ b)) = (⋃₀ (is_measurable' '' ms)), { ext, simp only [exists_prop, mem_Union, sUnion_image, mem_set_of_eq], refl, }) end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable (⋃i, (m i).is_measurable') s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λs, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λs, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma subsingleton.measurable [measurable_space α] [measurable_space β] [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable_id [measurable_space α] : measurable (@id α) := λ t, id lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h lemma measurable.piecewise [measurable_space α] [measurable_space β] {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end @[simp] lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := by { intros s hs, by_cases a ∈ s; simp [*, preimage] } lemma measurable.indicator [measurable_space α] [measurable_space β] [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one {α β} [measurable_space α] [has_one α] [measurable_space β] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] [measurable_space α] [measurable_space β] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := have f = (λu, f ()) := funext $ assume ⟨⟩, rfl, by { rw this, exact measurable_const } section nat lemma measurable_from_nat [measurable_space α] {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat [measurable_space α] {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' [measurable_space α] {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest [measurable_space α] {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find [measurable_space α] {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe [measurable_space α] {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image [measurable_space α] {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover [measurable_space α] [measurable_space β] {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λa:s, f a)) (hd : measurable (λa:t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_space α] [measurable_space β] [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λa, (f a).1) ∧ measurable (λa, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi instance measurable_space.pi {α : Type u} {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (Πa, β a) := ⨆a, (m a).comap (λb, b a) lemma measurable_pi_apply {α : Type u} {β : α → Type v} [Πa, measurable_space (β a)] (a : α) : measurable (λf:Πa, β a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable_pi_lambda {α : Type u} {β : α → Type v} {γ : Type w} [Πa, measurable_space (β a)] [measurable_space γ] (f : γ → Πa, β a) (hf : ∀a, measurable (λc, f c a)) : measurable f := measurable.of_le_map $ supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) end pi instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_rec {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : @measurable (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv instance (α β) [measurable_space α] [measurable_space β] : has_coe_to_fun (measurable_equiv α β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } /-- The composition of equivalences between measurable spaces. -/ def trans [measurable_space α] [measurable_space β] [measurable_space γ] (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } lemma trans_to_equiv {α β} [measurable_space α] [measurable_space β] [measurable_space γ] (e : measurable_equiv α β) (f : measurable_equiv β γ) : (e.trans f).to_equiv = e.to_equiv.trans f.to_equiv := rfl /-- The inverse of an equivalence between measurable spaces. -/ def symm [measurable_space α] [measurable_space β] (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } lemma symm_to_equiv {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : e.symm.to_equiv = e.to_equiv.symm := rfl /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun protected lemma measurable_coe_iff {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λh, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := measurable.prod_mk (ab.measurable_to_fun.comp (measurable.fst measurable_id)) (cd.measurable_to_fun.comp (measurable.snd measurable_id)), measurable_inv_fun := measurable.prod_mk (ab.measurable_inv_fun.comp (measurable.fst measurable_id)) (cd.measurable_inv_fun.comp (measurable.snd measurable_id)) } /-- Products of measurable spaces are symmetric. -/ def prod_comm [measurable_space α] [measurable_space β] : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id), measurable_inv_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id) } /-- Sums of measurable spaces are symmetric. -/ def sum_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod [measurable_space α] [measurable_space β] (s : set α) (t : set β) : measurable_equiv (s.prod t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable.prod_mk measurable_id.subtype_coe.fst.subtype_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable.prod_mk measurable_id.fst.subtype_coe measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton [measurable_space α] (a:α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, equiv.set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λa, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λb, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) ((measurable_inr.comp (measurable.fst measurable_id)).prod_mk (measurable.snd measurable_id)) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has aᶜ) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) namespace dynkin_system @[ext] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has aᶜ | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, is_measurable t → C t → C tᶜ) (h_union : ∀f:ℕ → set α, pairwise (disjoint on f) → (∀i, is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter
dc1bbde24b68910ad1e9f606c84a7c987b9e0ade
94e33a31faa76775069b071adea97e86e218a8ee
/test/matrix.lean
44cc83a135b9b7c0510c808c8420b56db30d8fdc
[ "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
5,003
lean
import data.matrix.notation import linear_algebra.matrix.determinant import group_theory.perm.fin import tactic.norm_swap variables {α β : Type} [semiring α] [ring β] namespace matrix open_locale matrix /-! Test that the dimensions are inferred correctly, even for empty matrices -/ section dimensions set_option pp.universes true set_option pp.all true meta def get_dims (e : pexpr) : tactic (expr × expr) := do elem_t ← tactic.mk_meta_var (expr.sort level.zero.succ), e ← tactic.to_expr ``(%%e : matrix _ _ %%elem_t) tt ff, t ← tactic.infer_type e, `(matrix.{0 0 0} (fin %%m) (fin %%n) %%elem_t) ← tactic.infer_type e, return (m, n) -- we test equality of expressions here to ensure that we have `2` and not `1.succ` in the type run_cmd do d ← get_dims ``(!![]), guard $ d = (`(0), `(0)) run_cmd do d ← get_dims ``(!![;]), guard $ d = (`(1), `(0)) run_cmd do d ← get_dims ``(!![;;]), guard $ d = (`(2), `(0)) run_cmd do d ← get_dims ``(!![,]), guard $ d = (`(0), `(1)) run_cmd do d ← get_dims ``(!![,,]), guard $ d = (`(0), `(2)) run_cmd do d ← get_dims ``(!![1]), guard $ d = (`(1), `(1)) run_cmd do d ← get_dims ``(!![1,]), guard $ d = (`(1), `(1)) run_cmd do d ← get_dims ``(!![1;]), guard $ d = (`(1), `(1)) run_cmd do d ← get_dims ``(!![1,2;3,4]), guard $ d = (`(2), `(2)) end dimensions run_cmd guard $ (!![1;2]) = of ![![1], ![2]] run_cmd guard $ (!![1,3]) = of ![![1,3]] run_cmd guard $ (!![1,2;3,4]) = of ![![1,2], ![3,4]] run_cmd guard $ (!![1,2;3,4;]) = of ![![1,2], ![3,4]] run_cmd guard $ (!![1,2,;3,4,]) = of ![![1,2], ![3,4]] example {a a' b b' c c' d d' : α} : !![a, b; c, d] + !![a', b'; c', d'] = !![a + a', b + b'; c + c', d + d'] := by simp example {a a' b b' c c' d d' : β} : !![a, b; c, d] - !![a', b'; c', d'] = !![a - a', b - b'; c - c', d - d'] := by simp example {a a' b b' c c' d d' : α} : !![a, b; c, d] ⬝ !![a', b'; c', d'] = !![a * a' + b * c', a * b' + b * d'; c * a' + d * c', c * b' + d * d'] := by simp [-equiv.perm.coe_subsingleton] example {a b c d x y : α} : mul_vec !![a, b; c, d] ![x, y] = ![a * x + b * y, c * x + d * y] := by simp example {a b c d : α} : minor !![a, b; c, d] ![1, 0] ![0] = !![c; a] := by { ext, simp } example {a b c : α} : ![a, b, c] 0 = a := by simp example {a b c : α} : ![a, b, c] 1 = b := by simp example {a b c : α} : ![a, b, c] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 0 = a := by simp example {a b c d : α} : ![a, b, c, d] 1 = b := by simp example {a b c d : α} : ![a, b, c, d] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 3 = d := by simp example {a b c d : α} : ![a, b, c, d] 42 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 0 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 1 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 2 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 3 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 4 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 5 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 6 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 7 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 8 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 9 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 123 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 123456789 = e := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 5 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 7 = h := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 37 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 99 = d := by simp example {α : Type*} [comm_ring α] {a b c d : α} : matrix.det !![a, b; c, d] = a * d - b * c := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [det_succ_row_zero, fin.sum_univ_succ, neg_mul, mul_one, fin.default_eq_zero, fin.coe_zero, one_mul, cons_val_one, fin.coe_succ, univ_unique, minor_apply, pow_one, fin.zero_succ_above, fin.succ_succ_above_zero, finset.sum_singleton, cons_val_zero, cons_val_succ, det_fin_zero, pow_zero] -/ ring end example {α : Type*} [comm_ring α] {a b c d e f g h i : α} : matrix.det !![a, b, c; d, e, f; g, h, i] = a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [det_succ_row_zero, fin.sum_univ_succ, neg_mul, cons_append, mul_one, fin.default_eq_zero, fin.coe_zero, cons_vec_bit0_eq_alt0, one_mul, cons_val_one, cons_vec_alt0, fin.succ_succ_above_one, fin.coe_succ, univ_unique, minor_apply, pow_one, fin.zero_succ_above, fin.succ_zero_eq_one, fin.succ_succ_above_zero, nat.neg_one_sq, finset.sum_singleton, cons_val_zero, cons_val_succ, det_fin_zero, head_cons, pow_zero] -/ ring end end matrix
22b2f9367e7fbac231e6e60beaf4cf95deb15adc
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/associated.lean
f2abcb4255a80f5e01d745850e5bcb6d0f21aeb3
[ "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
28,809
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker -/ import data.multiset.basic import algebra.divisibility import algebra.invertible /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} theorem is_unit_iff_dvd_one [comm_monoid α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_monoid α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, h.trans (one_dvd _), λ h, h _⟩ theorem is_unit_of_dvd_unit {α} [comm_monoid α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ xy.trans $ is_unit_iff_dvd_one.1 hu lemma is_unit_of_dvd_one [comm_monoid α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [comm_cancel_monoid_with_zero α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ dvd_not_unit x y := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, mul_left_cancel' hx0 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [comm_cancel_monoid_with_zero α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x ^ m * x ∣ x ^ m * 1, { rw [← pow_succ', mul_one], exact (pow_dvd_pow _ (nat.succ_le_of_lt hmn)).trans h }, rwa [mul_dvd_mul_iff_left, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end section prime variables [comm_monoid_with_zero α] /-- prime element of a `comm_monoid_with_zero` -/ def prime (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime variables {p : α} (hp : prime p) lemma ne_zero (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit (hp : prime p) : ¬ is_unit p := hp.2.1 lemma ne_one (hp : prime p) : p ≠ 1 := λ h, hp.2.1 (h.symm ▸ is_unit_one) lemma dvd_or_dvd (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h lemma dvd_of_dvd_pow (hp : prime p) {a : α} {n : ℕ} (h : p ∣ a^n) : p ∣ a := begin induction n with n ih, { rw pow_zero at h, have := is_unit_of_dvd_one _ h, have := not_unit hp, contradiction }, rw pow_succ at h, cases dvd_or_dvd hp h with dvd_a dvd_pow, { assumption }, exact ih dvd_pow end end prime @[simp] lemma not_prime_zero : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.dvd_or_dvd this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end end prime lemma left_dvd_or_dvd_right_of_dvd_prime_mul [comm_cancel_monoid_with_zero α] {a : α} : ∀ {b p : α}, prime p → a ∣ p * b → p ∣ a ∨ a ∣ b := begin rintros b p hp ⟨c, hc⟩, rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩, { exact or.inl h }, { rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc, exact or.inr (hc.symm ▸ dvd_mul_right _ _) } end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ class irreducible [monoid α] (p : α) : Prop := (not_unit' : ¬ is_unit p) (is_unit_or_is_unit' : ∀a b, p = a * b → is_unit a ∨ is_unit b) namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := irreducible.is_unit_or_is_unit' a b h end irreducible lemma irreducible_iff [monoid α] {p : α} : irreducible p ↔ ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b := ⟨λ h, ⟨h.1, h.2⟩, λ h, ⟨h.1, h.2⟩⟩ @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible_iff] @[simp] theorem not_irreducible_zero [monoid_with_zero α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [monoid_with_zero α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible_iff] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end protected lemma prime.irreducible [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.dvd_or_dvd (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show a ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, mul_right_cancel' (show b ≠ 0, from λ h, by simp [*, prime] at *) $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [mul_right_inj' hp0] at h⟩, (hp.dvd_or_dvd hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- If `p` and `q` are irreducible, then `p ∣ q` implies `q ∣ p`. -/ lemma irreducible.dvd_symm [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q → q ∣ p := begin tactic.unfreeze_local_instances, rintros ⟨q', rfl⟩, rw is_unit.mul_right_dvd (or.resolve_left (of_irreducible_mul hq) hp.not_unit), end lemma irreducible.dvd_comm [monoid α] {p q : α} (hp : irreducible p) (hq : irreducible q) : p ∣ q ↔ q ∣ p := ⟨hp.dvd_symm hq, hq.dvd_symm hp⟩ /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ /-- The setoid of the relation `x ~ᵤ y` iff there is a unit `u` such that `x * u = y` -/ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [monoid_with_zero α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated.mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ lemma associated.mul_left [comm_monoid α] (a : α) {b c : α} (h : b ~ᵤ c) : (a * b) ~ᵤ (a * c) := (associated.refl a).mul_mul h lemma associated.mul_right [comm_monoid α] {a b : α} (h : a ~ᵤ b) (c : α) : (a * c) ~ᵤ (b * c) := h.mul_mul (associated.refl c) lemma associated.pow_pow [comm_monoid α] {a b : α} {n : ℕ} (h : a ~ᵤ b) : a ^ n ~ᵤ b ^ n := begin induction n with n ih, { simp [h] }, convert h.mul_mul ih; rw pow_succ end protected lemma associated.dvd [monoid α] {a b : α} : a ~ᵤ b → a ∣ b := λ ⟨u, hu⟩, ⟨u, hu.symm⟩ protected lemma associated.dvd_dvd [monoid α] {a b : α} (h : a ~ᵤ b) : a ∣ b ∧ b ∣ a := ⟨h.dvd, h.symm.dvd⟩ theorem associated_of_dvd_dvd [cancel_monoid_with_zero α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have hac0 : a * c ≠ 0, { intro con, rw [con, zero_mul] at a_eq, apply ha0 a_eq, }, have : a * (c * d) = a * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hcd : (c * d) = 1, from mul_left_cancel' ha0 this, have : a * c * (d * c) = a * c * 1 := by rw [← mul_assoc, ← a_eq, mul_one], have hdc : d * c = 1, from mul_left_cancel' hac0 this, exact ⟨⟨c, d, hcd, hdc⟩, rfl⟩ end theorem dvd_dvd_iff_associated [cancel_monoid_with_zero α] {a b : α} : a ∣ b ∧ b ∣ a ↔ a ~ᵤ b := ⟨λ ⟨h1, h2⟩, associated_of_dvd_dvd h1 h2, associated.dvd_dvd⟩ lemma exists_associated_mem_of_dvd_prod [comm_cancel_monoid_with_zero α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.dvd_or_dvd hps with h h, { use [a, by simp], cases h with u hu, cases (((hs a (multiset.mem_cons.2 (or.inl rfl))).irreducible) .is_unit_or_is_unit hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma associated.dvd_iff_dvd_left [monoid α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.mul_right_dvd.symm lemma associated.dvd_iff_dvd_right [monoid α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ units.dvd_mul_right.symm lemma associated.eq_zero_iff [monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma associated.ne_zero_iff [monoid_with_zero α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := not_congr h.eq_zero_iff protected lemma associated.prime [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨h.ne_zero_iff.1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [units.mul_right_dvd], intros a b, exact hp.dvd_or_dvd }⟩⟩ lemma irreducible.associated_of_dvd [cancel_monoid_with_zero α] {p q : α} (p_irr : irreducible p) (q_irr : irreducible q) (dvd : p ∣ q) : associated p q := associated_of_dvd_dvd dvd (p_irr.dvd_symm q_irr dvd) lemma prime.associated_of_dvd [comm_cancel_monoid_with_zero α] {p q : α} (p_prime : prime p) (q_prime : prime q) (dvd : p ∣ q) : associated p q := p_prime.irreducible.associated_of_dvd q_prime.irreducible dvd lemma associated.prime_iff [comm_monoid_with_zero α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨h.prime, h.symm.prime⟩ protected lemma associated.is_unit [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a → is_unit b := let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩ lemma associated.is_unit_iff [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨h.is_unit, h.symm.is_unit⟩ protected lemma associated.irreducible [monoid α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt h.symm.is_unit hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.is_unit_or_is_unit hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ protected lemma associated.irreducible_iff [monoid α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨h.irreducible, h.symm.irreducible⟩ lemma associated.of_mul_left [comm_cancel_monoid_with_zero α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), mul_left_cancel' ha begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated.of_mul_right [comm_cancel_monoid_with_zero α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated.of_mul_left section unique_units variables [monoid α] [unique (units α)] theorem associated_iff_eq {x y : α} : x ~ᵤ y ↔ x = y := begin split, { rintro ⟨c, rfl⟩, simp [subsingleton.elim c 1] }, { rintro rfl, refl }, end theorem associated_eq_eq : (associated : α → α → Prop) = eq := by { ext, rw associated_iff_eq } end unique_units /-- The quotient of a monoid by the `associated` relation. Two elements `x` and `y` are associated iff there is a unit `u` such that `x * u = y`. There is a natural monoid structure on `associates α`. -/ def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated /-- The canonical quotient map from a monoid `α` into the `associates` of `α` -/ protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) theorem mk_surjective [monoid α] : function.surjective (@associates.mk α _) := forall_associated.2 (λ a, ⟨a, rfl⟩) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ lemma exists_rep [monoid α] (a : associates α) : ∃ a0 : α, associates.mk a0 = a := quot.exists_rep a section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := has_dvd.dvd, le_refl := dvd_refl, le_trans := λ a b c, dvd_trans} @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl /-- `associates.mk` as a `monoid_hom`. -/ protected def mk_monoid_hom : α →* (associates α) := ⟨associates.mk, mk_one, λ x y, mk_mul_mk⟩ @[simp] lemma mk_monoid_hom_apply (a : α) : associates.mk_monoid_hom a = associates.mk a := rfl lemma associated_map_mk {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a ~ᵤ f (associates.mk a) := associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by { rw [← multiset.rel_eq, multiset.rel_map], simp only [mk_eq_mk_iff_associated] } theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem units_eq_one (u : units (associates α)) : u = 1 := units.ext (mul_eq_one_iff.1 u.val_inv).1 instance unique_units : unique (units (associates α)) := { default := 1, uniq := associates.units_eq_one } theorem coe_unit_eq_one (u : units (associates α)): (u : associates α) = 1 := by simp theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx, hy, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := dvd.intro _ (one_mul a) theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_monoid_with_zero variables [comm_monoid_with_zero α] @[simp] theorem mk_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ instance : comm_monoid_with_zero (associates α) := { zero_mul := by { rintro ⟨a⟩, show associates.mk (0 * a) = associates.mk 0, rw [zero_mul] }, mul_zero := by { rintro ⟨a⟩, show associates.mk (a * 0) = associates.mk 0, rw [mul_zero] }, .. associates.comm_monoid, .. associates.has_zero } instance [nontrivial α] : nontrivial (associates α) := ⟨⟨0, 1, assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this⟩⟩ lemma exists_non_zero_rep {a : associates α} : a ≠ 0 → ∃ a0 : α, a0 ≠ 0 ∧ associates.mk a0 = a := quotient.induction_on a (λ b nz, ⟨b, mt (congr_arg quotient.mk) nz, rfl⟩) theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d) * c, calc b = (a * c) * ↑d : hd.symm ... = a * (↑d * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd theorem mk_dvd_mk {a b : α} : associates.mk a ∣ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq.symm).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match prime.le_or_le hp this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_eq_zero] }, apply and_congr, { rw [is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_dvd_mk, mk_dvd_mk, mk_dvd_mk], end theorem irreducible_mk (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp only [irreducible_iff, is_unit_mk], apply and_congr iff.rfl, split, { rintro h x y rfl, simpa [is_unit_mk] using h (associates.mk x) (associates.mk y) rfl }, { intros h x y, refine quotient.induction_on₂ x y (assume x y a_eq, _), rcases quotient.exact a_eq.symm with ⟨u, a_eq⟩, rw mul_assoc at a_eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ a_eq.symm } end theorem mk_dvd_not_unit_mk_iff {a b : α} : dvd_not_unit (associates.mk a) (associates.mk b) ↔ dvd_not_unit a b := begin rw [dvd_not_unit, dvd_not_unit, ne, ne, mk_eq_zero], apply and_congr_right, intro ane0, split, { contrapose!, rw forall_associated, intros h x hx hbax, rw [mk_mul_mk, mk_eq_mk_iff_associated] at hbax, cases hbax with u hu, apply h (x * ↑u⁻¹), { rw is_unit_mk at hx, rw associated.is_unit_iff, apply hx, use u, simp, }, simp [← mul_assoc, ← hu] }, { rintro ⟨x, ⟨hx, rfl⟩⟩, use associates.mk x, simp [is_unit_mk, mk_mul_mk, hx], } end theorem dvd_not_unit_of_lt {a b : associates α} (hlt : a < b) : dvd_not_unit a b := begin split, { rintro rfl, apply not_lt_of_le _ hlt, apply dvd_zero }, rcases hlt with ⟨⟨x, rfl⟩, ndvd⟩, refine ⟨x, _, rfl⟩, contrapose! ndvd, rcases ndvd with ⟨u, rfl⟩, simp, end end comm_monoid_with_zero section comm_cancel_monoid_with_zero variable [comm_cancel_monoid_with_zero α] instance : partial_order (associates α) := { le_antisymm := λ a' b', quotient.induction_on₂ a' b' (λ a b hab hba, quot.sound $ associated_of_dvd_dvd (dvd_of_mk_le_mk hab) (dvd_of_mk_le_mk hba)) .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, (mul_zero a).symm⟩, .. associates.partial_order } instance : no_zero_divisors (associates α) := ⟨λ x y, (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl))⟩ theorem irreducible_iff_prime_iff : (∀ a : α, irreducible a ↔ prime a) ↔ (∀ a : (associates α), irreducible a ↔ prime a) := begin rw forall_associated, split; intros h a; have ha := h a; rw irreducible_mk at *; rw prime_mk at *; exact ha, end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, mul_left_cancel' (mt mk_eq_zero.2 ha) hu⟩ end lemma eq_of_mul_eq_mul_right : ∀(a b c : associates α), b ≠ 0 → a * b = c * b → a = c := λ a b c bne0, (mul_comm b a) ▸ (mul_comm b c) ▸ (eq_of_mul_eq_mul_left b a c bne0) lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (dvd_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end instance : comm_cancel_monoid_with_zero (associates α) := { mul_left_cancel_of_ne_zero := eq_of_mul_eq_mul_left, mul_right_cancel_of_ne_zero := eq_of_mul_eq_mul_right, .. (infer_instance : comm_monoid_with_zero (associates α)) } theorem dvd_not_unit_iff_lt {a b : associates α} : dvd_not_unit a b ↔ a < b := dvd_and_not_dvd_iff.symm end comm_cancel_monoid_with_zero end associates
d5d80708536ea4ae7c383c69edd7c276a69d72fc
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/group_theory/perm/cycles.lean
f6eff1556b4e92c590933aeeb999a3c48b97c6d6
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,426
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.nat.parity import data.equiv.fintype import group_theory.perm.sign import data.finset.noncomm_prod /-! # Cyclic permutations ## Main definitions In the following, `f : equiv.perm β`. * `equiv.perm.is_cycle`: `f.is_cycle` when two nonfixed points of `β` are related by repeated application of `f`. * `equiv.perm.same_cycle`: `f.same_cycle x y` when `x` and `y` are in the same cycle of `f`. The following two definitions require that `β` is a `fintype`: * `equiv.perm.cycle_of`: `f.cycle_of x` is the cycle of `f` that `x` belongs to. * `equiv.perm.cycle_factors`: `f.cycle_factors` is a list of disjoint cyclic permutations that multiply to `f`. ## Main results * This file contains several closure results: - `closure_is_cycle` : The symmetric group is generated by cycles - `closure_cycle_adjacent_swap` : The symmetric group is generated by a cycle and an adjacent transposition - `closure_cycle_coprime_swap` : The symmetric group is generated by a cycle and a coprime transposition - `closure_prime_cycle_swap` : The symmetric group is generated by a prime cycle and a transposition -/ namespace equiv.perm open equiv function finset variables {α : Type*} {β : Type*} [decidable_eq α] section sign_cycle /-! ### `is_cycle` -/ variables [fintype α] /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) : Prop := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle.ne_one {f : perm β} (h : is_cycle f) : f ≠ 1 := λ hf, by simpa [hf, is_cycle] using h @[simp] lemma not_is_cycle_one : ¬ (1 : perm β).is_cycle := λ H, H.ne_one rfl lemma is_cycle.two_le_card_support {f : perm α} (h : is_cycle f) : 2 ≤ f.support.card := two_le_card_support_of_ne_one h.ne_one lemma is_cycle_swap {α : Type*} [decidable_eq α] {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_swap.is_cycle {α : Type*} [decidable_eq α] {f : perm α} (hf : is_swap f) : is_cycle f := begin obtain ⟨x, y, hxy, rfl⟩ := hf, exact is_cycle_swap hxy, end lemma is_cycle.inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }, λ y hy, let ⟨i, hi⟩ := hx.2 y (by { simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *, cc }) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma is_cycle.is_cycle_conj {f g : perm β} (hf : is_cycle f) : is_cycle (g * f * g⁻¹) := begin obtain ⟨a, ha1, ha2⟩ := hf, refine ⟨g a, by simp [ha1], λ b hb, _⟩, obtain ⟨i, hi⟩ := ha2 (g⁻¹ b) _, { refine ⟨i, _⟩, rw conj_gpow, simp [hi] }, { contrapose! hb, rw [perm.mul_apply, perm.mul_apply, hb, apply_inv_self] } end lemma is_cycle.exists_gpow_eq {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.exists_pow_eq [fintype β] {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℕ, (f ^ i) x = y := let ⟨n, hn⟩ := hf.exists_gpow_eq hx hy in by classical; exact ⟨(n % order_of f).to_nat, by { have := n.mod_nonneg (int.coe_nat_ne_zero.mpr (ne_of_gt (order_of_pos f))), rwa [← gpow_coe_nat, int.to_nat_of_nonneg this, ← gpow_eq_mod_order_of] }⟩ lemma is_cycle.exists_pow_eq_one [fintype β] {f : perm β} (hf : is_cycle f) : ∃ (k : ℕ) (hk : 1 < k), f ^ k = 1 := begin classical, have : is_of_fin_order f := exists_pow_eq_one f, rw is_of_fin_order_iff_pow_eq_one at this, obtain ⟨x, hx, hx'⟩ := hf, obtain ⟨_ | _ | k, hk, hk'⟩ := this, { exact absurd hk (lt_asymm hk) }, { rw pow_one at hk', simpa [hk'] using hx }, { exact ⟨k + 2, by simp, hk'⟩ } end /-- The subgroup generated by a cycle is in bijection with its support -/ noncomputable def is_cycle.gpowers_equiv_support {σ : perm α} (hσ : is_cycle σ) : (↑(subgroup.gpowers σ) : set (perm α)) ≃ (↑(σ.support) : set α) := equiv.of_bijective (λ τ, ⟨τ (classical.some hσ), begin obtain ⟨τ, n, rfl⟩ := τ, rw [finset.mem_coe, coe_fn_coe_base, subtype.coe_mk, gpow_apply_mem_support, mem_support], exact (classical.some_spec hσ).1, end⟩) begin split, { rintros ⟨a, m, rfl⟩ ⟨b, n, rfl⟩ h, ext y, by_cases hy : σ y = y, { simp_rw [subtype.coe_mk, gpow_apply_eq_self_of_apply_eq_self hy] }, { obtain ⟨i, rfl⟩ := (classical.some_spec hσ).2 y hy, rw [subtype.coe_mk, subtype.coe_mk, gpow_apply_comm σ m i, gpow_apply_comm σ n i], exact congr_arg _ (subtype.ext_iff.mp h) } }, by { rintros ⟨y, hy⟩, rw [finset.mem_coe, mem_support] at hy, obtain ⟨n, rfl⟩ := (classical.some_spec hσ).2 y hy, exact ⟨⟨σ ^ n, n, rfl⟩, rfl⟩ }, end @[simp] lemma is_cycle.gpowers_equiv_support_apply {σ : perm α} (hσ : is_cycle σ) {n : ℕ} : hσ.gpowers_equiv_support ⟨σ ^ n, n, rfl⟩ = ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ := rfl @[simp] lemma is_cycle.gpowers_equiv_support_symm_apply {σ : perm α} (hσ : is_cycle σ) (n : ℕ) : hσ.gpowers_equiv_support.symm ⟨(σ ^ n) (classical.some hσ), pow_apply_mem_support.2 (mem_support.2 (classical.some_spec hσ).1)⟩ = ⟨σ ^ n, n, rfl⟩ := (equiv.symm_apply_eq _).2 hσ.gpowers_equiv_support_apply lemma order_of_is_cycle {σ : perm α} (hσ : is_cycle σ) : order_of σ = σ.support.card := begin rw [order_eq_card_gpowers, ←fintype.card_coe], convert fintype.card_congr (is_cycle.gpowers_equiv_support hσ), end lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (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, ← f.injective.eq_iff, 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₂ {α : Type*} [decidable_eq α] : ∀ (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 only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] 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_of_nat, ← 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 is_cycle.eq_swap_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {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 {α : Type*} [decidable_eq α] {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 [f.injective.eq_iff] at *; cc }, λ y hy, let ⟨i, hi⟩ := hf.exists_gpow_eq 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⟩ lemma is_cycle.sign : ∀ {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, begin rw hf.eq_swap_of_apply_apply_eq_self hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by { rw [sign_mul, sign_swap hx.1.symm, h, sign_one, hf.eq_swap_of_apply_apply_eq_self 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 _ _), sdiff_singleton_eq_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, (hf.swap_mul hx.1 h1).sign, ← h], simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true, pow_one, units.neg_mul_neg] } using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} lemma is_cycle_of_is_cycle_pow {σ : perm α} {n : ℕ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin have key : ∀ x : α, (σ ^ n) x ≠ x ↔ σ x ≠ x, { simp_rw [←mem_support], exact finset.ext_iff.mp (le_antisymm (support_pow_le σ n) h2) }, obtain ⟨x, hx1, hx2⟩ := h1, refine ⟨x, (key x).mp hx1, λ y hy, _⟩, cases (hx2 y ((key y).mpr hy)) with i _, exact ⟨n * i, by rwa gpow_mul⟩ end -- The lemma `support_gpow_le` is relevant. It means that `h2` is equivalent to -- `σ.support = (σ ^ n).support`, as well as to `σ.support.card ≤ (σ ^ n).support.card`. lemma is_cycle_of_is_cycle_gpow {σ : perm α} {n : ℤ} (h1 : is_cycle (σ ^ n)) (h2 : σ.support ≤ (σ ^ n).support) : is_cycle σ := begin cases n, { exact is_cycle_of_is_cycle_pow h1 h2 }, { simp only [le_eq_subset, gpow_neg_succ_of_nat, perm.support_inv] at h1 h2, simpa using is_cycle_of_is_cycle_pow h1.inv h2 } end lemma is_cycle.extend_domain {α : Type*} {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} (h : is_cycle g) : is_cycle (g.extend_domain f) := begin obtain ⟨a, ha, ha'⟩ := h, refine ⟨f a, _, λ b hb, _⟩, { rw extend_domain_apply_image, exact λ con, ha (f.injective (subtype.coe_injective con)) }, by_cases pb : p b, { obtain ⟨i, hi⟩ := ha' (f.symm ⟨b, pb⟩) (λ con, hb _), { refine ⟨i, _⟩, have hnat : ∀ (k : ℕ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k ih, { refl }, rw [pow_succ, perm.mul_apply, ih, extend_domain_apply_image, pow_succ, perm.mul_apply] }, have hint : ∀ (k : ℤ) (a : α), (g.extend_domain f ^ k) ↑(f a) = f ((g ^ k) a), { intros k a, induction k with k k, { rw [gpow_of_nat, gpow_of_nat, hnat] }, rw [gpow_neg_succ_of_nat, gpow_neg_succ_of_nat, inv_eq_iff_eq, hnat, apply_inv_self] }, rw [hint, hi, apply_symm_apply, subtype.coe_mk] }, { rw [extend_domain_apply_subtype _ _ pb, con, apply_symm_apply, subtype.coe_mk] } }, { exact (hb (extend_domain_apply_not_subtype _ _ pb)).elim } end lemma nodup_of_pairwise_disjoint_cycles {l : list (perm β)} (h1 : ∀ f ∈ l, is_cycle f) (h2 : l.pairwise disjoint) : l.nodup := nodup_of_pairwise_disjoint (λ h, (h1 1 h).ne_one rfl) h2 end sign_cycle /-! ### `same_cycle` -/ /-- The equivalence relation indicating that two points are in the same cycle of a permutation. -/ def same_cycle (f : perm β) (x y : β) : Prop := ∃ i : ℤ, (f ^ i) x = y @[refl] lemma same_cycle.refl (f : perm β) (x : β) : same_cycle f x x := ⟨0, rfl⟩ @[symm] lemma same_cycle.symm {f : perm β} {x y : β} : same_cycle f x y → same_cycle f y x := λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← hi, inv_apply_self]⟩ @[trans] lemma same_cycle.trans {f : perm β} {x y z : β} : same_cycle f x y → same_cycle f y z → same_cycle f x z := λ ⟨i, hi⟩ ⟨j, hj⟩, ⟨j + i, by rw [gpow_add, mul_apply, hi, hj]⟩ lemma same_cycle.apply_eq_self_iff {f : perm β} {x y : β} : same_cycle f x y → (f x = x ↔ f y = y) := λ ⟨i, hi⟩, by rw [← hi, ← mul_apply, ← gpow_one_add, add_comm, gpow_add_one, mul_apply, (f ^ i).injective.eq_iff] lemma is_cycle.same_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : same_cycle f x y := hf.exists_gpow_eq hx hy lemma same_cycle.nat' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (h : i < order_of f), (f ^ i) x = y := begin classical, obtain ⟨k, rfl⟩ := id h, by_cases hk : (k % order_of f) = 0, { use 0, rw ←int.dvd_iff_mod_eq_zero at hk, obtain ⟨m, rfl⟩ := hk, simp [pow_order_of_eq_one, order_of_pos, gpow_mul] }, { use ((k % order_of f).nat_abs), rw [←gpow_coe_nat, int.nat_abs_of_nonneg, ←gpow_eq_mod_order_of], { refine ⟨_, rfl⟩, rw [←int.coe_nat_lt, int.nat_abs_of_nonneg], { refine (int.mod_lt_of_pos _ _), simpa using order_of_pos _ }, { refine int.mod_nonneg _ _, simpa using ne_of_gt (order_of_pos _) } }, { refine int.mod_nonneg _ _, simpa using (order_of_pos _).ne' } } end lemma same_cycle.nat'' [fintype β] {f : perm β} {x y : β} (h : same_cycle f x y) : ∃ (i : ℕ) (hpos : 0 < i) (h : i ≤ order_of f), (f ^ i) x = y := begin classical, obtain ⟨_|i, hi, rfl⟩ := h.nat', { refine ⟨order_of f, order_of_pos f, le_rfl, _⟩, rw [pow_order_of_eq_one, pow_zero] }, { exact ⟨i.succ, i.zero_lt_succ, hi.le, rfl⟩ } end instance [fintype α] (f : perm α) : decidable_rel (same_cycle f) := λ x y, decidable_of_iff (∃ n ∈ list.range (fintype.card (perm α)), (f ^ n) x = y) ⟨λ ⟨n, _, hn⟩, ⟨n, hn⟩, λ ⟨i, hi⟩, ⟨(i % order_of f).nat_abs, list.mem_range.2 (int.coe_nat_lt.1 $ by { rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { apply lt_of_lt_of_le (int.mod_lt _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), { simp [order_of_le_card_univ] }, exact fintype_perm }, exact fintype_perm, }), by { rw [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of, hi], exact fintype_perm }⟩⟩ lemma same_cycle_apply {f : perm β} {x y : β} : same_cycle f x (f y) ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-1 + i, by rw [gpow_add, mul_apply, hi, gpow_neg_one, inv_apply_self]⟩, λ ⟨i, hi⟩, ⟨1 + i, by rw [gpow_add, mul_apply, hi, gpow_one]⟩⟩ lemma same_cycle_cycle {f : perm β} {x : β} (hx : f x ≠ x) : is_cycle f ↔ (∀ {y}, same_cycle f x y ↔ f y ≠ y) := ⟨λ hf y, ⟨λ ⟨i, hi⟩ hy, hx $ by { rw [← gpow_apply_eq_self_of_apply_eq_self hy i, (f ^ i).injective.eq_iff] at hi, rw [hi, hy] }, hf.exists_gpow_eq hx⟩, λ h, ⟨x, hx, λ y hy, h.2 hy⟩⟩ lemma same_cycle_inv (f : perm β) {x y : β} : same_cycle f⁻¹ x y ↔ same_cycle f x y := ⟨λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, hi]⟩, λ ⟨i, hi⟩, ⟨-i, by rw [gpow_neg, ← inv_gpow, inv_inv, hi]⟩ ⟩ lemma same_cycle_inv_apply {f : perm β} {x y : β} : same_cycle f x (f⁻¹ y) ↔ same_cycle f x y := by rw [← same_cycle_inv, same_cycle_apply, same_cycle_inv] @[simp] lemma same_cycle_pow_left_iff {f : perm β} {x y : β} {n : ℕ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin split, { rintro ⟨k, rfl⟩, use (k + n), simp [gpow_add] }, { rintro ⟨k, rfl⟩, use (k - n), rw [←gpow_coe_nat, ←mul_apply, ←gpow_add, int.sub_add_cancel] } end @[simp] lemma same_cycle_gpow_left_iff {f : perm β} {x y : β} {n : ℤ} : same_cycle f ((f ^ n) x) y ↔ same_cycle f x y := begin cases n, { exact same_cycle_pow_left_iff }, { rw [gpow_neg_succ_of_nat, ←inv_pow, ←same_cycle_inv, same_cycle_pow_left_iff, same_cycle_inv] } end /-- Unlike `support_congr`, which assumes that `∀ (x ∈ g.support), f x = g x)`, here we have the weaker assumption that `∀ (x ∈ f.support), f x = g x`. -/ lemma is_cycle.support_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : f.support ⊆ g.support) (h' : ∀ (x ∈ f.support), f x = g x) : f = g := begin have : f.support = g.support, { refine le_antisymm h _, intros z hz, obtain ⟨x, hx, hf'⟩ := id hf, have hx' : g x ≠ x, { rwa [←h' x (mem_support.mpr hx)] }, obtain ⟨m, hm⟩ := hg.exists_pow_eq hx' (mem_support.mp hz), have h'' : ∀ (x ∈ f.support ∩ g.support), f x = g x, { intros x hx, exact h' x (mem_of_mem_inter_left hx) }, rwa [←hm, ←pow_eq_on_of_mem_support h'' _ x (mem_inter_of_mem (mem_support.mpr hx) (mem_support.mpr hx')), pow_apply_mem_support, mem_support] }, refine support_congr h _, simpa [←this] using h' end /-- If two cyclic permutations agree on all terms in their intersection, and that intersection is not empty, then the two cyclic permutations must be equal. -/ lemma is_cycle.eq_on_support_inter_nonempty_congr [fintype α] {f g : perm α} (hf : is_cycle f) (hg : is_cycle g) (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) {x : α} (hx : f x = g x) (hx' : x ∈ f.support) : f = g := begin have hx'' : x ∈ g.support, { rwa [mem_support, ←hx, ←mem_support] }, have : f.support ⊆ g.support, { intros y hy, obtain ⟨k, rfl⟩ := hf.exists_pow_eq (mem_support.mp hx') (mem_support.mp hy), rwa [pow_eq_on_of_mem_support h _ _ (mem_inter_of_mem hx' hx''), pow_apply_mem_support] }, rw (inter_eq_left_iff_subset _ _).mpr this at h, exact hf.support_congr hg this h end lemma is_cycle.support_pow_eq_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : support (f ^ n) = support f ↔ ¬ order_of f ∣ n := begin rw order_of_dvd_iff_pow_eq_one, split, { intros h H, refine hf.ne_one _, rw [←support_eq_empty_iff, ←h, H, support_one] }, { intro H, apply le_antisymm (support_pow_le _ n) _, intros x hx, contrapose! H, ext z, by_cases hz : f z = z, { rw [pow_apply_eq_self_of_apply_eq_self hz, one_apply] }, { obtain ⟨k, rfl⟩ := hf.exists_pow_eq hz (mem_support.mp hx), apply (f ^ k).injective, rw [←mul_apply, (commute.pow_pow_self _ _ _).eq, mul_apply], simpa using H } } end lemma is_cycle.pow_iff [fintype β] {f : perm β} (hf : is_cycle f) {n : ℕ} : is_cycle (f ^ n) ↔ n.coprime (order_of f) := begin classical, split, { intro h, have hr : support (f ^ n) = support f, { rw hf.support_pow_eq_iff, rintro ⟨k, rfl⟩, refine h.ne_one _, simp [pow_mul, pow_order_of_eq_one] }, have : order_of (f ^ n) = order_of f, { rw [order_of_is_cycle h, hr, order_of_is_cycle hf] }, rw [order_of_pow, nat.div_eq_self] at this, cases this, { exact absurd this (order_of_pos _).ne' }, { rwa [nat.coprime_iff_gcd_eq_one, nat.gcd_comm] } }, { intro h, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime h, have hf' : is_cycle ((f ^ n) ^ m) := by rwa hm, refine is_cycle_of_is_cycle_pow hf' _, intros x hx, rw [hm], exact support_pow_le _ n hx } end lemma is_cycle.pow_eq_one_iff [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} : f ^ n = 1 ↔ ∃ (x ∈ f.support), (f ^ n) x = x := begin split, { intro h, obtain ⟨x, hx, -⟩ := id hf, exact ⟨x, mem_support.mpr hx, by simp [h]⟩ }, { rintro ⟨x, hx, hx'⟩, by_cases h : support (f ^ n) = support f, { rw [←h, mem_support] at hx, contradiction }, { rw [hf.support_pow_eq_iff, not_not] at h, obtain ⟨k, rfl⟩ := h, rw [pow_mul, pow_order_of_eq_one, one_pow] } } end lemma is_cycle.mem_support_pos_pow_iff_of_lt_order_of [fintype α] {f : perm α} (hf : is_cycle f) {n : ℕ} (npos : 0 < n) (hn : n < order_of f) {x : α} : x ∈ (f ^ n).support ↔ x ∈ f.support := begin have : ¬ order_of f ∣ n := nat.not_dvd_of_pos_of_lt npos hn, rw ←hf.support_pow_eq_iff at this, rw this end lemma is_cycle.is_cycle_pow_pos_of_lt_prime_order [fintype β] {f : perm β} (hf : is_cycle f) (hf' : (order_of f).prime) (n : ℕ) (hn : 0 < n) (hn' : n < order_of f) : is_cycle (f ^ n) := begin classical, have : n.coprime (order_of f), { refine nat.coprime.symm _, rw nat.prime.coprime_iff_not_dvd hf', exact nat.not_dvd_of_pos_of_lt hn hn' }, obtain ⟨m, hm⟩ := exists_pow_eq_self_of_coprime this, have hf'' := hf, rw ←hm at hf'', refine is_cycle_of_is_cycle_pow hf'' _, rw [hm], exact support_pow_le f n end /-! ### `cycle_of` -/ /-- `f.cycle_of x` is the cycle of the permutation `f` to which `x` belongs. -/ def cycle_of [fintype α] (f : perm α) (x : α) : perm α := of_subtype (@subtype_perm _ f (same_cycle f x) (λ _, same_cycle_apply.symm)) lemma cycle_of_apply [fintype α] (f : perm α) (x y : α) : cycle_of f x y = if same_cycle f x y then f y else y := rfl lemma cycle_of_inv [fintype α] (f : perm α) (x : α) : (cycle_of f x)⁻¹ = cycle_of f⁻¹ x := equiv.ext $ λ y, begin rw [inv_eq_iff_eq, cycle_of_apply, cycle_of_apply], split_ifs; simp [*, same_cycle_inv, same_cycle_inv_apply] at * end @[simp] lemma cycle_of_pow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℕ, (cycle_of f x ^ n) x = (f ^ n) x | 0 := rfl | (n+1) := by { rw [pow_succ, mul_apply, cycle_of_apply, cycle_of_pow_apply_self, if_pos, pow_succ, mul_apply], exact ⟨n, rfl⟩ } @[simp] lemma cycle_of_gpow_apply_self [fintype α] (f : perm α) (x : α) : ∀ n : ℤ, (cycle_of f x ^ n) x = (f ^ n) x | (n : ℕ) := cycle_of_pow_apply_self f x n | -[1+ n] := by rw [gpow_neg_succ_of_nat, ← inv_pow, cycle_of_inv, gpow_neg_succ_of_nat, ← inv_pow, cycle_of_pow_apply_self] lemma same_cycle.cycle_of_apply [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x y = f y := dif_pos h lemma cycle_of_apply_of_not_same_cycle [fintype α] {f : perm α} {x y : α} (h : ¬same_cycle f x y) : cycle_of f x y = y := dif_neg h lemma same_cycle.cycle_of_eq [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : cycle_of f x = cycle_of f y := begin ext z, rw cycle_of_apply, split_ifs with hz hz, { exact (h.symm.trans hz).cycle_of_apply.symm }, { exact (cycle_of_apply_of_not_same_cycle (mt h.trans hz)).symm } end @[simp] lemma cycle_of_apply_apply_gpow_self [fintype α] (f : perm α) (x : α) (k : ℤ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := begin rw same_cycle.cycle_of_apply, { rw [add_comm, gpow_add, gpow_one, mul_apply] }, { exact ⟨k, rfl⟩ } end @[simp] lemma cycle_of_apply_apply_pow_self [fintype α] (f : perm α) (x : α) (k : ℕ) : cycle_of f x ((f ^ k) x) = (f ^ (k + 1)) x := by convert cycle_of_apply_apply_gpow_self f x k using 1 @[simp] lemma cycle_of_apply_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x (f x) = f (f x) := by convert cycle_of_apply_apply_pow_self f x 1 using 1 @[simp] lemma cycle_of_apply_self [fintype α] (f : perm α) (x : α) : cycle_of f x x = f x := (same_cycle.refl _ _).cycle_of_apply lemma is_cycle.cycle_of_eq [fintype α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) : cycle_of f x = f := equiv.ext $ λ y, if h : same_cycle f x y then by rw [h.cycle_of_apply] else by rw [cycle_of_apply_of_not_same_cycle h, not_not.1 (mt ((same_cycle_cycle hx).1 hf).2 h)] @[simp] lemma cycle_of_eq_one_iff [fintype α] (f : perm α) {x : α} : cycle_of f x = 1 ↔ f x = x := begin simp_rw [ext_iff, cycle_of_apply, one_apply], refine ⟨λ h, (if_pos (same_cycle.refl f x)).symm.trans (h x), λ h y, _⟩, by_cases hy : f y = y, { rw [hy, if_t_t] }, { exact if_neg (mt same_cycle.apply_eq_self_iff (by tauto)) }, end @[simp] lemma cycle_of_self_apply [fintype α] (f : perm α) (x : α) : cycle_of f (f x) = cycle_of f x := (same_cycle_apply.mpr (same_cycle.refl _ _)).symm.cycle_of_eq @[simp] lemma cycle_of_self_apply_pow [fintype α] (f : perm α) (n : ℕ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_pow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq @[simp] lemma cycle_of_self_apply_gpow [fintype α] (f : perm α) (n : ℤ) (x : α) : cycle_of f ((f ^ n) x) = cycle_of f x := (same_cycle_gpow_left_iff.mpr (same_cycle.refl _ _)).cycle_of_eq lemma is_cycle.cycle_of [fintype α] {f : perm α} (hf : is_cycle f) {x : α} : cycle_of f x = if f x = x then 1 else f := begin by_cases hx : f x = x, { rwa [if_pos hx, cycle_of_eq_one_iff] }, { rwa [if_neg hx, hf.cycle_of_eq] }, end lemma cycle_of_one [fintype α] (x : α) : cycle_of 1 x = 1 := (cycle_of_eq_one_iff 1).mpr rfl lemma is_cycle_cycle_of [fintype α] (f : perm α) {x : α} (hx : f x ≠ x) : is_cycle (cycle_of f x) := have cycle_of f x x ≠ x, by rwa [(same_cycle.refl _ _).cycle_of_apply], (same_cycle_cycle this).2 $ λ y, ⟨λ h, mt h.apply_eq_self_iff.2 this, λ h, if hxy : same_cycle f x y then let ⟨i, hi⟩ := hxy in ⟨i, by rw [cycle_of_gpow_apply_self, hi]⟩ else by { rw [cycle_of_apply_of_not_same_cycle hxy] at h, exact (h rfl).elim }⟩ @[simp] lemma two_le_card_support_cycle_of_iff [fintype α] {f : perm α} {x : α} : 2 ≤ card (cycle_of f x).support ↔ f x ≠ x := begin refine ⟨λ h, _, λ h, by simpa using (is_cycle_cycle_of _ h).two_le_card_support⟩, contrapose! h, rw ←cycle_of_eq_one_iff at h, simp [h] end @[simp] lemma card_support_cycle_of_pos_iff [fintype α] {f : perm α} {x : α} : 0 < card (cycle_of f x).support ↔ f x ≠ x := begin rw [←two_le_card_support_cycle_of_iff, ←nat.succ_le_iff], exact ⟨λ h, or.resolve_left h.eq_or_lt (card_support_ne_one _).symm, zero_lt_two.trans_le⟩ end lemma pow_apply_eq_pow_mod_order_of_cycle_of_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ n) x = (f ^ (n % order_of (cycle_of f x))) x := by rw [←cycle_of_pow_apply_self f, ←cycle_of_pow_apply_self f, pow_eq_mod_order_of] lemma cycle_of_mul_of_apply_right_eq_self [fintype α] {f g : perm α} (h : _root_.commute f g) (x : α) (hx : g x = x) : (f * g).cycle_of x = f.cycle_of x := begin ext y, by_cases hxy : (f * g).same_cycle x y, { obtain ⟨z, rfl⟩ := hxy, rw cycle_of_apply_apply_gpow_self, simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] }, { rw [cycle_of_apply_of_not_same_cycle hxy, cycle_of_apply_of_not_same_cycle], contrapose! hxy, obtain ⟨z, rfl⟩ := hxy, refine ⟨z, _⟩, simp [h.mul_gpow, gpow_apply_eq_self_of_apply_eq_self hx] } end lemma disjoint.cycle_of_mul_distrib [fintype α] {f g : perm α} (h : f.disjoint g) (x : α) : (f * g).cycle_of x = (f.cycle_of x * g.cycle_of x) := begin cases (disjoint_iff_eq_or_eq.mp h) x with hfx hgx, { simp [h.commute.eq, cycle_of_mul_of_apply_right_eq_self h.symm.commute, hfx] }, { simp [cycle_of_mul_of_apply_right_eq_self h.commute, hgx] } end lemma support_cycle_of_eq_nil_iff [fintype α] {f : perm α} {x : α} : (f.cycle_of x).support = ∅ ↔ x ∉ f.support := by simp lemma support_cycle_of_le [fintype α] (f : perm α) (x : α) : support (f.cycle_of x) ≤ support f := begin intros y hy, rw [mem_support, cycle_of_apply] at hy, split_ifs at hy, { exact mem_support.mpr hy }, { exact absurd rfl hy } end lemma mem_support_cycle_of_iff [fintype α] {f : perm α} {x y : α} : y ∈ support (f.cycle_of x) ↔ same_cycle f x y ∧ x ∈ support f := begin by_cases hx : f x = x, { rw (cycle_of_eq_one_iff _).mpr hx, simp [hx] }, { rw [mem_support, cycle_of_apply], split_ifs with hy, { simp only [hx, hy, iff_true, ne.def, not_false_iff, and_self, mem_support], rcases hy with ⟨k, rfl⟩, rw ←not_mem_support, simpa using hx }, { simpa [hx] using hy } } end lemma same_cycle.mem_support_iff [fintype α] {f : perm α} {x y : α} (h : same_cycle f x y) : x ∈ support f ↔ y ∈ support f := ⟨λ hx, support_cycle_of_le f x (mem_support_cycle_of_iff.mpr ⟨h, hx⟩), λ hy, support_cycle_of_le f y (mem_support_cycle_of_iff.mpr ⟨h.symm, hy⟩)⟩ lemma pow_mod_card_support_cycle_of_self_apply [fintype α] (f : perm α) (n : ℕ) (x : α) : (f ^ (n % (f.cycle_of x).support.card)) x = (f ^ n) x := begin by_cases hx : f x = x, { rw [pow_apply_eq_self_of_apply_eq_self hx, pow_apply_eq_self_of_apply_eq_self hx] }, { rw [←cycle_of_pow_apply_self, ←cycle_of_pow_apply_self f, ←order_of_is_cycle (is_cycle_cycle_of f hx), ←pow_eq_mod_order_of] } end /-! ### `cycle_factors` -/ /-- Given a list `l : list α` and a permutation `f : perm α` whose nonfixed points are all in `l`, recursively factors `f` into cycles. -/ def cycle_factors_aux [fintype α] : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} | [] f h := ⟨[], by { simp only [imp_false, list.pairwise.nil, list.not_mem_nil, forall_const, and_true, forall_prop_of_false, not_not, not_false_iff, list.prod_nil] at *, ext, simp * }⟩ | (x::l) f h := if hx : f x = x then cycle_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h, hy (by rwa h)) (h hy)) else let ⟨m, hm₁, hm₂, hm₃⟩ := cycle_factors_aux l ((cycle_of f x)⁻¹ * f) (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by { rw [h, mul_apply, ne.def, inv_eq_iff_eq, cycle_of_apply_self] at hy, exact hy rfl }) (h (λ h : f y = y, by { rw [mul_apply, h, ne.def, inv_eq_iff_eq, cycle_of_apply] at hy, split_ifs at hy; cc }))) in ⟨(cycle_of f x) :: m, by { rw [list.prod_cons, hm₁], simp }, λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ hg, hg.symm ▸ is_cycle_cycle_of _ hx) (hm₂ g), list.pairwise_cons.2 ⟨λ g hg y, or_iff_not_imp_left.2 (λ hfy, have hxy : same_cycle f x y := not_not.1 (mt cycle_of_apply_of_not_same_cycle hfy), have hgm : g :: m.erase g ~ m := list.cons_perm_iff_perm_erase.2 ⟨hg, list.perm.refl _⟩, have ∀ h ∈ m.erase g, disjoint g h, from (list.pairwise_cons.1 ((hgm.pairwise_iff (λ a b (h : disjoint a b), h.symm)).2 hm₃)).1, classical.by_cases id $ λ hgy : g y ≠ y, (disjoint_prod_right _ this y).resolve_right $ have hsc : same_cycle f⁻¹ x (f y), by rwa [same_cycle_inv, same_cycle_apply], by { rw [disjoint_prod_perm hm₃ hgm.symm, list.prod_cons, ← eq_inv_mul_iff_mul_eq] at hm₁, rwa [hm₁, mul_apply, mul_apply, cycle_of_inv, hsc.cycle_of_apply, inv_apply_self, inv_eq_iff_eq, eq_comm] }), hm₃⟩⟩ lemma mem_list_cycles_iff {α : Type*} [fintype α] {l : list (perm α)} (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) {σ : perm α} : σ ∈ l ↔ σ.is_cycle ∧ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a := begin suffices : σ.is_cycle → (σ ∈ l ↔ ∀ (a : α) (h4 : σ a ≠ a), σ a = l.prod a), { exact ⟨λ hσ, ⟨h1 σ hσ, (this (h1 σ hσ)).mp hσ⟩, λ hσ, (this hσ.1).mpr hσ.2⟩ }, intro h3, classical, split, { intros h a ha, exact eq_on_support_mem_disjoint h h2 _ (mem_support.mpr ha) }, { intros h, have hσl : σ.support ⊆ l.prod.support, { intros x hx, rw mem_support at hx, rwa [mem_support, ←h _ hx] }, obtain ⟨a, ha, -⟩ := id h3, rw ←mem_support at ha, obtain ⟨τ, hτ, hτa⟩ := exists_mem_support_of_mem_support_prod (hσl ha), have hτl : ∀ (x ∈ τ.support), τ x = l.prod x := eq_on_support_mem_disjoint hτ h2, have key : ∀ (x ∈ σ.support ∩ τ.support), σ x = τ x, { intros x hx, rw [h x (mem_support.mp (mem_of_mem_inter_left hx)), hτl x (mem_of_mem_inter_right hx)] }, convert hτ, refine h3.eq_on_support_inter_nonempty_congr (h1 _ hτ) key _ ha, exact key a (mem_inter_of_mem ha hτa) } end lemma list_cycles_perm_list_cycles {α : Type*} [fintype α] {l₁ l₂ : list (perm α)} (h₀ : l₁.prod = l₂.prod) (h₁l₁ : ∀ σ : perm α, σ ∈ l₁ → σ.is_cycle) (h₁l₂ : ∀ σ : perm α, σ ∈ l₂ → σ.is_cycle) (h₂l₁ : l₁.pairwise disjoint) (h₂l₂ : l₂.pairwise disjoint) : l₁ ~ l₂ := begin classical, refine (list.perm_ext (nodup_of_pairwise_disjoint_cycles h₁l₁ h₂l₁) (nodup_of_pairwise_disjoint_cycles h₁l₂ h₂l₂)).mpr (λ σ, _), by_cases hσ : σ.is_cycle, { obtain ⟨a, ha⟩ := not_forall.mp (mt ext hσ.ne_one), rw [mem_list_cycles_iff h₁l₁ h₂l₁, mem_list_cycles_iff h₁l₂ h₂l₂, h₀] }, { exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ) } end /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := cycle_factors_aux (univ.sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- Factors a permutation `f` into a list of disjoint cyclic permutations that multiply to `f`, without a linear order. -/ def trunc_cycle_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (cycle_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) section cycle_factors_finset variables [fintype α] (f : perm α) /-- Factors a permutation `f` into a `finset` of disjoint cyclic permutations that multiply to `f`. -/ def cycle_factors_finset : finset (perm α) := (trunc_cycle_factors f).lift (λ (l : {l : list (perm α) // l.prod = f ∧ (∀ g ∈ l, is_cycle g) ∧ l.pairwise disjoint}), l.val.to_finset) (λ ⟨l, hl⟩ ⟨l', hl'⟩, list.to_finset_eq_of_perm _ _ (list_cycles_perm_list_cycles (hl'.left.symm ▸ hl.left) hl.right.left (hl'.right.left) hl.right.right hl'.right.right)) lemma cycle_factors_finset_eq_list_to_finset {σ : perm α} {l : list (perm α)} (hn : l.nodup) : σ.cycle_factors_finset = l.to_finset ↔ (∀ f : perm α, f ∈ l → f.is_cycle) ∧ l.pairwise disjoint ∧ l.prod = σ := begin obtain ⟨⟨l', hp', hc', hd'⟩, hl⟩ := trunc.exists_rep σ.trunc_cycle_factors, have ht : cycle_factors_finset σ = l'.to_finset, { rw [cycle_factors_finset, ←hl, trunc.lift_mk] }, rw ht, split, { intro h, have hn' : l'.nodup := nodup_of_pairwise_disjoint_cycles hc' hd', have hperm : l ~ l' := list.perm_of_nodup_nodup_to_finset_eq hn hn' h.symm, refine ⟨_, _, _⟩, { exact λ _ h, hc' _ (hperm.subset h)}, { rwa list.perm.pairwise_iff disjoint.symmetric hperm }, { rw [←hp', hperm.symm.prod_eq'], refine hd'.imp _, exact λ _ _, disjoint.commute } }, { rintro ⟨hc, hd, hp⟩, refine list.to_finset_eq_of_perm _ _ _, refine list_cycles_perm_list_cycles _ hc' hc hd' hd, rw [hp, hp'] } end lemma cycle_factors_finset_eq_finset {σ : perm α} {s : finset (perm α)} : σ.cycle_factors_finset = s ↔ (∀ f : perm α, f ∈ s → f.is_cycle) ∧ (∃ h : (∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b), s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise_on.mono' (λ _ _, disjoint.commute) h a ha b hb)) = σ) := begin obtain ⟨l, hl, rfl⟩ := s.exists_list_nodup_eq, rw cycle_factors_finset_eq_list_to_finset hl, simp only [noncomm_prod_to_finset, hl, exists_prop, list.mem_to_finset, and.congr_left_iff, and.congr_right_iff, list.map_id, ne.def], intros, exact ⟨list.forall_of_pairwise disjoint.symmetric, hl.pairwise_of_forall_ne⟩ end lemma cycle_factors_finset_pairwise_disjoint (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) (h : p ≠ q) : disjoint p q := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, -⟩ := cycle_factors_finset_eq_finset.mp this, exact hd p hp q hq h end lemma cycle_factors_finset_mem_commute (p : perm α) (hp : p ∈ cycle_factors_finset f) (q : perm α) (hq : q ∈ cycle_factors_finset f) : _root_.commute p q := begin by_cases h : p = q, { exact h ▸ commute.refl _ }, { exact (cycle_factors_finset_pairwise_disjoint _ _ hp _ hq h).commute } end /-- The product of cycle factors is equal to the original `f : perm α`. -/ lemma cycle_factors_finset_noncomm_prod (comm : ∀ (g ∈ f.cycle_factors_finset) (h ∈ f.cycle_factors_finset), commute (id g) (id h) := cycle_factors_finset_mem_commute f) : f.cycle_factors_finset.noncomm_prod id (comm) = f := begin have : f.cycle_factors_finset = f.cycle_factors_finset := rfl, obtain ⟨-, hd, hp⟩ := cycle_factors_finset_eq_finset.mp this, exact hp end lemma mem_cycle_factors_finset_iff {f p : perm α} : p ∈ cycle_factors_finset f ↔ p.is_cycle ∧ ∀ (a ∈ p.support), p a = f a := begin obtain ⟨l, hl, hl'⟩ := f.cycle_factors_finset.exists_list_nodup_eq, rw ←hl', rw [eq_comm, cycle_factors_finset_eq_list_to_finset hl] at hl', simpa [list.mem_to_finset, ne.def, ←hl'.right.right] using mem_list_cycles_iff hl'.left hl'.right.left end lemma cycle_of_mem_cycle_factors_finset_iff {f : perm α} {x : α} : cycle_of f x ∈ cycle_factors_finset f ↔ x ∈ f.support := begin rw mem_cycle_factors_finset_iff, split, { rintro ⟨hc, h⟩, contrapose! hc, rw [not_mem_support, ←cycle_of_eq_one_iff] at hc, simp [hc] }, { intros hx, refine ⟨is_cycle_cycle_of _ (mem_support.mp hx), _⟩, intros y hy, rw mem_support at hy, rw cycle_of_apply, split_ifs with H, { refl }, { rw cycle_of_apply_of_not_same_cycle H at hy, contradiction } } end lemma mem_cycle_factors_finset_support_le {p f : perm α} (h : p ∈ cycle_factors_finset f) : p.support ≤ f.support := begin rw mem_cycle_factors_finset_iff at h, intros x hx, rwa [mem_support, ←h.right x hx, ←mem_support] end lemma cycle_factors_finset_eq_empty_iff {f : perm α} : cycle_factors_finset f = ∅ ↔ f = 1 := by simpa [cycle_factors_finset_eq_finset] using eq_comm @[simp] lemma cycle_factors_finset_one : cycle_factors_finset (1 : perm α) = ∅ := by simp [cycle_factors_finset_eq_empty_iff] @[simp] lemma cycle_factors_finset_eq_singleton_self_iff {f : perm α} : f.cycle_factors_finset = {f} ↔ f.is_cycle := by simp [cycle_factors_finset_eq_finset] lemma is_cycle.cycle_factors_finset_eq_singleton {f : perm α} (hf : is_cycle f) : f.cycle_factors_finset = {f} := cycle_factors_finset_eq_singleton_self_iff.mpr hf lemma cycle_factors_finset_eq_singleton_iff {f g : perm α} : f.cycle_factors_finset = {g} ↔ f.is_cycle ∧ f = g := begin suffices : f = g → (g.is_cycle ↔ f.is_cycle), { simpa [cycle_factors_finset_eq_finset, eq_comm] }, rintro rfl, exact iff.rfl end /-- Two permutations `f g : perm α` have the same cycle factors iff they are the same. -/ lemma cycle_factors_finset_injective : function.injective (@cycle_factors_finset α _ _) := begin intros f g h, rw ←cycle_factors_finset_noncomm_prod f, simpa [h] using cycle_factors_finset_noncomm_prod g end lemma disjoint.disjoint_cycle_factors_finset {f g : perm α} (h : disjoint f g) : _root_.disjoint (cycle_factors_finset f) (cycle_factors_finset g) := begin rw disjoint_iff_disjoint_support at h, intros x hx, simp only [mem_cycle_factors_finset_iff, inf_eq_inter, mem_inter, mem_support] at hx, obtain ⟨⟨⟨a, ha, -⟩, hf⟩, -, hg⟩ := hx, refine h (_ : a ∈ f.support ∩ g.support), simp [ha, ←hf a ha, ←hg a ha] end lemma disjoint.cycle_factors_finset_mul_eq_union {f g : perm α} (h : disjoint f g) : cycle_factors_finset (f * g) = cycle_factors_finset f ∪ cycle_factors_finset g := begin rw cycle_factors_finset_eq_finset, split, { simp only [mem_cycle_factors_finset_iff, mem_union], rintro _ (⟨h, -⟩ | ⟨h, -⟩); exact h }, { refine ⟨_, _⟩, { simp_rw mem_union, rintros x (hx | hx) y (hy | hy) hxy, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy }, { exact h.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact h.symm.mono (mem_cycle_factors_finset_support_le hx) (mem_cycle_factors_finset_support_le hy) }, { exact cycle_factors_finset_pairwise_disjoint _ _ hx _ hy hxy } }, { rw noncomm_prod_union_of_disjoint h.disjoint_cycle_factors_finset, rw [cycle_factors_finset_noncomm_prod, cycle_factors_finset_noncomm_prod] } } end lemma disjoint_mul_inv_of_mem_cycle_factors_finset {f g : perm α} (h : f ∈ cycle_factors_finset g) : disjoint (g * f⁻¹) f := begin rw mem_cycle_factors_finset_iff at h, intro x, by_cases hx : f x = x, { exact or.inr hx }, { refine or.inl _, rw [mul_apply, ←h.right, apply_inv_self], rwa [←support_inv, apply_mem_support, support_inv, mem_support] } end end cycle_factors_finset @[elab_as_eliminator] lemma cycle_induction_on [fintype β] (P : perm β → Prop) (σ : perm β) (base_one : P 1) (base_cycles : ∀ σ : perm β, σ.is_cycle → P σ) (induction_disjoint : ∀ σ τ : perm β, disjoint σ τ → is_cycle σ → P σ → P τ → P (σ * τ)) : P σ := begin suffices : ∀ l : list (perm β), (∀ τ : perm β, τ ∈ l → τ.is_cycle) → l.pairwise disjoint → P l.prod, { classical, let x := σ.trunc_cycle_factors.out, exact (congr_arg P x.2.1).mp (this x.1 x.2.2.1 x.2.2.2) }, intro l, induction l with σ l ih, { exact λ _ _, base_one }, { intros h1 h2, rw list.prod_cons, exact induction_disjoint σ l.prod (disjoint_prod_right _ (list.pairwise_cons.mp h2).1) (h1 _ (list.mem_cons_self _ _)) (base_cycles σ (h1 σ (l.mem_cons_self σ))) (ih (λ τ hτ, h1 τ (list.mem_cons_of_mem σ hτ)) (list.pairwise_of_pairwise_cons h2)) }, end lemma cycle_factors_finset_mul_inv_mem_eq_sdiff [fintype α] {f g : perm α} (h : f ∈ cycle_factors_finset g) : cycle_factors_finset (g * f⁻¹) = (cycle_factors_finset g) \ {f} := begin revert f, apply cycle_induction_on _ g, { simp }, { intros σ hσ f hf, simp only [cycle_factors_finset_eq_singleton_self_iff.mpr hσ, mem_singleton] at hf ⊢, simp [hf] }, { intros σ τ hd hc hσ hτ f, simp_rw [hd.cycle_factors_finset_mul_eq_union, mem_union], -- if only `wlog` could work here... rintro (hf | hf), { rw [hd.commute.eq, union_comm, union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hσ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd.symm x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem hf H) } }, { rw [union_sdiff_distrib, sdiff_singleton_eq_erase, erase_eq_of_not_mem, mul_assoc, disjoint.cycle_factors_finset_mul_eq_union, hτ hf], { rw mem_cycle_factors_finset_iff at hf, intro x, cases hd x with hx hx, { exact or.inl hx }, { refine or.inr _, by_cases hfx : f x = x, { rw ←hfx, simpa [hx] using hfx.symm }, { rw mul_apply, rw ←hf.right _ (mem_support.mpr hfx) at hx, contradiction } } }, { exact λ H, hd.disjoint_cycle_factors_finset (mem_inter_of_mem H hf) } } } end lemma same_cycle.nat_of_mem_support [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) (hx : x ∈ f.support) : ∃ (i : ℕ) (hi' : i < (f.cycle_of x).support.card), (f ^ i) x = y := begin revert f, intro f, apply cycle_induction_on _ f, { simp }, { intros g hg H hx, rw mem_support at hx, rw [hg.cycle_of_eq hx, ←order_of_is_cycle hg], exact H.nat' }, { rintros g h hd hg IH IH' ⟨m, rfl⟩ hx, cases (disjoint_iff_eq_or_eq.mp hd) x with hgx hhx, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (h ^ k) x, { intro k, suffices : (g ^ k) x = x, { simpa [hd.commute.eq, hd.commute.symm.mul_gpow] }, rw gpow_apply_eq_self_of_apply_eq_self, simpa using hgx }, obtain ⟨k, hk, hk'⟩ := IH' _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hgx, rwa [hd.cycle_of_mul_distrib, hgx, one_mul] }, { simpa [←gpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { rw [mem_support, hd.commute.eq] at hx, simpa [hgx] using hx } }, { have hpow : ∀ (k : ℤ), ((g * h) ^ k) x = (g ^ k) x, { intro k, suffices : (h ^ k) x = x, { simpa [hd.commute.mul_gpow] }, rw gpow_apply_eq_self_of_apply_eq_self, simpa using hhx }, obtain ⟨k, hk, hk'⟩ := IH _ _, { refine ⟨k, _, _⟩, { rw [←cycle_of_eq_one_iff] at hhx, rwa [hd.cycle_of_mul_distrib, hhx, mul_one] }, { simpa [←gpow_coe_nat, hpow] using hk' } }, { use m, simp [hpow] }, { simpa [hhx] using hx } } } end lemma same_cycle.nat [fintype α] (f : perm α) {x y : α} (h : same_cycle f x y) : ∃ (i : ℕ) (hi : 0 < i) (hi' : i ≤ (f.cycle_of x).support.card + 1), (f ^ i) x = y := begin by_cases hx : x ∈ f.support, { obtain ⟨k, hk, hk'⟩ := same_cycle.nat_of_mem_support f h hx, cases k, { refine ⟨(f.cycle_of x).support.card, _, self_le_add_right _ _, _⟩, { refine zero_lt_one.trans (one_lt_card_support_of_ne_one _), simpa using hx }, { simp only [perm.coe_one, id.def, pow_zero] at hk', subst hk', rw [←order_of_is_cycle (is_cycle_cycle_of _ (mem_support.mp hx)), ←cycle_of_pow_apply_self, pow_order_of_eq_one, one_apply] } }, { exact ⟨k + 1, by simp, nat.le_succ_of_le hk.le, hk'⟩ } }, { refine ⟨1, zero_lt_one, by simp, _⟩, obtain ⟨k, rfl⟩ := h, rw [not_mem_support] at hx, rw [pow_apply_eq_self_of_apply_eq_self hx, gpow_apply_eq_self_of_apply_eq_self hx] } end section generation variables [fintype α] [fintype β] open subgroup lemma closure_is_cycle : closure {σ : perm β | is_cycle σ} = ⊤ := begin classical, exact top_le_iff.mp (le_trans (ge_of_eq closure_is_swap) (closure_mono (λ _, is_swap.is_cycle))), end lemma closure_cycle_adjacent_swap {σ : perm α} (h1 : is_cycle σ) (h2 : σ.support = ⊤) (x : α) : closure ({σ, swap x (σ x)} : set (perm α)) = ⊤ := begin let H := closure ({σ, swap x (σ x)} : set (perm α)), have h3 : σ ∈ H := subset_closure (set.mem_insert σ _), have h4 : swap x (σ x) ∈ H := subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)), have step1 : ∀ (n : ℕ), swap ((σ ^ n) x) ((σ^(n+1)) x) ∈ H, { intro n, induction n with n ih, { exact subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)) }, { convert H.mul_mem (H.mul_mem h3 ih) (H.inv_mem h3), rw [mul_swap_eq_swap_mul, mul_inv_cancel_right], refl } }, have step2 : ∀ (n : ℕ), swap x ((σ ^ n) x) ∈ H, { intro n, induction n with n ih, { convert H.one_mem, exact swap_self x }, { by_cases h5 : x = (σ ^ n) x, { rw [pow_succ, mul_apply, ←h5], exact h4 }, by_cases h6 : x = (σ^(n+1)) x, { rw [←h6, swap_self], exact H.one_mem }, rw [swap_comm, ←swap_mul_swap_mul_swap h5 h6], exact H.mul_mem (H.mul_mem (step1 n) ih) (step1 n) } }, have step3 : ∀ (y : α), swap x y ∈ H, { intro y, have hx : x ∈ (⊤ : finset α) := finset.mem_univ x, rw [←h2, mem_support] at hx, have hy : y ∈ (⊤ : finset α) := finset.mem_univ y, rw [←h2, mem_support] at hy, cases is_cycle.exists_pow_eq h1 hx hy with n hn, rw ← hn, exact step2 n }, have step4 : ∀ (y z : α), swap y z ∈ H, { intros y z, by_cases h5 : z = x, { rw [h5, swap_comm], exact step3 y }, by_cases h6 : z = y, { rw [h6, swap_self], exact H.one_mem }, rw [←swap_mul_swap_mul_swap h5 h6, swap_comm z x], exact H.mul_mem (H.mul_mem (step3 y) (step3 z)) (step3 y) }, rw [eq_top_iff, ←closure_is_swap, closure_le], rintros τ ⟨y, z, h5, h6⟩, rw h6, exact step4 y z, end lemma closure_cycle_coprime_swap {n : ℕ} {σ : perm α} (h0 : nat.coprime n (fintype.card α)) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (x : α) : closure ({σ, swap x ((σ ^ n) x)} : set (perm α)) = ⊤ := begin rw [←finset.card_univ, ←h2, ←order_of_is_cycle h1] at h0, cases exists_pow_eq_self_of_coprime h0 with m hm, have h2' : (σ ^ n).support = ⊤ := eq.trans (support_pow_coprime h0) h2, have h1' : is_cycle ((σ ^ n) ^ (m : ℤ)) := by rwa ← hm at h1, replace h1' : is_cycle (σ ^ n) := is_cycle_of_is_cycle_pow h1' (le_trans (support_pow_le σ n) (ge_of_eq (congr_arg support hm))), rw [eq_top_iff, ←closure_cycle_adjacent_swap h1' h2' x, closure_le, set.insert_subset], exact ⟨subgroup.pow_mem (closure _) (subset_closure (set.mem_insert σ _)) n, set.singleton_subset_iff.mpr (subset_closure (set.mem_insert_of_mem _ (set.mem_singleton _)))⟩, end lemma closure_prime_cycle_swap {σ τ : perm α} (h0 : (fintype.card α).prime) (h1 : is_cycle σ) (h2 : σ.support = finset.univ) (h3 : is_swap τ) : closure ({σ, τ} : set (perm α)) = ⊤ := begin obtain ⟨x, y, h4, h5⟩ := h3, obtain ⟨i, hi⟩ := h1.exists_pow_eq (mem_support.mp ((finset.ext_iff.mp h2 x).mpr (finset.mem_univ x))) (mem_support.mp ((finset.ext_iff.mp h2 y).mpr (finset.mem_univ y))), rw [h5, ←hi], refine closure_cycle_coprime_swap (nat.coprime.symm (h0.coprime_iff_not_dvd.mpr (λ h, h4 _))) h1 h2 x, cases h with m hm, rwa [hm, pow_mul, ←finset.card_univ, ←h2, ←order_of_is_cycle h1, pow_order_of_eq_one, one_pow, one_apply] at hi, end end generation section variables [fintype α] {σ τ : perm α} noncomputable theory lemma is_conj_of_support_equiv (f : {x // x ∈ (σ.support : set α)} ≃ {x // x ∈ (τ.support : set α)}) (hf : ∀ (x : α) (hx : x ∈ (σ.support : set α)), (f ⟨σ x, apply_mem_support.2 hx⟩ : α) = τ ↑(f ⟨x,hx⟩)) : is_conj σ τ := begin refine is_conj_iff.2 ⟨equiv.extend_subtype f, _⟩, rw mul_inv_eq_iff_eq_mul, ext, simp only [perm.mul_apply], by_cases hx : x ∈ σ.support, { rw [equiv.extend_subtype_apply_of_mem, equiv.extend_subtype_apply_of_mem], { exact hf x (finset.mem_coe.2 hx) } }, { rwa [not_not.1 ((not_congr mem_support).1 (equiv.extend_subtype_not_mem f _ _)), not_not.1 ((not_congr mem_support).mp hx)] } end theorem is_cycle.is_conj (hσ : is_cycle σ) (hτ : is_cycle τ) (h : σ.support.card = τ.support.card) : is_conj σ τ := begin refine is_conj_of_support_equiv (hσ.gpowers_equiv_support.symm.trans ((gpowers_equiv_gpowers begin rw [order_of_is_cycle hσ, h, order_of_is_cycle hτ], end).trans hτ.gpowers_equiv_support)) _, intros x hx, simp only [perm.mul_apply, equiv.trans_apply, equiv.sum_congr_apply], obtain ⟨n, rfl⟩ := hσ.exists_pow_eq (classical.some_spec hσ).1 (mem_support.1 hx), apply eq.trans _ (congr rfl (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply n).symm)))), apply (congr rfl (congr rfl (congr rfl (hσ.gpowers_equiv_support_symm_apply (n + 1))))).trans _, simp only [ne.def, is_cycle.gpowers_equiv_support_apply, subtype.coe_mk, gpowers_equiv_gpowers_apply], rw [pow_succ, perm.mul_apply], end theorem is_cycle.is_conj_iff (hσ : is_cycle σ) (hτ : is_cycle τ) : is_conj σ τ ↔ σ.support.card = τ.support.card := ⟨begin intro h, obtain ⟨π, rfl⟩ := is_conj_iff.1 h, apply finset.card_congr (λ a ha, π a) (λ _ ha, _) (λ _ _ _ _ ab, π.injective ab) (λ b hb, _), { simp [mem_support.1 ha] }, { refine ⟨π⁻¹ b, ⟨_, π.apply_inv_self b⟩⟩, contrapose! hb, rw [mem_support, not_not] at hb, rw [mem_support, not_not, perm.mul_apply, perm.mul_apply, hb, perm.apply_inv_self] } end, hσ.is_conj hτ⟩ @[simp] lemma support_conj : (σ * τ * σ⁻¹).support = τ.support.map σ.to_embedding := begin ext, simp only [mem_map_equiv, perm.coe_mul, comp_app, ne.def, perm.mem_support, equiv.eq_symm_apply], refl, end lemma card_support_conj : (σ * τ * σ⁻¹).support.card = τ.support.card := by simp end theorem disjoint.is_conj_mul {α : Type*} [fintype α] {σ τ π ρ : perm α} (hc1 : is_conj σ π) (hc2 : is_conj τ ρ) (hd1 : disjoint σ τ) (hd2 : disjoint π ρ) : is_conj (σ * τ) (π * ρ) := begin classical, obtain ⟨f, rfl⟩ := is_conj_iff.1 hc1, obtain ⟨g, rfl⟩ := is_conj_iff.1 hc2, have hd1' := coe_inj.2 hd1.support_mul, have hd2' := coe_inj.2 hd2.support_mul, rw [coe_union] at *, have hd1'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd1), have hd2'' := disjoint_iff_disjoint_coe.1 (disjoint_iff_disjoint_support.1 hd2), refine is_conj_of_support_equiv _ _, { refine ((equiv.set.of_eq hd1').trans (equiv.set.union hd1'')).trans ((equiv.sum_congr (subtype_equiv f (λ a, _)) (subtype_equiv g (λ a, _))).trans ((equiv.set.of_eq hd2').trans (equiv.set.union hd2'')).symm); { simp only [set.mem_image, to_embedding_apply, exists_eq_right, support_conj, coe_map, apply_eq_iff_eq] } }, { intros x hx, simp only [trans_apply, symm_trans_apply, set.of_eq_apply, set.of_eq_symm_apply, equiv.sum_congr_apply], rw [hd1', set.mem_union] at hx, cases hx with hxσ hxτ, { rw [mem_coe, mem_support] at hxσ, rw [set.union_apply_left hd1'' _, set.union_apply_left hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inl, comp_app, set.union_symm_apply_left, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (f x)).resolve_left _, { rw [mul_apply, mul_apply] at h, rw [h, inv_apply_self, (hd1 x).resolve_left hxσ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 x).resolve_left hxσ, mem_coe, apply_mem_support, mem_support] } }, { rw [mem_coe, ← apply_mem_support, mem_support] at hxτ, rw [set.union_apply_right hd1'' _, set.union_apply_right hd1'' _], simp only [subtype_equiv_apply, perm.coe_mul, sum.map_inr, comp_app, set.union_symm_apply_right, subtype.coe_mk, apply_eq_iff_eq], { have h := (hd2 (g (τ x))).resolve_right _, { rw [mul_apply, mul_apply] at h, rw [inv_apply_self, h, (hd1 (τ x)).resolve_right hxτ] }, { rwa [mul_apply, mul_apply, inv_apply_self, apply_eq_iff_eq] } }, { rwa [subtype.coe_mk, subtype.coe_mk, mem_coe, ← apply_mem_support, mem_support] }, { rwa [subtype.coe_mk, subtype.coe_mk, perm.mul_apply, (hd1 (τ x)).resolve_right hxτ, mem_coe, mem_support] } } } end section fixed_points /-! ### Fixed points -/ lemma fixed_point_card_lt_of_ne_one [fintype α] {σ : perm α} (h : σ ≠ 1) : (filter (λ x, σ x = x) univ).card < fintype.card α - 1 := begin rw [nat.lt_sub_left_iff_add_lt, ← nat.lt_sub_right_iff_add_lt, ← finset.card_compl, finset.compl_filter], exact one_lt_card_support_of_ne_one h end end fixed_points end equiv.perm
dff6902ea59f5582add661e1624edc9dd574f055
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/counterexamples/cyclotomic_105.lean
9499e39f118ac2bee738e8167b9612de79e858f0
[ "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
3,857
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic /-! # Not all coefficients of cyclotomic polynomials are -1, 0, or 1 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We show that not all coefficients of cyclotomic polynomials are equal to `0`, `-1` or `1`, in the theorem `not_forall_coeff_cyclotomic_neg_one_zero_one`. We prove this with the counterexample `coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2`. -/ open nat (proper_divisors) finset namespace counterexample section computation instance nat.fact_prime_five : fact (nat.prime 5) := ⟨by norm_num⟩ instance nat.fact_prime_seven : fact (nat.prime 7) := ⟨by norm_num⟩ lemma proper_divisors_15 : nat.proper_divisors 15 = {1, 3, 5} := rfl lemma proper_divisors_21 : nat.proper_divisors 21 = {1, 3, 7} := rfl lemma proper_divisors_35 : nat.proper_divisors 35 = {1, 5, 7} := rfl lemma proper_divisors_105 : nat.proper_divisors 105 = {1, 3, 5, 7, 15, 21, 35} := rfl end computation open polynomial lemma cyclotomic_3 : cyclotomic 3 ℤ = 1 + X + X ^ 2 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_5 : cyclotomic 5 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_7 : cyclotomic 7 ℤ = 1 + X + X ^ 2 + X ^ 3 + X ^ 4 + X ^ 5 + X ^ 6 := by simp only [cyclotomic_prime, sum_range_succ, range_one, sum_singleton, pow_zero, pow_one] lemma cyclotomic_15 : cyclotomic 15 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 5 - X ^ 7 + X ^ 8 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_15, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5], ring, repeat { norm_num } end lemma cyclotomic_21 : cyclotomic 21 ℤ = 1 - X + X ^ 3 - X ^ 4 + X ^ 6 - X ^ 8 + X ^ 9 - X ^ 11 + X ^ 12 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_21, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_35 : cyclotomic 35 ℤ = 1 - X + X ^ 5 - X ^ 6 + X ^ 7 - X ^ 8 + X ^ 10 - X ^ 11 + X ^ 12 - X ^ 13 + X ^ 14 - X ^ 16 + X ^ 17 - X ^ 18 + X ^ 19 - X ^ 23 + X ^ 24 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw [proper_divisors_35, finset.prod_insert _, finset.prod_insert _, finset.prod_singleton, cyclotomic_one, cyclotomic_5, cyclotomic_7], ring, repeat { norm_num } end lemma cyclotomic_105 : cyclotomic 105 ℤ = 1 + X + X ^ 2 - X ^ 5 - X ^ 6 - 2 * X ^ 7 - X ^ 8 - X ^ 9 + X ^ 12 + X ^ 13 + X ^ 14 + X ^ 15 + X ^ 16 + X ^ 17 - X ^ 20 - X ^ 22 - X ^ 24 - X ^ 26 - X ^ 28 + X ^ 31 + X ^ 32 + X ^ 33 + X ^ 34 + X ^ 35 + X ^ 36 - X ^ 39 - X ^ 40 - 2 * X ^ 41 - X ^ 42 - X ^ 43 + X ^ 46 + X ^ 47 + X ^ 48 := begin refine ((eq_cyclotomic_iff (by norm_num) _).2 _).symm, rw proper_divisors_105, repeat {rw finset.prod_insert _}, rw [finset.prod_singleton, cyclotomic_one, cyclotomic_3, cyclotomic_5, cyclotomic_7, cyclotomic_15, cyclotomic_21, cyclotomic_35], ring, repeat { norm_num } end lemma coeff_cyclotomic_105 : coeff (cyclotomic 105 ℤ) 7 = -2 := begin simp [cyclotomic_105, coeff_X_pow, coeff_one, coeff_X_of_ne_one, coeff_bit0_mul, coeff_bit1_mul] end lemma not_forall_coeff_cyclotomic_neg_one_zero_one : ¬∀ n i, coeff (cyclotomic n ℤ) i ∈ ({-1, 0, 1} : set ℤ) := begin intro h, specialize h 105 7, rw coeff_cyclotomic_105 at h, norm_num at h end end counterexample
228febbdb14867909f084723fe975e52311fbd22
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/algebra/module.lean
61cad55e90b170243643398fa1408888242c10a3
[ "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
12,065
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl Modules over a ring. -/ import algebra.ring algebra.big_operators data.set.lattice open function universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : out_param $ Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `α` and an additive monoid of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class semimodule (α : out_param $ Type u) (β : Type v) [out_param $ semiring α] extends has_scalar α β, add_comm_monoid β := (smul_add : ∀r (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀r s (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀r s (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) (zero_smul : ∀x : β, (0 : α) • x = 0) (smul_zero {} : ∀r, r • (0 : β) = 0) section semimodule variables {R:semiring α} [semimodule α β] {r s : α} {x y : β} include R theorem smul_add' : r • (x + y) = r • x + r • y := semimodule.smul_add r x y theorem add_smul' : (r + s) • x = r • x + s • x := semimodule.add_smul r s x theorem mul_smul' : (r * s) • x = r • s • x := semimodule.mul_smul r s x @[simp] theorem one_smul' : (1 : α) • x = x := semimodule.one_smul x @[simp] theorem zero_smul' : (0 : α) • x = 0 := semimodule.zero_smul x @[simp] theorem smul_zero' : r • (0 : β) = 0 := semimodule.smul_zero r lemma smul_smul' : r • s • x = (r * s) • x := mul_smul'.symm end semimodule /-- A module is a generalization of vector spaces to a scalar ring. It consists of a scalar ring `α` and an additive group of "vectors" `β`, connected by a "scalar multiplication" operation `r • x : β` (where `r : α` and `x : β`) with some natural associativity and distributivity axioms similar to those on a ring. -/ class module (α : out_param $ Type u) (β : Type v) [out_param $ ring α] extends has_scalar α β, add_comm_group β := (smul_add : ∀r (x y : β), r • (x + y) = r • x + r • y) (add_smul : ∀r s (x : β), (r + s) • x = r • x + s • x) (mul_smul : ∀r s (x : β), (r * s) • x = r • s • x) (one_smul : ∀x : β, (1 : α) • x = x) section module variables {R:ring α} [module α β] {r s : α} {x y : β} include R theorem smul_add : r • (x + y) = r • x + r • y := module.smul_add r x y theorem add_smul : (r + s) • x = r • x + s • x := module.add_smul r s x theorem mul_smul : (r * s) • x = r • s • x := module.mul_smul r s x @[simp] theorem one_smul : (1 : α) • x = x := module.one_smul x @[simp] theorem zero_smul : (0 : α) • x = 0 := have (0 : α) • x + 0 • x = 0 • x + 0, by rw ← add_smul; simp, add_left_cancel this @[simp] theorem smul_zero : r • (0 : β) = 0 := have r • (0:β) + r • 0 = r • 0 + 0, by rw ← smul_add; simp, add_left_cancel this instance module.to_semimodule : semimodule α β := { zero_smul := λ x, zero_smul, smul_zero := λ r, smul_zero, ..‹module α β› } @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) theorem neg_one_smul (x : β) : (-1 : α) • x = -x := by simp @[simp] theorem smul_neg : r • (-x) = -(r • x) := by rw [← neg_one_smul x, ← mul_smul, mul_neg_one, neg_smul] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by simp [smul_add] theorem sub_smul (r s : α) (y : β) : (r - s) • y = r • y - s • y := by simp [add_smul] lemma smul_smul : r • s • x = (r * s) • x := mul_smul.symm end module instance semiring.to_semimodule [r : semiring α] : semimodule α α := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero, ..r } @[simp] lemma smul_eq_mul' [semiring α] {a a' : α} : a • a' = a * a' := rfl instance ring.to_module [r : ring α] : module α α := { ..semiring.to_semimodule } @[simp] lemma smul_eq_mul [ring α] {a a' : α} : a • a' = a * a' := rfl structure is_linear_map {α : Type u} {β : Type v} {γ : Type w} [ring α] [module α β] [module α γ] (f : β → γ) : Prop := (add : ∀x y, f (x + y) = f x + f y) (smul : ∀c x, f (c • x) = c • f x) namespace is_linear_map variables [ring α] [module α β] [module α γ] [module α δ] variables {f g h : β → γ} {r : α} {x y : β} include α section variable (hf : is_linear_map f) include hf @[simp] lemma zero : f 0 = 0 := calc f 0 = f (0 • 0 : β) : by rw [zero_smul] ... = 0 : by rw [hf.smul]; simp @[simp] lemma neg (x : β) : f (- x) = - f x := eq_neg_of_add_eq_zero $ by rw [←hf.add]; simp [hf.zero] @[simp] lemma sub (x y : β) : f (x - y) = f x - f y := by simp [hf.neg, hf.add] @[simp] lemma sum {ι : Type x} {t : finset ι} {g : ι → β} : f (t.sum g) = t.sum (λi, f (g i)) := (finset.sum_hom f hf.zero hf.add).symm end lemma comp {g : δ → β} (hf : is_linear_map f) (hg : is_linear_map g) : is_linear_map (f ∘ g) := by refine {..}; simp [(∘), hg.add, hf.add, hg.smul, hf.smul] lemma id : is_linear_map (id : β → β) := by refine {..}; simp lemma inverse {f : γ → β} {g : β → γ} (hf : is_linear_map f) (h₁ : left_inverse g f) (h₂ : right_inverse g f): is_linear_map g := ⟨assume x y, have g (f (g (x + y))) = g (f (g x + g y)), by rw [h₂ (x + y), hf.add, h₂ x, h₂ y], by rwa [h₁ (g (x + y)), h₁ (g x + g y)] at this, assume a b, have g (f (g (a • b))) = g (f (a • g b)), by rw [h₂ (a • b), hf.smul, h₂ b], by rwa [h₁ (g (a • b)), h₁ (a • g b)] at this ⟩ lemma map_zero : is_linear_map (λb, 0 : β → γ) := by refine {..}; simp lemma map_neg (hf : is_linear_map f) : is_linear_map (λb, - f b) := by refine {..}; simp [hf.add, hf.smul] lemma map_add (hf : is_linear_map f) (hg : is_linear_map g) : is_linear_map (λb, f b + g b) := by refine {..}; simp [hg.add, hf.add, hg.smul, hf.smul, smul_add] lemma map_sum [decidable_eq δ] {t : finset δ} {f : δ → β → γ} : (∀d∈t, is_linear_map (f d)) → is_linear_map (λb, t.sum $ λd, f d b) := finset.induction_on t (by simp [map_zero]) (by simp [map_add] {contextual := tt}) lemma map_sub (hf : is_linear_map f) (hg : is_linear_map g) : is_linear_map (λb, f b - g b) := by refine {..}; simp [hg.add, hf.add, hg.smul, hf.smul, smul_add] lemma map_smul_right {α : Type u} {β : Type v} {γ : Type w} [comm_ring α] [module α β] [module α γ] {f : β → γ} {r : α} (hf : is_linear_map f) : is_linear_map (λb, r • f b) := by refine {..}; simp [hf.add, hf.smul, smul_add, smul_smul, mul_comm] lemma map_smul_left {f : γ → α} (hf : is_linear_map f) : is_linear_map (λb, f b • x) := by refine {..}; simp [hf.add, hf.smul, add_smul, smul_smul] end is_linear_map /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ class is_submodule {α : Type u} {β : Type v} [ring α] [module α β] (p : set β) : Prop := (zero_ : (0:β) ∈ p) (add_ : ∀ {x y}, x ∈ p → y ∈ p → x + y ∈ p) (smul : ∀ c {x}, x ∈ p → c • x ∈ p) namespace is_submodule variables [ring α] [module α β] [module α γ] variables {p p' : set β} [is_submodule p] [is_submodule p'] variables {r : α} include α section variables {x y : β} lemma zero : (0 : β) ∈ p := is_submodule.zero_ α p lemma add : x ∈ p → y ∈ p → x + y ∈ p := is_submodule.add_ α lemma neg (hx : x ∈ p) : -x ∈ p := by rw ← neg_one_smul x; exact smul _ hx lemma sub (hx : x ∈ p) (hy : y ∈ p) : x - y ∈ p := add hx (neg hy) lemma sum {ι : Type w} [decidable_eq ι] {t : finset ι} {f : ι → β} : (∀c∈t, f c ∈ p) → t.sum f ∈ p := finset.induction_on t (by simp [zero]) (by simp [add] {contextual := tt}) lemma smul_ne_0 {a : α} {b : β} (h : a ≠ 0 → b ∈ p) : a • b ∈ p := classical.by_cases (assume : a = 0, by simp [this, zero]) (assume : a ≠ 0, by simp [h this, smul]) instance single_zero : is_submodule ({0} : set β) := by refine {..}; by simp {contextual := tt} instance univ : is_submodule (set.univ : set β) := by refine {..}; by simp {contextual := tt} instance image {f : β → γ} (hf : is_linear_map f) : is_submodule (f '' p) := { is_submodule . zero_ := ⟨0, zero, hf.zero⟩, add_ := assume c₁ c₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ + b₂, add hb₁ hb₂, by simp [eq₁, eq₂, hf.add]⟩, smul := assume a c ⟨b, hb, eq⟩, ⟨a • b, smul a hb, by simp [hf.smul, eq]⟩ } instance range {f : β → γ} (hf : is_linear_map f) : is_submodule (set.range f) := by rw [← set.image_univ]; exact is_submodule.image hf instance preimage {f : γ → β} (hf : is_linear_map f) : is_submodule (f ⁻¹' p) := by refine {..}; simp [hf.zero, hf.add, hf.smul, zero, add, smul] {contextual:=tt} instance add_submodule : is_submodule {z | ∃x∈p, ∃y∈p', z = x + y} := { is_submodule . zero_ := ⟨0, zero, 0, zero, by simp⟩, add_ := assume b₁ b₂ ⟨x₁, hx₁, y₁, hy₁, eq₁⟩ ⟨x₂, hx₂, y₂, hy₂, eq₂⟩, ⟨x₁ + x₂, add hx₁ hx₂, y₁ + y₂, add hy₁ hy₂, by simp [eq₁, eq₂]⟩, smul := assume a b ⟨x, hx, y, hy, eq⟩, ⟨a • x, smul _ hx, a • y, smul _ hy, by simp [eq, smul_add]⟩ } lemma Inter_submodule {ι : Sort w} {s : ι → set β} (h : ∀i, is_submodule (s i)) : is_submodule (⋂i, s i) := by refine {..}; simp [zero, add, smul] {contextual := tt} instance Inter_submodule' {ι : Sort w} {s : ι → set β} [h : ∀i, is_submodule (s i)] : is_submodule (⋂i, s i) := Inter_submodule h instance sInter_submodule {s : set (set β)} [hs : ∀t∈s, is_submodule t] : is_submodule (⋂₀ s) := by rw set.sInter_eq_bInter; exact Inter_submodule (assume t, Inter_submodule $ hs t) instance inter_submodule : is_submodule (p ∩ p') := suffices is_submodule (⋂₀ {p, p'} : set β), by simpa [set.inter_comm], @is_submodule.sInter_submodule α β _ _ {p, p'} $ by simp [or_imp_distrib, ‹is_submodule p›, ‹is_submodule p'›] {contextual := tt} end end is_submodule section comm_ring theorem is_submodule.eq_univ_of_contains_unit {α : Type u} [comm_ring α] (S : set α) [is_submodule S] (x y : α) (hx : x ∈ S) (h : y * x = 1) : S = set.univ := set.ext $ λ z, ⟨λ hz, trivial, λ hz, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ S : is_submodule.smul (z * y) hx⟩ theorem is_submodule.univ_of_one_mem {α : Type u} [comm_ring α] (S : set α) [is_submodule S] : (1:α) ∈ S → S = set.univ := λ h, set.ext $ λ z, ⟨λ hz, trivial, λ hz, by simpa using (is_submodule.smul z h : z * 1 ∈ S)⟩ end comm_ring /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ class vector_space (α : out_param $ Type u) (β : Type v) [out_param $ field α] extends module α β /-- Subspace of a vector space. Defined to equal `is_submodule`. -/ @[reducible] def subspace {α : Type u} {β : Type v} [field α] [vector_space α β] (p : set β) : Prop := is_submodule p
8797714f2b81214b72e1fbbaf006711475448792
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/usizeBug.lean
d97c66de8b488a3897d6a173a62a0a2a994152e4
[ "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
136
lean
structure S := (n : Nat) (u : USize) @[noinline] def f (u : USize) : S := { n := 0, u := u } def main : IO Unit := IO.println (f 2).u
054febfbf63eb3f46fb9e1d72f36184e565b82e5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/fubini.lean
d646586ed4111b9a8b12a8f4e0e1844b2cf513cb
[ "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
9,993
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.limits.has_limits import category_theory.products.basic import category_theory.currying /-! # A Fubini theorem for categorical limits We prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`, when all the appropriate limits exist. We begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated "uncurried" functor. In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`, and a cone `c` over `G`, we construct a cone over the cone points of `D`. We then show that if `c` is a limit cone, the constructed cone is also a limit cone. In the second part, we state the Fubini theorem in the setting where limits are provided by suitable `has_limit` classes. We construct `limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)` and give simp lemmas characterising it. For convenience, we also provide `limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)` in terms of the uncurried functor. ## Future work The dual statement. -/ universes v u open category_theory namespace category_theory.limits variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables (F : J ⥤ K ⥤ C) /-- A structure carrying a diagram of cones over the the functors `F.obj j`. -/ -- We could try introducing a "dependent functor type" to handle this? structure diagram_of_cones := (obj : Π j : J, cone (F.obj j)) (map : Π {j j' : J} (f : j ⟶ j'), (cones.postcompose (F.map f)).obj (obj j) ⟶ obj j') (id : ∀ j : J, (map (𝟙 j)).hom = 𝟙 _ . obviously) (comp : ∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃), (map (f ≫ g)).hom = (map f).hom ≫ (map g).hom . obviously) variables {F} /-- Extract the functor `J ⥤ C` consisting of the cone points and the maps between them, from a `diagram_of_cones`. -/ @[simps] def diagram_of_cones.cone_points (D : diagram_of_cones F) : J ⥤ C := { obj := λ j, (D.obj j).X, map := λ j j' f, (D.map f).hom, map_id' := λ j, D.id j, map_comp' := λ j₁ j₂ j₃ f g, D.comp f g, } /-- Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`, we can construct a cone over the diagram consisting of the cone points from `D`. -/ @[simps] def cone_of_cone_uncurry {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) (c : cone (uncurry.obj F)) : cone (D.cone_points) := { X := c.X, π := { app := λ j, (Q j).lift { X := c.X, π := { app := λ k, c.π.app (j, k), naturality' := λ k k' f, begin dsimp, simp only [category.id_comp], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j, k') (𝟙 j, f), dsimp at this, simp only [category.id_comp, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end } }, naturality' := λ j j' f, (Q j').hom_ext begin dsimp, intro k, simp only [limits.cone_morphism.w, limits.cones.postcompose_obj_π, limits.is_limit.fac_assoc, limits.is_limit.fac, nat_trans.comp_app, category.id_comp, category.assoc], have := @nat_trans.naturality _ _ _ _ _ _ c.π (j, k) (j', k) (f, 𝟙 k), dsimp at this, simp only [category.id_comp, category.comp_id, category_theory.functor.map_id, nat_trans.id_app] at this, exact this, end, } }. /-- `cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.` -/ def cone_of_cone_uncurry_is_limit {D : diagram_of_cones F} (Q : Π j, is_limit (D.obj j)) {c : cone (uncurry.obj F)} (P : is_limit c) : is_limit (cone_of_cone_uncurry Q c) := { lift := λ s, P.lift { X := s.X, π := { app := λ p, s.π.app p.1 ≫ (D.obj p.1).π.app p.2, naturality' := λ p p' f, begin dsimp, simp only [category.id_comp, category.assoc], rcases p with ⟨j, k⟩, rcases p' with ⟨j', k'⟩, rcases f with ⟨fj, fk⟩, dsimp, slice_rhs 3 4 { rw ←nat_trans.naturality, }, slice_rhs 2 3 { rw ←(D.obj j).π.naturality, }, simp only [functor.const.obj_map, category.id_comp, category.assoc], have w := (D.map fj).w k', dsimp at w, rw ←w, have n := s.π.naturality fj, dsimp at n, simp only [category.id_comp] at n, rw n, simp, end, } }, fac' := λ s j, begin apply (Q j).hom_ext, intro k, simp, end, uniq' := λ s m w, begin refine P.uniq { X := s.X, π := _, } m _, rintro ⟨j, k⟩, dsimp, rw [←w j], simp, end, } section variables (F) variables [has_limits_of_shape K C] /-- Given a functor `F : J ⥤ K ⥤ C`, with all needed limits, we can construct a diagram consisting of the limit cone over each functor `F.obj j`, and the universal cone morphisms between these. -/ @[simps] noncomputable def diagram_of_cones.mk_of_has_limits : diagram_of_cones F := { obj := λ j, limit.cone (F.obj j), map := λ j j' f, { hom := lim.map (F.map f), }, } -- Satisfying the inhabited linter. noncomputable instance diagram_of_cones_inhabited : inhabited (diagram_of_cones F) := ⟨diagram_of_cones.mk_of_has_limits F⟩ @[simp] lemma diagram_of_cones.mk_of_has_limits_cone_points : (diagram_of_cones.mk_of_has_limits F).cone_points = (F ⋙ lim) := rfl variables [has_limit (uncurry.obj F)] variables [has_limit (F ⋙ lim)] /-- The Fubini theorem for a functor `F : J ⥤ K ⥤ C`, showing that the limit of `uncurry.obj F` can be computed as the limit of the limits of the functors `F.obj j`. -/ noncomputable def limit_uncurry_iso_limit_comp_lim : limit (uncurry.obj F) ≅ limit (F ⋙ lim) := begin let c := limit.cone (uncurry.obj F), let P : is_limit c := limit.is_limit _, let G := diagram_of_cones.mk_of_has_limits F, let Q : Π j, is_limit (G.obj j) := λ j, limit.is_limit _, have Q' := cone_of_cone_uncurry_is_limit Q P, have Q'' := (limit.is_limit (F ⋙ lim)), exact is_limit.cone_point_unique_up_to_iso Q' Q'', end @[simp] lemma limit_uncurry_iso_limit_comp_lim_hom_π_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := begin dsimp [limit_uncurry_iso_limit_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso], simp, end @[simp] lemma limit_uncurry_iso_limit_comp_lim_inv_π {j} {k} : (limit_uncurry_iso_limit_comp_lim F).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_uncurry_iso_limit_comp_lim F).hom], simp, end end section variables (G : J × K ⥤ C) section variables [has_limits_of_shape K C] variables [has_limit G] variables [has_limit ((curry.obj G) ⋙ lim)] /-- The Fubini theorem for a functor `G : J × K ⥤ C`, showing that the limit of `G` can be computed as the limit of the limits of the functors `G.obj (j, _)`. -/ noncomputable def limit_iso_limit_curry_comp_lim : limit G ≅ limit ((curry.obj G) ⋙ lim) := begin have i : G ≅ uncurry.obj ((@curry J _ K _ C _).obj G) := currying.symm.unit_iso.app G, haveI : limits.has_limit (uncurry.obj ((@curry J _ K _ C _).obj G)) := has_limit_of_iso i, transitivity limit (uncurry.obj ((@curry J _ K _ C _).obj G)), apply has_limit.iso_of_nat_iso i, exact limit_uncurry_iso_limit_comp_lim ((@curry J _ K _ C _).obj G), end @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ (j, k) := by simp [limit_iso_limit_curry_comp_lim, is_limit.cone_point_unique_up_to_iso, is_limit.unique_up_to_iso] @[simp, reassoc] lemma limit_iso_limit_curry_comp_lim_inv_π {j} {k} : (limit_iso_limit_curry_comp_lim G).inv ≫ limit.π _ (j, k) = limit.π _ j ≫ limit.π _ k := begin rw [←cancel_epi (limit_iso_limit_curry_comp_lim G).hom], simp, end end section variables [has_limits C] -- Certainly one could weaken the hypotheses here. open category_theory.prod /-- A variant of the Fubini theorem for a functor `G : J × K ⥤ C`, showing that $\lim_k \lim_j G(j,k) ≅ \lim_j \lim_k G(j,k)$. -/ noncomputable def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim : limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit ((curry.obj G) ⋙ lim) := calc limit ((curry.obj (swap K J ⋙ G)) ⋙ lim) ≅ limit (swap K J ⋙ G) : (limit_iso_limit_curry_comp_lim _).symm ... ≅ limit G : has_limit.iso_of_equivalence (braiding K J) (iso.refl _) ... ≅ limit ((curry.obj G) ⋙ lim) : limit_iso_limit_curry_comp_lim _ @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).hom ≫ limit.π _ j ≫ limit.π _ k = limit.π _ k ≫ limit.π _ j := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_hom_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end @[simp] lemma limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {j} {k} : (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G).inv ≫ limit.π _ k ≫ limit.π _ j = limit.π _ j ≫ limit.π _ k := begin dsimp [limit_curry_swap_comp_lim_iso_limit_curry_comp_lim], simp only [iso.refl_hom, braiding_counit_iso_hom_app, limits.has_limit.iso_of_equivalence_inv_π, iso.refl_inv, limit_iso_limit_curry_comp_lim_hom_π_π, eq_to_iso_refl, category.assoc], erw [nat_trans.id_app], -- Why can't `simp` do this`? dsimp, simp, end end end end category_theory.limits
9aa53cde9f35680122f0998409e0769c833a14c8
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/stage0/src/Lean/Server/FileWorker.lean
aa8bb94641dc7a1e5d58d6d0c5ee29e7375609c1
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
21,395
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Util.Paths import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList import Lean.Server.FileWorker.Utils import Lean.Server.FileWorker.RequestHandling import Lean.Server.FileWorker.WidgetRequests import Lean.Server.Rpc.Basic import Lean.Widget.InteractiveDiagnostic /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Std (RBMap RBMap.empty) open JsonRpc structure WorkerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream srcSearchPath : SearchPath /- Asynchronous snapshot elaboration. -/ section Elab abbrev AsyncElabM := ExceptT ElabTaskError (ReaderT WorkerContext IO) /-- Elaborates the next command after `parentSnap` and emits diagnostics into `hOut`. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) : AsyncElabM Snapshot := do cancelTk.check let hOut := (←read).hOut if parentSnap.isAtEnd then publishDiagnostics m parentSnap.diagnostics.toArray hOut publishProgressDone m hOut throw ElabTaskError.eof publishProgressAtPos m parentSnap.endPos hOut let snap ← compileNextCmd m.text parentSnap -- TODO(MH): check for interrupt with increased precision cancelTk.check /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ -- NOTE(WN): this is *not* redundent even if there are no new diagnostics in this snapshot -- because empty diagnostics clear existing error/information squiggles. Therefore we always -- want to publish in case there was previously a message at this position. publishDiagnostics m snap.diagnostics.toArray hOut return snap /-- Elaborates all commands after `initSnap`, emitting the diagnostics into `hOut`. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) (initial : Bool) : ReaderT WorkerContext IO (AsyncList ElabTaskError Snapshot) := do if initial && initSnap.msgLog.hasErrors then -- treat header processing errors as fatal so users aren't swamped with followup errors let hOut := (←read).hOut publishProgressAtPos m initSnap.beginPos hOut (kind := LeanFileProgressKind.fatalError) AsyncList.nil else AsyncList.unfoldAsync (nextCmdSnap m . cancelTk (← read)) initSnap end Elab -- Pending requests are tracked so they can be cancelled abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) compare structure WorkerState where doc : EditableDocument pendingRequests : PendingRequestMap /-- A map of RPC session IDs. We allow asynchronous elab tasks and request handlers to modify sessions. A single `Ref` ensures atomic transactions. -/ rpcSessions : Std.RBMap UInt64 (IO.Ref RpcSession) compare abbrev WorkerM := ReaderT WorkerContext <| StateRefT WorkerState IO /- Worker initialization sequence. -/ section Initialization /-- Use `lake print-paths` to compile dependencies on the fly and add them to `LEAN_PATH`. Compilation progress is reported to `hOut` via LSP notifications. Return the search path for source files. -/ partial def lakeSetupSearchPath (lakePath : System.FilePath) (m : DocumentMeta) (imports : Array Import) (hOut : FS.Stream) : IO SearchPath := do let args := #["print-paths"] ++ imports.map (toString ·.module) let cmdStr := " ".intercalate (toString lakePath :: args.toList) let lakeProc ← Process.spawn { stdin := Process.Stdio.null stdout := Process.Stdio.piped stderr := Process.Stdio.piped cmd := lakePath.toString args } -- progress notification: report latest stderr line let rec processStderr (acc : String) : IO String := do let line ← lakeProc.stderr.getLine if line == "" then return acc else publishDiagnostics m #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.information, message := line }] hOut processStderr (acc ++ line) let stderr ← IO.asTask (processStderr "") Task.Priority.dedicated let stdout := String.trim (← lakeProc.stdout.readToEnd) let stderr ← IO.ofExcept stderr.get match (← lakeProc.wait) with | 0 => -- ignore any output up to the last line -- TODO: leanpkg should instead redirect nested stdout output to stderr let stdout := stdout.split (· == '\n') |>.getLast! let Except.ok (paths : LeanPaths) ← pure (Json.parse stdout >>= fromJson?) | throwServerError s!"invalid output from `{cmdStr}`:\n{stdout}\nstderr:\n{stderr}" initSearchPath (← getBuildDir) paths.oleanPath paths.srcPath.mapM realPathNormalized | 2 => pure [] -- no lakefile.lean | _ => throwServerError s!"`{cmdStr}` failed:\n{stdout}\nstderr:\n{stderr}" def compileHeader (m : DocumentMeta) (hOut : FS.Stream) (opts : Options) : IO (Snapshot × SearchPath) := do let inputCtx := Parser.mkInputContext m.text.source "<input>" let (headerStx, headerParserState, msgLog) ← Parser.parseHeader inputCtx let lakePath ← match (← IO.getEnv "LAKE") with | some path => System.FilePath.mk path | none => let lakePath := -- backward compatibility, kill when `leanpkg` is removed if (← System.FilePath.pathExists "leanpkg.toml") && !(← System.FilePath.pathExists "lakefile.lean") then "leanpkg" else "lake" let lakePath ← match (← IO.getEnv "LEAN_SYSROOT") with | some path => pure <| System.FilePath.mk path / "bin" / lakePath | _ => pure <| (← appDir) / lakePath lakePath.withExtension System.FilePath.exeExtension let srcPath := (← appDir) / ".." / "lib" / "lean" / "src" -- `lake/` should come first since on case-insensitive file systems, Lean thinks that `src/` also contains `Lake/` let mut srcSearchPath := [srcPath / "lake", srcPath] let (headerEnv, msgLog) ← try -- NOTE: lake does not exist in stage 0 (yet?) if (← System.FilePath.pathExists lakePath) then let pkgSearchPath ← lakeSetupSearchPath lakePath m (Lean.Elab.headerToImports headerStx).toArray hOut srcSearchPath := pkgSearchPath ++ srcSearchPath Elab.processHeader headerStx opts msgLog inputCtx catch e => -- should be from `lake print-paths` let msgs := MessageLog.empty.add { fileName := "<ignored>", pos := ⟨0, 0⟩, data := e.toString } pure (← mkEmptyEnvironment, msgs) if let some p := (← IO.getEnv "LEAN_SRC_PATH") then srcSearchPath := System.SearchPath.parse p ++ srcSearchPath let cmdState := Elab.Command.mkState headerEnv msgLog opts let cmdState := { cmdState with infoState := { enabled := true -- add dummy tree for invariant in `Snapshot.infoTree` -- TODO: maybe even fill with useful stuff trees := #[Elab.InfoTree.node (Elab.Info.ofCommandInfo { elaborator := `import, stx := headerStx }) #[].toPersistentArray].toPersistentArray }} let headerSnap := { beginPos := 0 stx := headerStx mpState := headerParserState cmdState := cmdState interactiveDiags := ← cmdState.messages.msgs.mapM (Widget.msgToInteractiveDiagnostic m.text) } publishDiagnostics m headerSnap.diagnostics.toArray hOut return (headerSnap, srcSearchPath) def initializeWorker (meta : DocumentMeta) (i o e : FS.Stream) (opts : Options) : IO (WorkerContext × WorkerState) := do let (headerSnap, srcSearchPath) ← compileHeader meta o opts let cancelTk ← CancelToken.new let ctx := { hIn := i hOut := o hLog := e srcSearchPath := srcSearchPath } let cmdSnaps ← unfoldCmdSnaps meta headerSnap cancelTk (initial := true) ctx let doc : EditableDocument := ⟨meta, headerSnap, cmdSnaps, cancelTk⟩ return (ctx, { doc := doc pendingRequests := RBMap.empty rpcSessions := Std.RBMap.empty }) end Initialization section Updates def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : WorkerM Unit := do modify fun st => { st with pendingRequests := map st.pendingRequests } /-- Given the new document, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) : WorkerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let ctx ← read let oldDoc := (←get).doc let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some ElabTaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (ElabTaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set let changePos := oldDoc.meta.text.source.firstDiffPos newMeta.text.source -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk (initial := true) ctx modify fun st => { st with doc := ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ } else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk (initial := false) ctx let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps modify fun st => { st with doc := ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ } end Updates /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidChange (p : DidChangeTextDocumentParams) : WorkerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc := (←get).doc let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let newDocText := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ def handleCancelRequest (p : CancelParams) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) def handleRpcRelease (p : Lsp.RpcReleaseParams) : WorkerM Unit := do let st ← get -- NOTE(WN): when the worker restarts e.g. due to changed imports, we may receive `rpc/release` -- for the previous RPC session. This is fine, just ignore. if let some seshRef := st.rpcSessions.find? p.sessionId then let mut sesh ← seshRef.get for ref in p.refs do sesh := sesh.release ref |>.snd sesh ← sesh.keptAlive seshRef.set sesh def handleRpcKeepAlive (p : Lsp.RpcKeepAliveParams) : WorkerM Unit := do let st ← get match st.rpcSessions.find? p.sessionId with | none => return | some seshRef => let sesh ← seshRef.get let sesh ← sesh.keptAlive seshRef.set sesh end NotificationHandling /-! Requests here are handled synchronously rather than in the asynchronous `RequestM`. -/ section RequestHandling def handleRpcConnect (p : RpcConnectParams) : WorkerM RpcConnected := do let (newId, newSesh) ← RpcSession.new let newSeshRef ← IO.mkRef newSesh modify fun st => { st with rpcSessions := st.rpcSessions.insert newId newSeshRef } return { sessionId := newId } end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : WorkerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleNotification (method : String) (params : Json) : WorkerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → WorkerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/release" => handle RpcReleaseParams handleRpcRelease | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams handleRpcKeepAlive | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : WorkerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : WorkerM Unit := do let ctx ← read let st ← get if method == "$/lean/rpc/connect" then try let ps ← parseParams RpcConnectParams params let resp ← handleRpcConnect ps ctx.hOut.writeLspResponse ⟨id, resp⟩ catch e => ctx.hOut.writeLspResponseError { id code := ErrorCode.internalError message := toString e } return let rc : RequestContext := { rpcSessions := st.rpcSessions srcSearchPath := ctx.srcSearchPath doc := st.doc hLog := ctx.hLog } let t? ← EIO.toIO' <| handleLspRequest method params rc let t₁ ← match t? with | Except.error e => IO.asTask do ctx.hOut.writeLspResponseError <| e.toLspResponseError id | Except.ok t => (IO.mapTask · t) fun | Except.ok resp => ctx.hOut.writeLspResponse ⟨id, resp⟩ | Except.error e => ctx.hOut.writeLspResponseError <| e.toLspResponseError id queueRequest id t₁ end MessageHandling section MainLoop partial def mainLoop : WorkerM Unit := do let ctx ← read let mut st ← get let msg ← ctx.hIn.readLspMessage let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : IO PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← st.pendingRequests.foldM (fun acc id task => filterFinishedTasks acc id task) st.pendingRequests st := { st with pendingRequests } -- Opportunistically (i.e. when we wake up on messages) check if any RPC session has expired. for (id, seshRef) in st.rpcSessions do let sesh ← seshRef.get if (← sesh.hasExpired) then st := { st with rpcSessions := st.rpcSessions.erase id } set st match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => let doc ← (←get).doc doc.cancelTk.set return () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) (opts : Options) : IO UInt32 := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let doc := param.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ let meta : DocumentMeta := ⟨doc.uri, doc.version, doc.text.toFileMap⟩ let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e try let (ctx, st) ← initializeWorker meta i o e opts let _ ← StateRefT'.run (s := st) <| ReaderT.run (r := ctx) mainLoop return (0 : UInt32) catch e => IO.eprintln e publishDiagnostics meta #[{ range := ⟨⟨0, 0⟩, ⟨0, 0⟩⟩, severity? := DiagnosticSeverity.error, message := e.toString }] o return (1 : UInt32) @[export lean_server_worker_main] def workerMain (opts : Options) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try let seed ← (UInt64.toNat ∘ ByteArray.toUInt64LE!) <$> IO.getRandomBytes 8 IO.setRandSeed seed let exitCode ← initAndRunWorker i o e opts -- HACK: all `Task`s are currently "foreground", i.e. we join on them on main thread exit, but we definitely don't -- want to do that in the case of the worker processes, which can produce non-terminating tasks evaluating user code o.flush e.flush IO.Process.exit exitCode.toUInt8 catch err => e.putStrLn s!"worker initialization error: {err}" return (1 : UInt32) end Lean.Server.FileWorker
c8bdc4430d6266af247a1fff7d0b039680a757fd
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/over_notation.lean
9bba96e9d70c5e6fffb649567fd63b4bb7438613
[ "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
364
lean
constant f : nat → nat → nat constant g : string → string → string infix ` & `:60 := f infix ` & `:60 := g set_option pp.notation false check 0 & 1 check "a" & "b" check tt & ff notation `[[`:max l:(foldr `, ` (h t, f h t) 0 `]]`:0) := l notation `[[`:max l:(foldr `, ` (h t, g h t) "" `]]`:0) := l check [[ (1:nat), 2, 3 ]] check [[ "a", "b", "c" ]]
5cefbd1eba0a6ac57a9e0ee9a5467576207f4ddc
64874bd1010548c7f5a6e3e8902efa63baaff785
/hott/algebra/precategory/functor.hlean
1617b901f97b69c3e6f26760702da671de41daa7
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,955
hlean
-- Copyright (c) 2014 Floris van Doorn. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Floris van Doorn, Jakob von Raumer import .basic types.pi open function precategory eq prod equiv is_equiv sigma sigma.ops truncation open pi structure functor (C D : Precategory) : Type := (obF : C → D) (homF : Π ⦃a b : C⦄, hom a b → hom (obF a) (obF b)) (respect_id : Π (a : C), homF (ID a) = ID (obF a)) (respect_comp : Π {a b c : C} (g : hom b c) (f : hom a b), homF (g ∘ f) = homF g ∘ homF f) infixl `⇒`:25 := functor namespace functor variables {C D E : Precategory} attribute obF [coercion] attribute homF [coercion] -- "functor C D" is equivalent to a certain sigma type set_option unifier.max_steps 38500 protected definition sigma_char : (Σ (obF : C → D) (homF : Π ⦃a b : C⦄, hom a b → hom (obF a) (obF b)), (Π (a : C), homF (ID a) = ID (obF a)) × (Π {a b c : C} (g : hom b c) (f : hom a b), homF (g ∘ f) = homF g ∘ homF f)) ≃ (functor C D) := begin fapply equiv.mk, intro S, fapply functor.mk, exact (S.1), exact (S.2.1), exact (pr₁ S.2.2), exact (pr₂ S.2.2), fapply adjointify, intro F, apply (functor.rec_on F), intros (d1, d2, d3, d4), exact (sigma.mk d1 (sigma.mk d2 (pair d3 (@d4)))), intro F, apply (functor.rec_on F), intros (d1, d2, d3, d4), apply idp, intro S, apply (sigma.rec_on S), intros (d1, S2), apply (sigma.rec_on S2), intros (d2, P1), apply (prod.rec_on P1), intros (d3, d4), apply idp, end protected definition strict_cat_has_functor_hset [HD : is_hset (objects D)] : is_hset (functor C D) := begin apply trunc_equiv, apply equiv.to_is_equiv, apply sigma_char, apply trunc_sigma, apply trunc_pi, intros, exact HD, intro F, apply trunc_sigma, apply trunc_pi, intro a, apply trunc_pi, intro b, apply trunc_pi, intro c, apply !homH, intro H, apply trunc_prod, apply trunc_pi, intro a, apply succ_is_trunc, apply trunc_succ, apply !homH, apply trunc_pi, intro a, apply trunc_pi, intro b, apply trunc_pi, intro c, apply trunc_pi, intro g, apply trunc_pi, intro f, apply succ_is_trunc, apply trunc_succ, apply !homH, end -- The following lemmas will later be used to prove that the type of -- precategories formes a precategory itself protected definition compose (G : functor D E) (F : functor C D) : functor C E := functor.mk (λ x, G (F x)) (λ a b f, G (F f)) (λ a, calc G (F (ID a)) = G (ID (F a)) : {respect_id F a} ... = ID (G (F a)) : respect_id G (F a)) (λ a b c g f, calc G (F (g ∘ f)) = G (F g ∘ F f) : respect_comp F g f ... = G (F g) ∘ G (F f) : respect_comp G (F g) (F f)) infixr `∘f`:60 := compose protected theorem congr {C : Precategory} {D : Precategory} (F : C → D) (foo2 : Π ⦃a b : C⦄, hom a b → hom (F a) (F b)) (foo3a foo3b : Π (a : C), foo2 (ID a) = ID (F a)) (foo4a foo4b : Π {a b c : C} (g : @hom C C b c) (f : @hom C C a b), foo2 (g ∘ f) = foo2 g ∘ foo2 f) (p3 : foo3a = foo3b) (p4 : @foo4a = @foo4b) : functor.mk F foo2 foo3a @foo4a = functor.mk F foo2 foo3b @foo4b := begin apply (eq.rec_on p3), intros, apply (eq.rec_on p4), intros, apply idp, end protected theorem assoc {A B C D : Precategory} (H : functor C D) (G : functor B C) (F : functor A B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := begin apply (functor.rec_on H), intros (H1, H2, H3, H4), apply (functor.rec_on G), intros (G1, G2, G3, G4), apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, apply funext.path_pi, intro a, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end protected definition id {C : Precategory} : functor C C := mk (λa, a) (λ a b f, f) (λ a, idp) (λ a b c f g, idp) protected definition ID (C : Precategory) : functor C C := id protected theorem id_left (F : functor C D) : id ∘f F = F := begin apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end protected theorem id_right (F : functor C D) : F ∘f id = F := begin apply (functor.rec_on F), intros (F1, F2, F3, F4), fapply functor.congr, apply funext.path_pi, intro a, apply (@is_hset.elim), apply !homH, repeat (apply funext.path_pi; intros), apply (@is_hset.elim), apply !homH, end end functor namespace precategory open functor definition precat_of_strict_precats : precategory (Σ (C : Precategory), is_hset (objects C)) := precategory.mk (λ a b, functor a.1 b.1) (λ a b, @functor.strict_cat_has_functor_hset a.1 b.1 b.2) (λ a b c g f, functor.compose g f) (λ a, functor.id) (λ a b c d h g f, !functor.assoc) (λ a b f, !functor.id_left) (λ a b f, !functor.id_right) definition Precat_of_strict_cats := Mk precat_of_strict_precats namespace ops notation `PreCat`:max := Precat_of_strict_cats attribute precat_of_strict_precats [instance] end ops end precategory namespace functor -- open category.ops -- universes l m variables {C D : Precategory} -- check hom C D -- variables (F : C ⟶ D) (G : D ⇒ C) -- check G ∘ F -- check F ∘f G -- variables (a b : C) (f : a ⟶ b) -- check F a -- check F b -- check F f -- check G (F f) -- print "---" -- -- check (G ∘ F) f --error -- check (λ(x : functor C C), x) (G ∘ F) f -- check (G ∘f F) f -- print "---" -- -- check (G ∘ F) a --error -- check (G ∘f F) a -- print "---" -- -- check λ(H : hom C D) (x : C), H x --error -- check λ(H : @hom _ Cat C D) (x : C), H x -- check λ(H : C ⇒ D) (x : C), H x -- print "---" -- -- variables {obF obG : C → D} (Hob : ∀x, obF x = obG x) (homF : Π(a b : C) (f : a ⟶ b), obF a ⟶ obF b) (homG : Π(a b : C) (f : a ⟶ b), obG a ⟶ obG b) -- -- check eq.rec_on (funext Hob) homF = homG /-theorem mk_heq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) (Hmor : ∀(a b : C) (f : a ⟶ b), homF a b f == homG a b f) : mk obF homF idF compF = mk obG homG idG compG := hddcongr_arg4 mk (funext Hob) (hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor)))) !proof_irrel !proof_irrel protected theorem hequal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) (Hmor : ∀a b (f : a ⟶ b), F f == G f), F = G := functor.rec (λ obF homF idF compF, functor.rec (λ obG homG idG compG Hob Hmor, mk_heq Hob Hmor) G) F-/ -- theorem mk_eq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) -- (Hmor : ∀(a b : C) (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f) -- = homG a b f) -- : mk obF homF idF compF = mk obG homG idG compG := -- dcongr_arg4 mk -- (funext Hob) -- (funext (λ a, funext (λ b, funext (λ f, sorry ⬝ Hmor a b f)))) -- -- to fill this sorry use (a generalization of) cast_pull -- !proof_irrel -- !proof_irrel -- protected theorem equal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) -- (Hmor : ∀a b (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (F f) = G f), F = G := -- functor.rec -- (λ obF homF idF compF, -- functor.rec -- (λ obG homG idG compG Hob Hmor, mk_eq Hob Hmor) -- G) -- F end functor
865ea13d612d93fa0c6ba73434d7e5d6acb9bc91
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/nat/totient.lean
de46894cf28f51a22b3cf213b723eed4dfa60298
[ "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
3,595
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators data.nat.gcd open finset namespace nat def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _) ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 (mt eq_empty_iff_forall_not_mem.1 (not_forall_of_exists_not ⟨1, not_not.2 $ mem_filter.2 ⟨mem_range.2 dec_trivial, by simp [coprime]⟩⟩)) lemma sum_totient (n : ℕ) : ((range n.succ).filter (∣ n)).sum φ = n := if hn0 : n = 0 then by rw hn0; refl else calc ((range n.succ).filter (∣ n)).sum φ = ((range n.succ).filter (∣ n)).sum (λ d, ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card) : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_right_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_right_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ((range n.succ).filter (∣ n)).sum (λ d, ((range n).filter (λ m, gcd n m = d)).card) : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_left_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bind (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bind (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext.2 (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bind.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
624f16b94f6d69a66b84a7268532430988d32041
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/mv_polynomial/comm_ring.lean
b737acc26dff0f2e7fc968d35ebdad7c3b9475ae
[ "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
5,022
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.variables /-! # Multivariate polynomials over a ring Many results about polynomials hold when the coefficient ring is a commutative semiring. Some stronger results can be derived when we assume this semiring is a ring. This file does not define any new operations, but proves some of these stronger results. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_ring 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` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v variables {R : Type u} {S : Type v} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_ring variable [comm_ring R] variables {p q : mv_polynomial σ R} instance : comm_ring (mv_polynomial σ R) := add_monoid_algebra.comm_ring instance C.is_ring_hom : is_ring_hom (C : R → mv_polynomial σ R) := by apply is_ring_hom.of_semiring variables (σ a a') @[simp] lemma C_sub : (C (a - a') : mv_polynomial σ R) = C a - C a' := is_ring_hom.map_sub _ @[simp] lemma C_neg : (C (-a) : mv_polynomial σ R) = -C a := is_ring_hom.map_neg _ @[simp] lemma coeff_neg (m : σ →₀ ℕ) (p : mv_polynomial σ R) : coeff m (-p) = -coeff m p := finsupp.neg_apply _ _ @[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply _ _ _ instance coeff.is_add_group_hom (m : σ →₀ ℕ) : is_add_group_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m } variables {σ} (p) section degrees lemma degrees_neg (p : mv_polynomial σ R) : (- p).degrees = p.degrees := by rw [degrees, finsupp.support_neg]; refl lemma degrees_sub (p q : mv_polynomial σ R) : (p - q).degrees ≤ p.degrees ⊔ q.degrees := by simpa only [sub_eq_add_neg] using le_trans (degrees_add p (-q)) (by rw degrees_neg) end degrees section vars variables (p q) @[simp] lemma vars_neg : (-p).vars = p.vars := by simp [vars, degrees_neg] lemma vars_sub_subset : (p - q).vars ⊆ p.vars ∪ q.vars := by convert vars_add_subset p (-q) using 2; simp [sub_eq_add_neg] variables {p q} @[simp] lemma vars_sub_of_disjoint (hpq : disjoint p.vars q.vars) : (p - q).vars = p.vars ∪ q.vars := begin rw ←vars_neg q at hpq, convert vars_add_of_disjoint hpq using 2; simp [sub_eq_add_neg] end end vars section eval₂ variables [comm_ring S] variables (f : R →+* S) (g : σ → S) @[simp] lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := (eval₂_hom f g).map_sub _ _ @[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := (eval₂_hom f g).map_neg _ lemma hom_C (f : mv_polynomial σ ℤ → S) [is_ring_hom f] (n : ℤ) : f (C n) = (n : S) := ((ring_hom.of f).comp (ring_hom.of C)).eq_int_cast n /-- A ring homomorphism f : Z[X_1, X_2, ...] → R is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma eval₂_hom_X {R : Type u} (c : ℤ →+* S) (f : mv_polynomial R ℤ →+* S) (x : mv_polynomial R ℤ) : eval₂ c (f ∘ X) x = f x := mv_polynomial.induction_on x (λ n, by { rw [hom_C f, eval₂_C], exact (ring_hom.of c).eq_int_cast n }) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm }) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`, -/ def hom_equiv : (mv_polynomial σ ℤ →+* S) ≃ (σ → S) := { to_fun := λ f, ⇑f ∘ X, inv_fun := λ f, eval₂_hom (int.cast_ring_hom S) f, left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _, right_inv := λ f, funext $ λ x, by simp only [coe_eval₂_hom, function.comp_app, eval₂_X] } end eval₂ section total_degree @[simp] lemma total_degree_neg (a : mv_polynomial σ R) : (-a).total_degree = a.total_degree := by simp only [total_degree, finsupp.support_neg] lemma total_degree_sub (a b : mv_polynomial σ R) : (a - b).total_degree ≤ max a.total_degree b.total_degree := calc (a - b).total_degree = (a + -b).total_degree : by rw sub_eq_add_neg ... ≤ max a.total_degree (-b).total_degree : total_degree_add a (-b) ... = max a.total_degree b.total_degree : by rw total_degree_neg end total_degree end comm_ring end mv_polynomial
d18872be1739b8dc876958253c224a8a0511e72a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/count.lean
b4479638e6b4737d1f9215ecc35fb5a74bcfbd6d
[ "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
8,736
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.list.big_operators /-! # Counting in lists This file proves basic properties of `list.countp` and `list.count`, which count the number of elements of a list satisfying a predicate and equal to a given element respectively. Their definitions can be found in [`data.list.defs`](./defs). -/ open nat variables {α β : Type*} {l l₁ l₂ : list α} namespace list section countp variables (p : α → Prop) [decidable_pred p] @[simp] lemma countp_nil : countp p [] = 0 := rfl @[simp] lemma countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] lemma countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa lemma countp_cons (a : α) (l) : countp p (a :: l) = countp p l + ite (p a) 1 0 := by { by_cases h : p a; simp [h] } lemma length_eq_countp_add_countp (l) : length l = countp p l + countp (λ a, ¬p a) l := by induction l with x h ih; [refl, by_cases p x]; [simp only [countp_cons_of_pos _ _ h, countp_cons_of_neg (λ a, ¬p a) _ (decidable.not_not.2 h), ih, length], simp only [countp_cons_of_pos (λ a, ¬p a) _ h, countp_cons_of_neg _ _ h, ih, length]]; ac_refl lemma 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 lemma countp_le_length : countp p l ≤ l.length := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist _) @[simp] lemma 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] lemma 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_eq_zero {l} : countp p l = 0 ↔ ∀ a ∈ l, ¬ p a := by { rw [← not_iff_not, ← ne.def, ← pos_iff_ne_zero, countp_pos], simp } lemma countp_eq_length {l} : countp p l = l.length ↔ ∀ a ∈ l, p a := by rw [countp_eq_length_filter, filter_length_eq_length] lemma length_filter_lt_length_iff_exists (l) : length (filter p l) < length l ↔ ∃ x ∈ l, ¬p x := by rw [length_eq_countp_add_countp p l, ← countp_pos, countp_eq_length_filter, lt_add_iff_pos_right] lemma sublist.countp_le (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (s.filter p) @[simp] lemma 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] @[simp] lemma countp_true : l.countp (λ _, true) = l.length := by simp [countp_eq_length_filter] @[simp] lemma countp_false : l.countp (λ _, false) = 0 := by simp [countp_eq_length_filter] end countp /-! ### count -/ section count variables [decidable_eq α] @[simp] lemma count_nil (a : α) : count a [] = 0 := rfl lemma count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl lemma 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] lemma count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp, priority 990] lemma count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h lemma 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 } lemma count_le_length (a : α) (l : list α) : count a l ≤ l.length := countp_le_length _ lemma sublist.count_le (h : l₁ <+ l₂) (a : α) : count a l₁ ≤ count a l₂ := h.countp_le _ lemma count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := (sublist_cons _ _).count_le _ lemma count_singleton (a : α) : count a [a] = 1 := if_pos rfl lemma count_singleton' (a b : α) : count a [b] = ite (a = b) 1 0 := rfl @[simp] lemma count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append _ lemma count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by simp [-add_comm] @[simp] lemma count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp] lemma one_le_count_iff_mem {a : α} {l : list α} : 1 ≤ count a l ↔ a ∈ l := count_pos @[simp, priority 980] lemma 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') lemma not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', (count_pos.2 h').ne' h lemma count_eq_zero {a : α} {l} : count a l = 0 ↔ a ∉ l := ⟨not_mem_of_count_eq_zero, count_eq_zero_of_not_mem⟩ lemma count_eq_length {a : α} {l} : count a l = l.length ↔ ∀ b ∈ l, a = b := by rw [count, countp_eq_length] @[simp] lemma 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 lemma 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 h.count_le a⟩ lemma 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] lemma 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, show (λ b, a = b ∧ p b) = eq a, by { ext b, constructor; cc }] lemma count_bind {α β} [decidable_eq β] (l : list α) (f : α → list β) (x : β) : count x (l.bind f) = sum (map (count x ∘ f) l) := begin induction l with hd tl IH, { simp }, { simpa } end @[simp] lemma count_map_of_injective {α β} [decidable_eq α] [decidable_eq β] (l : list α) (f : α → β) (hf : function.injective f) (x : α) : count (f x) (map f l) = count x l := begin induction l with y l IH generalizing x, { simp }, { simp [map_cons, count_cons', IH, hf.eq_iff] } end lemma count_le_count_map [decidable_eq β] (l : list α) (f : α → β) (x : α) : count x l ≤ count (f x) (map f l) := begin induction l with a as IH, { simp }, rcases eq_or_ne x a with rfl | hxa, { simp [succ_le_succ IH] }, { simp [hxa, le_add_right IH, count_cons'] } end @[simp] lemma 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] lemma 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 @[to_additive] lemma prod_map_eq_pow_single [monoid β] {l : list α} (a : α) (f : α → β) (hf : ∀ a' ≠ a, a' ∈ l → f a' = 1) : (l.map f).prod = (f a) ^ (l.count a) := begin induction l with a' as h generalizing a, { rw [map_nil, prod_nil, count_nil, pow_zero] }, { specialize h a (λ a' ha' hfa', hf a' ha' (mem_cons_of_mem _ hfa')), rw [list.map_cons, list.prod_cons, count_cons, h], split_ifs with ha', { rw [ha', pow_succ] }, { rw [hf a' (ne.symm ha') (list.mem_cons_self a' as), one_mul] } } end @[to_additive] lemma prod_eq_pow_single [monoid α] {l : list α} (a : α) (h : ∀ a' ≠ a, a' ∈ l → a' = 1) : l.prod = a ^ (l.count a) := trans (by rw [map_id'']) (prod_map_eq_pow_single a id h) end count end list
94bd38f1f36055486249e5f74ed939762d0aeaff
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/playground/task_test.lean
636ce43bc335c110ad0866bcd10e364c2664aeb4
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
515
lean
def g (x : Nat) : Nat := dbgTrace ("g: " ++ toString x) $ fun _ => x + 1 def f1 (x : Nat) : Nat := dbgSleep 1000 $ fun _ => dbgTrace ("f1: " ++ toString x) $ fun _ => g (x + 1) def f2 (x : Nat) : Nat := dbgSleep 100 $ fun _ => dbgTrace ("f2: " ++ toString x) $ fun _ => g x def main (xs : List String) : IO UInt32 := let t1 := Task.mk $ (fun _ => f1 xs.head.toNat); let t2 := Task.mk $ (fun _ => f2 xs.head.toNat); dbgSleep 1000 $ fun _ => IO.println (toString t1.get ++ " " ++ toString t2.get) *> pure 0
6316936b4bcc59d532ea3605c8ed358ad9a9ef8b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/basic.lean
1dca88a4290fc695896376d60e94d2a90d835f11
[ "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
159,631
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.nat.basic /-! # Basic properties of lists -/ open function nat (hiding one_pos) namespace list universes u v w x variables {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} attribute [inline] list.head /-- There is only one list of an empty type -/ instance unique_of_is_empty [is_empty α] : unique (list α) := { uniq := λ l, match l with | [] := rfl | (a :: l) := is_empty_elim a end, ..list.inhabited α } 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'], } lemma set_of_mem_cons (l : list α) (a : α) : {x | x ∈ a :: l} = insert a {x | x ∈ l} := rfl /-! ### 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) @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := begin -- This proof uses no axioms, that's why it's longer that `induction`; simp [...] induction l with a l ihl, { split, { rintro ⟨_⟩ }, { rintro ⟨a, ⟨_⟩, _⟩ } }, { refine (or_congr eq_comm ihl).trans _, split, { rintro (h|⟨c, hcl, h⟩), exacts [⟨a, or.inl rfl, h⟩, ⟨c, or.inr hcl, h⟩] }, { rintro ⟨c, (hc|hc), h⟩, exacts [or.inl $ (congr_arg f hc.symm).trans h, or.inr ⟨c, hc, h⟩] } } end alias mem_map ↔ exists_of_mem_map _ theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := mem_map.2 ⟨a, h, rfl⟩ 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 _⟩ @[simp] lemma _root_.function.involutive.exists_mem_and_apply_eq_iff {f : α → α} (hf : function.involutive f) (x : α) (l : list α) : (∃ (y : α), y ∈ l ∧ f y = x) ↔ f x ∈ l := ⟨by { rintro ⟨y, h, rfl⟩, rwa hf y }, λ h, ⟨f x, h, hf _⟩⟩ theorem mem_map_of_involutive {f : α → α} (hf : involutive f) {a : α} {l : list α} : a ∈ map f l ↔ f a ∈ l := by rw [mem_map, hf.exists_mem_and_apply_eq_iff] lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} : (∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) := begin split, { assume H j hj, exact H (f j) (mem_map_of_mem f hj) }, { assume H i hi, rcases mem_map.1 hi with ⟨j, hj, ji⟩, rw ← ji, exact H j hj } end @[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] := ⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff], λ h, h.symm ▸ rfl⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] lemma map_bind (g : β → list γ) (f : α → β) : ∀ l : list α, (list.map f l).bind g = l.bind (λ a, g (f a)) | [] := rfl | (a::l) := by simp only [cons_bind, map_cons, map_bind l] lemma range_map (f : α → β) : set.range (map f) = {l | ∀ x ∈ l, x ∈ set.range f} := begin refine set.subset.antisymm (set.range_subset_iff.2 $ λ l, forall_mem_map_iff.2 $ λ y _, set.mem_range_self _) (λ l hl, _), induction l with a l ihl, { exact ⟨[], rfl⟩ }, rcases ihl (λ x hx, hl x $ subset_cons _ _ hx) with ⟨l, rfl⟩, rcases hl a (mem_cons_self _ _) with ⟨a, rfl⟩, exact ⟨a :: l, map_cons _ _ _⟩ end lemma range_map_coe (s : set α) : set.range (map (coe : s → α)) = {l | ∀ x ∈ l, x ∈ s} := by rw [range_map, subtype.range_coe] /-- If each element of a list can be lifted to some type, then the whole list can be lifted to this type. -/ instance [h : can_lift α β] : can_lift (list α) (list β) := { coe := list.map h.coe, cond := λ l, ∀ x ∈ l, can_lift.cond β x, prf := λ l H, begin rw [← set.mem_range, range_map], exact λ a ha, can_lift.prf a (H a ha), end} /-! ### 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 lemma length_eq_two {l : list α} : l.length = 2 ↔ ∃ a b, l = [a, b] := ⟨match l with [a, b], _ := ⟨a, b, rfl⟩ end, λ ⟨a, b, e⟩, e.symm ▸ rfl⟩ lemma length_eq_three {l : list α} : l.length = 3 ↔ ∃ a b c, l = [a, b, c] := ⟨match l with [a, b, c], _ := ⟨a, b, c, rfl⟩ end, λ ⟨a, b, c, e⟩, e.symm ▸ rfl⟩ /-! ### 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 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) lemma subset_singleton_iff {a : α} : ∀ L : list α, L ⊆ [a] ↔ ∃ n, L = repeat a n | [] := ⟨λ h, ⟨0, by simp⟩, by simp⟩ | (h :: L) := begin refine ⟨λ h, _, λ ⟨k, hk⟩, by simp [hk, repeat_subset_singleton]⟩, rw [cons_subset] at h, obtain ⟨n, rfl⟩ := (subset_singleton_iff L).mp h.2, exact ⟨n.succ, by simp [mem_singleton.mp h.1]⟩ end @[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) @[simp] theorem bind_singleton' (l : list α) : l.bind (λ x, [x]) = l := bind_pure l theorem map_eq_bind {α β} (f : α → β) (l : list α) : map f l = l.bind (λ x, [f x]) := by { transitivity, rw [← bind_singleton' l, bind_map], refl } theorem bind_assoc {α β} (l : list α) (f : α → list β) (g : β → list γ) : (l.bind f).bind g = l.bind (λ x, (f x).bind g) := by induction l; simp * /-! ### 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 α) := reverse_reverse @[simp] theorem reverse_injective : injective (@reverse α) := reverse_involutive.injective theorem reverse_surjective : surjective (@reverse α) := reverse_involutive.surjective theorem reverse_bijective : bijective (@reverse α) := reverse_involutive.bijective @[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 : l ≠ nil), last (a :: l) (cons_ne_nil a l) = last l h := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append_singleton {a : α} (l : list α) : last (l ++ [a]) (append_ne_nil_of_ne_nil_right l _ (cons_ne_nil a _)) = a := by induction l; [refl, simp only [cons_append, last_cons (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_append (l₁ l₂ : list α) (h : l₂ ≠ []) : last (l₁ ++ l₂) (append_ne_nil_of_ne_nil_right l₁ l₂ h) = last l₂ h := begin induction l₁ with _ _ ih, { simp }, { simp only [cons_append], rw list.last_cons, exact ih }, end theorem last_concat {a : α} (l : list α) : last (concat l a) (concat_ne_nil a l) = a := by simp only [concat_eq_append, last_append_singleton] @[simp] theorem last_singleton (a : α) : last [a] (cons_ne_nil a []) = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) : last (a₁::a₂::l) (cons_ne_nil _ _) = 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 _ _)], 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 last'_eq_last_of_ne_nil : ∀ {l : list α} (h : l ≠ []), l.last' = some (l.last h) | [] h := (h rfl).elim | [a] _ := by {unfold last, unfold last'} | (a::b::l) _ := @last'_eq_last_of_ne_nil (b::l) (cons_ne_nil _ _) theorem mem_last'_cons {x y : α} : ∀ {l : list α} (h : x ∈ l.last'), x ∈ (y :: l).last' | [] _ := by contradiction | (a::l) h := h 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] @[simp] theorem last'_cons_cons (x y : α) (l : list α) : last' (x :: y :: l) = last' (y :: l) := rfl 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₂ theorem last'_append {l₁ l₂ : list α} {x : α} (h : x ∈ l₂.last') : x ∈ (l₁ ++ l₂).last' := by { cases l₂, { contradiction, }, { rw list.last'_append_cons, exact h } } /-! ### 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 head'_append {s t : list α} {x : α} (h : x ∈ s.head') : x ∈ (s ++ t).head' := by { cases s, contradiction, exact h } theorem head'_append_of_ne_nil : ∀ (l₁ : list α) {l₂ : list α} (hl₁ : l₁ ≠ []), head' (l₁ ++ l₂) = head' l₁ | [] _ hl₁ := by contradiction | (x::l₁) _ _ := rfl 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 @[simp] lemma nth_le_tail (l : list α) (i) (h : i < l.tail.length) (h' : i + 1 < l.length := by simpa [←lt_tsub_iff_right] using h) : l.tail.nth_le i h = l.nth_le (i + 1) h' := begin cases l, { cases h, }, { simpa } end lemma nth_le_cons_aux {l : list α} {a : α} {n} (hn : n ≠ 0) (h : n < (a :: l).length) : n - 1 < l.length := begin contrapose! h, rw length_cons, convert succ_le_succ h, exact (nat.succ_pred_eq_of_pos hn.bot_lt).symm end lemma nth_le_cons {l : list α} {a : α} {n} (hl) : (a :: l).nth_le n hl = if hn : n = 0 then a else l.nth_le (n - 1) (nth_le_cons_aux hn hl) := begin split_ifs, { simp [nth_le, h] }, cases l, { rw [length_singleton, nat.lt_one_iff] at hl, contradiction }, cases n, { contradiction }, refl end @[simp] lemma modify_head_modify_head (l : list α) (f g : α → α) : (l.modify_head f).modify_head g = l.modify_head (g ∘ f) := by cases l; simp /-! ### 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 sublist.cons_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₂ := (sublist_append_left l₁ l₂).cons_cons _ @[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, sublist.cons_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 ih.cons_cons a } 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 (sublist.cons_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 @[simp] 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 ▸ ((nil_sublist _).cons_cons _ ).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ s.subset @[simp] theorem sublist_nil_iff_eq_nil {l : list α} : l <+ [] ↔ l = [] := ⟨eq_nil_of_sublist_nil, λ H, H ▸ sublist.refl _⟩ @[simp] 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 ⟨sublist.cons_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) @[simp] theorem nth_length (l : list α) : l.nth l.length = none := nth_len_le le_rfl 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₂ := (nat.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₂, apply lt_of_add_lt_add_right, rwa [nat.sub_add_cancel h₁, nat.add_comm], 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.add_sub_add_right], }, 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 nat.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 le_tsub_of_add_le_left hl } end lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []), last l h = l.nth_le (l.length - 1) (nat.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 (nat.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 ← tsub_add_eq_tsub_tsub, 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 nth_le_eq_iff {l : list α} {n : ℕ} {x : α} {h} : l.nth_le n h = x ↔ l.nth n = some x := by { rw nth_eq_some, tauto } lemma some_nth_le_eq {l : list α} {n : ℕ} {h} : some (l.nth_le n h) = l.nth n := by { symmetry, rw nth_eq_some, tauto } 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 exists_add_of_le h with ⟨m, rfl⟩, rw [add_tsub_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), tsub_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_zero (s : list α) (x : α) : insert_nth 0 x s = x :: s := rfl @[simp] lemma insert_nth_succ_nil (n : ℕ) (a : α) : insert_nth (n + 1) a [] = [] := rfl @[simp] lemma insert_nth_succ_cons (s : list α) (hd x : α) (n : ℕ) : insert_nth (n + 1) x (hd :: s) = hd :: (insert_nth n x s) := 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 [mem_insert_nth (nat.le_of_succ_le_succ h), ← or.assoc, or_comm (a = a'), or.assoc] end lemma inj_on_insert_nth_index_of_not_mem (l : list α) (x : α) (hx : x ∉ l) : set.inj_on (λ k, insert_nth k x l) {n | n ≤ l.length} := begin induction l with hd tl IH, { intros n hn m hm h, simp only [set.mem_singleton_iff, set.set_of_eq_eq_singleton, length, nonpos_iff_eq_zero] at hn hm, simp [hn, hm] }, { intros n hn m hm h, simp only [length, set.mem_set_of_eq] at hn hm, simp only [mem_cons_iff, not_or_distrib] at hx, cases n; cases m, { refl }, { simpa [hx.left] using h }, { simpa [ne.symm hx.left] using h }, { simp only [true_and, eq_self_iff_true, insert_nth_succ_cons] at h, rw nat.succ_inj', refine IH hx.right _ _ h, { simpa [nat.succ_le_succ_iff] using hn }, { simpa [nat.succ_le_succ_iff] using hm } } } end lemma insert_nth_of_length_lt (l : list α) (x : α) (n : ℕ) (h : l.length < n) : insert_nth n x l = l := begin induction l with hd tl IH generalizing n, { cases n, { simpa using h }, { simp } }, { cases n, { simpa using h }, { simp only [nat.succ_lt_succ_iff, length] at h, simpa using IH _ h } } end @[simp] lemma insert_nth_length_self (l : list α) (x : α) : insert_nth l.length x l = l ++ [x] := begin induction l with hd tl IH, { simp }, { simpa using IH } end lemma length_le_length_insert_nth (l : list α) (x : α) (n : ℕ) : l.length ≤ (insert_nth n x l).length := begin cases le_or_lt n l.length with hn hn, { rw length_insert_nth _ _ hn, exact (nat.lt_succ_self _).le }, { rw insert_nth_of_length_lt _ _ _ hn } end lemma length_insert_nth_le_succ (l : list α) (x : α) (n : ℕ) : (insert_nth n x l).length ≤ l.length + 1 := begin cases le_or_lt n l.length with hn hn, { rw length_insert_nth _ _ hn }, { rw insert_nth_of_length_lt _ _ _ hn, exact (nat.lt_succ_self _).le } end lemma nth_le_insert_nth_of_lt (l : list α) (x : α) (n k : ℕ) (hn : k < n) (hk : k < l.length) (hk' : k < (insert_nth n x l).length := hk.trans_le (length_le_length_insert_nth _ _ _)): (insert_nth n x l).nth_le k hk' = l.nth_le k hk := begin induction n with n IH generalizing k l, { simpa using hn }, { cases l with hd tl, { simp }, { cases k, { simp }, { rw nat.succ_lt_succ_iff at hn, simpa using IH _ _ hn _ } } } end @[simp] lemma nth_le_insert_nth_self (l : list α) (x : α) (n : ℕ) (hn : n ≤ l.length) (hn' : n < (insert_nth n x l).length := by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff]) : (insert_nth n x l).nth_le n hn' = x := begin induction l with hd tl IH generalizing n, { simp only [length, nonpos_iff_eq_zero] at hn, simp [hn] }, { cases n, { simp }, { simp only [nat.succ_le_succ_iff, length] at hn, simpa using IH _ hn } } end lemma nth_le_insert_nth_add_succ (l : list α) (x : α) (n k : ℕ) (hk' : n + k < l.length) (hk : n + k + 1 < (insert_nth n x l).length := by rwa [length_insert_nth _ _ (le_self_add.trans hk'.le), nat.succ_lt_succ_iff]) : (insert_nth n x l).nth_le (n + k + 1) hk = nth_le l (n + k) hk' := begin induction l with hd tl IH generalizing n k, { simpa using hk' }, { cases n, { simpa }, { simpa [succ_add] using IH _ _ _ } } end lemma insert_nth_injective (n : ℕ) (x : α) : function.injective (insert_nth n x) := begin induction n with n IH, { have : insert_nth 0 x = cons x := funext (λ _, rfl), simp [this] }, { rintros (_|⟨a, as⟩) (_|⟨b, bs⟩) h; simpa [IH.eq_iff] using h <|> refl } 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 @[simp] theorem map_id'' (l : list α) : map (λ x, x) l = l := map_id _ theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by simp [show f = id, from funext h] 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 lemma bind_congr {l : list α} {f g : α → list β} (h : ∀ x ∈ l, f x = g x) : list.bind l f = list.bind l g := (congr_arg list.join $ map_congr h : _) @[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], } /-- Taking the first `n` elements in `l₁ ++ l₂` is the same as appending the first `n` elements of `l₁` to the first `n - l₁.length` elements of `l₂`. -/ lemma take_append_eq_append_take {l₁ l₂ : list α} {n : ℕ} : take n (l₁ ++ l₂) = take n l₁ ++ take (n - l₁.length) l₂ := begin induction l₁ generalizing n, { simp }, cases n, { simp }, simp * end lemma take_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) : (l₁ ++ l₂).take n = l₁.take n := by simp [take_append_eq_append_take, tsub_eq_zero_iff_le.mpr h] /-- 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₂) := by simp [take_append_eq_append_take, take_all_of_le le_self_add] /-- 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 init_cons_of_ne_nil {α : Type*} {x : α} : ∀ {l : list α} (h : l ≠ []), (x :: l).init = x :: l.init | [] h := false.elim (h rfl) | (a :: l) _ := by simp [init] @[simp] lemma init_append_of_ne_nil {α : Type*} {l : list α} : ∀ (l' : list α) (h : l ≠ []), (l' ++ l).init = l' ++ l.init | [] _ := by simp only [nil_append] | (a :: l') h := by simp [append_ne_nil_of_ne_nil_right l' l h, init_append_of_ne_nil l' h] @[simp] lemma drop_eq_nil_of_le {l : list α} {k : ℕ} (h : l.length ≤ k) : l.drop k = [] := by simpa [←length_eq_zero] using tsub_eq_zero_iff_le.mpr 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 _) @[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 _ _ /-- Dropping the elements up to `n` in `l₁ ++ l₂` is the same as dropping the elements up to `n` in `l₁`, dropping the elements up to `n - l₁.length` in `l₂`, and appending them. -/ lemma drop_append_eq_append_drop {l₁ l₂ : list α} {n : ℕ} : drop n (l₁ ++ l₂) = drop n l₁ ++ drop (n - l₁.length) l₂ := begin induction l₁ generalizing n, { simp }, cases n, { simp }, simp * end lemma drop_append_of_le_length {l₁ l₂ : list α} {n : ℕ} (h : n ≤ l₁.length) : (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ := by simp [drop_append_eq_append_drop, tsub_eq_zero_iff_le.mpr h] /-- 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₂ := by simp [drop_append_eq_append_drop, take_all_of_le le_self_add] lemma drop_sizeof_le [has_sizeof α] (l : list α) : ∀ (n : ℕ), (l.drop n).sizeof ≤ l.sizeof := begin induction l with _ _ lih; intro n, { rw [drop_nil] }, { induction n with n nih, { refl, }, { exact trans (lih _) le_add_self } } 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) (lt_tsub_iff_left.mp ((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 [lt_tsub_iff_left] 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, zero_tsub, 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, ← tsub_add_eq_add_tsub] }, { rwa length_reverse } }, { subst h', rw [length, tsub_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₂] theorem foldl_fixed' {f : α → β → α} {a : α} (hf : ∀ b, f a b = a) : Π l : list β, foldl f a l = a | [] := rfl | (b::l) := by rw [foldl_cons, hf b, foldl_fixed' l] theorem foldr_fixed' {f : α → β → β} {b : β} (hf : ∀ a, f a b = b) : Π l : list α, foldr f b l = b | [] := rfl | (a::l) := by rw [foldr_cons, foldr_fixed' l, hf a] @[simp] theorem foldl_fixed {a : α} : Π l : list β, foldl (λ a b, a) a l = a := foldl_fixed' (λ _, rfl) @[simp] theorem foldr_fixed {b : β} : Π l : list α, foldr (λ a b, b) b l = b := foldr_fixed' (λ _, rfl) @[simp] theorem foldl_combinator_K {a : α} : Π l : list β, foldl combinator.K a l = a := foldl_fixed @[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 foldl_hom₂ (l : list ι) (f : α → β → γ) (op₁ : α → ι → α) (op₂ : β → ι → β) (op₃ : γ → ι → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ a i) (op₂ b i) = op₃ (f a b) i) : foldl op₃ (f a b) l = f (foldl op₁ a l) (foldl op₂ b l) := eq.symm $ by { revert a b, induction l; intros; [refl, simp only [*, foldl]] } lemma foldr_hom₂ (l : list ι) (f : α → β → γ) (op₁ : ι → α → α) (op₂ : ι → β → β) (op₃ : ι → γ → γ) (a : α) (b : β) (h : ∀ a b i, f (op₁ i a) (op₂ i b) = op₃ i (f a b)) : foldr op₃ (f a b) l = f (foldr op₁ a l) (foldr op₂ b 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 (name := op) a ` * ` b := op a b local notation (name := foldl) 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 functor_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, is_lawful_monad.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, is_lawful_monad.bind_assoc] end mfoldl_mfoldr /-! ### intersperse -/ @[simp] lemma intersperse_nil {α : Type u} (a : α) : intersperse a [] = [] := rfl @[simp] lemma intersperse_singleton {α : Type u} (a b : α) : intersperse a [b] = [b] := rfl @[simp] lemma intersperse_cons_cons {α : Type u} (a b c : α) (tl : list α) : intersperse a (b :: c :: tl) = b :: a :: intersperse a (c :: tl) := rfl /-! ### split_at and split_on -/ section split_at_on variables (p : α → Prop) [decidable_pred p] (xs ys : list α) (ls : list (list α)) (f : list α → list α) @[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] lemma split_on_nil {α : Type u} [decidable_eq α] (a : α) : [].split_on a = [[]] := rfl @[simp] lemma split_on_p_nil : [].split_on_p p = [[]] := rfl /-- An auxiliary definition for proving a specification lemma for `split_on_p`. `split_on_p_aux' P xs ys` splits the list `ys ++ xs` at every element satisfying `P`, where `ys` is an accumulating parameter for the initial segment of elements not satisfying `P`. -/ def split_on_p_aux' {α : Type u} (P : α → Prop) [decidable_pred P] : list α → list α → list (list α) | [] xs := [xs] | (h :: t) xs := if P h then xs :: split_on_p_aux' t [] else split_on_p_aux' t (xs ++ [h]) lemma split_on_p_aux_eq : split_on_p_aux' p xs ys = split_on_p_aux p xs ((++) ys) := begin induction xs with a t ih generalizing ys; simp! only [append_nil, eq_self_iff_true, and_self], split_ifs; rw ih, { refine ⟨rfl, rfl⟩ }, { congr, ext, simp } end lemma split_on_p_aux_nil : split_on_p_aux p xs id = split_on_p_aux' p xs [] := by { rw split_on_p_aux_eq, refl } /-- The original list `L` can be recovered by joining the lists produced by `split_on_p p L`, interspersed with the elements `L.filter p`. -/ lemma split_on_p_spec (as : list α) : join (zip_with (++) (split_on_p p as) ((as.filter p).map (λ x, [x]) ++ [[]])) = as := begin rw [split_on_p, split_on_p_aux_nil], suffices : ∀ xs, join (zip_with (++) (split_on_p_aux' p as xs) ((as.filter p).map(λ x, [x]) ++ [[]])) = xs ++ as, { rw this, refl }, induction as; intro; simp! only [split_on_p_aux', append_nil], split_ifs; simp [zip_with, join, *], end lemma split_on_p_aux_ne_nil : split_on_p_aux p xs f ≠ [] := begin induction xs with _ _ ih generalizing f, { trivial, }, simp only [split_on_p_aux], split_ifs, { trivial, }, exact ih _, end lemma split_on_p_aux_spec : split_on_p_aux p xs f = (xs.split_on_p p).modify_head f := begin simp only [split_on_p], induction xs with hd tl ih generalizing f, { simp [split_on_p_aux], }, simp only [split_on_p_aux], split_ifs, { simp, }, rw [ih (λ l, f (hd :: l)), ih (λ l, id (hd :: l))], simp, end lemma split_on_p_ne_nil : xs.split_on_p p ≠ [] := split_on_p_aux_ne_nil _ _ id @[simp] lemma split_on_p_cons (x : α) (xs : list α) : (x :: xs).split_on_p p = if p x then [] :: xs.split_on_p p else (xs.split_on_p p).modify_head (cons x) := by { simp only [split_on_p, split_on_p_aux], split_ifs, { simp }, rw split_on_p_aux_spec, refl, } /-- If no element satisfies `p` in the list `xs`, then `xs.split_on_p p = [xs]` -/ lemma split_on_p_eq_single (h : ∀ x ∈ xs, ¬p x) : xs.split_on_p p = [xs] := by { induction xs with hd tl ih, { refl, }, simp [h hd _, ih (λ t ht, h t (or.inr ht))], } /-- When a list of the form `[...xs, sep, ...as]` is split on `p`, the first element is `xs`, assuming no element in `xs` satisfies `p` but `sep` does satisfy `p` -/ lemma split_on_p_first (h : ∀ x ∈ xs, ¬p x) (sep : α) (hsep : p sep) (as : list α) : (xs ++ sep :: as).split_on_p p = xs :: as.split_on_p p := by { induction xs with hd tl ih, { simp [hsep], }, simp [h hd _, ih (λ t ht, h t (or.inr ht))], } /-- `intercalate [x]` is the left inverse of `split_on x` -/ lemma intercalate_split_on (x : α) [decidable_eq α] : [x].intercalate (xs.split_on x) = xs := begin simp only [intercalate, split_on], induction xs with hd tl ih, { simp [join], }, simp only [split_on_p_cons], cases h' : split_on_p (=x) tl with hd' tl', { exact (split_on_p_ne_nil _ tl h').elim, }, rw h' at ih, split_ifs, { subst h, simp [ih, join], }, cases tl'; simpa [join] using ih, end /-- `split_on x` is the left inverse of `intercalate [x]`, on the domain consisting of each nonempty list of lists `ls` whose elements do not contain `x` -/ lemma split_on_intercalate [decidable_eq α] (x : α) (hx : ∀ l ∈ ls, x ∉ l) (hls : ls ≠ []) : ([x].intercalate ls).split_on x = ls := begin simp only [intercalate], induction ls with hd tl ih, { contradiction, }, cases tl, { suffices : hd.split_on x = [hd], { simpa [join], }, refine split_on_p_eq_single _ _ _, intros y hy H, rw H at hy, refine hx hd _ hy, simp, }, { simp only [intersperse_cons_cons, singleton_append, join], specialize ih _ _, { intros l hl, apply hx l, simp at hl ⊢, tauto, }, { trivial, }, have := split_on_p_first (=x) hd _ x rfl _, { simp only [split_on] at ⊢ ih, rw this, rw ih, }, intros y hy H, rw H at hy, exact hx hd (or.inl rfl) hy, } end end split_at_on /-! ### 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 @[simp] 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 ∈ l) h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := begin induction l with _ _ ih, { refl, }, { rw [pmap, pmap, h _ (mem_cons_self _ _), ih (λ a ha, h a (mem_cons_of_mem _ ha))], }, end 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 (λ _ _ _ _, 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 lemma pmap_append {p : ι → Prop} (f : Π (a : ι), p a → α) (l₁ l₂ : list ι) (h : ∀ a ∈ l₁ ++ l₂, p a) : (l₁ ++ l₂).pmap f h = l₁.pmap f (λ a ha, h a (mem_append_left l₂ ha)) ++ l₂.pmap f (λ a ha, h a (mem_append_right l₁ ha)) := begin induction l₁ with _ _ ih, { refl, }, { dsimp only [pmap, cons_append], rw ih, } end lemma pmap_append' {α β : Type*} {p : α → Prop} (f : Π (a : α), p a → β) (l₁ l₂ : list α) (h₁ : ∀ a ∈ l₁, p a) (h₂ : ∀ a ∈ l₂, p a) : (l₁ ++ l₂).pmap f (λ a ha, (list.mem_append.1 ha).elim (h₁ a) (h₂ a)) = l₁.pmap f h₁ ++ l₂.pmap f h₂ := pmap_append f l₁ l₂ _ /-! ### 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 theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end 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 theorem map_filter_map_some_eq_filter_map_is_some (f : α → option β) (l : list α) : (l.filter_map f).map some = (l.map f).filter (λ b, b.is_some) := begin induction l with x xs ih, { simp }, { cases h : f x; rw [list.filter_map_cons, h]; simp [h, ih] }, end @[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 @[simp] theorem filter_map_join (f : α → option β) (L : list (list α)) : filter_map f (join L) = join (map (filter_map f) L) := begin induction L with hd tl ih, { refl }, { rw [map, join, join, filter_map_append, ih] }, 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 length_filter_le (p : α → Prop) [decidable_pred p] (l : list α) : (l.filter p).length ≤ l.length := list.length_le_of_sublist (list.filter_sublist _) theorem length_filter_map_le (f : α → option β) (l : list α) : (list.filter_map f l).length ≤ l.length := begin rw [← list.length_map some, list.map_filter_map_some_eq_filter_map_is_some, ← list.length_map f], apply list.length_filter_le, end 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] lemma filter_singleton {a : α} : [a].filter p = if p a then [a] else [] := rfl 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₂⟩ lemma monotone_filter_left (p : α → Prop) [decidable_pred p] ⦃l l' : list α⦄ (h : l ⊆ l') : filter p l ⊆ filter p l' := begin intros x hx, rw [mem_filter] at hx ⊢, exact ⟨h hx.left, hx.right⟩ end 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_length_eq_length {l} : (filter p l).length = l.length ↔ ∀ a ∈ l, p a := iff.trans ⟨eq_of_sublist_of_length_eq l.filter_sublist, congr_arg list.length⟩ filter_eq_self 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 sublist.filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := filter_map_eq_filter p ▸ s.filter_map _ lemma monotone_filter_right (l : list α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : l.filter p <+ l.filter q := begin induction l with hd tl IH, { refl }, { by_cases hp : p hd, { rw [filter_cons_of_pos _ hp, filter_cons_of_pos _ (h _ hp)], exact IH.cons_cons hd }, { rw filter_cons_of_neg _ hp, by_cases hq : q hd, { rw filter_cons_of_pos _ hq, exact sublist_cons_of_sublist hd IH }, { rw filter_cons_of_neg _ hq, exact IH } } } end 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] lemma drop_while_nth_le_zero_not (l : list α) (hl : 0 < (l.drop_while p).length) : ¬ p ((l.drop_while p).nth_le 0 hl) := begin induction l with hd tl IH, { cases hl }, { simp only [drop_while], split_ifs with hp, { exact IH _ }, { simpa using hp } } end variables {p} {l : list α} @[simp] lemma drop_while_eq_nil_iff : drop_while p l = [] ↔ ∀ x ∈ l, p x := begin induction l with x xs IH, { simp [drop_while] }, { by_cases hp : p x; simp [hp, drop_while, IH] } end @[simp] lemma take_while_eq_self_iff : take_while p l = l ↔ ∀ x ∈ l, p x := begin induction l with x xs IH, { simp [take_while] }, { by_cases hp : p x; simp [hp, take_while, IH] } end @[simp] lemma take_while_eq_nil_iff : take_while p l = [] ↔ ∀ (hl : 0 < l.length), ¬ p (l.nth_le 0 hl) := begin induction l with x xs IH, { simp }, { by_cases hp : p x; simp [hp, take_while, IH] } end lemma mem_take_while_imp {x : α} (hx : x ∈ take_while p l) : p x := begin induction l with hd tl IH, { simpa [take_while] using hx }, { simp only [take_while] at hx, split_ifs at hx, { rw mem_cons_iff at hx, rcases hx with rfl|hx, { exact h }, { exact IH hx } }, { simpa using hx } } end lemma take_while_take_while (p q : α → Prop) [decidable_pred p] [decidable_pred q] (l : list α) : take_while p (take_while q l) = take_while (λ a, p a ∧ q a) l := begin induction l with hd tl IH, { simp [take_while] }, { by_cases hp : p hd; by_cases hq : q hd; simp [take_while, hp, hq, IH] } end lemma take_while_idem : take_while p (take_while p l) = take_while p l := by simp_rw [take_while_take_while, and_self] end filter /-! ### 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 @[simp] lemma length_erasep_add_one {l : list α} {a} (al : a ∈ l) (pa : p a) : (l.erasep p).length + 1 = l.length := let ⟨_, l₁, l₂, _, _, h₁, h₂⟩ := exists_of_erasep al pa in by { rw [h₂, h₁, length_append, length_append], 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 @[simp] lemma length_erase_add_one {a : α} {l : list α} (h : a ∈ l) : (l.erase a).length + 1 = l.length := by rw [erase_eq_erasep, length_erasep_add_one 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) := have this : eq a = eq (f a) ∘ f, { ext b, simp [finj.eq_iff] }, by simp [erase_eq_erasep, erase_eq_erasep, erasep_map, this] 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, *]] 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 _)]] lemma cons_diff (a : α) (l₁ l₂ : list α) : (a :: l₁).diff l₂ = if a ∈ l₂ then l₁.diff (l₂.erase a) else a :: l₁.diff l₂ := begin induction l₂ with b l₂ ih, { refl }, rcases eq_or_ne a b with rfl|hne, { simp }, { simp only [mem_cons_iff, *, false_or, diff_cons_right], split_ifs with h₂; simp [diff_erase, list.erase, hne, hne.symm] } end lemma cons_diff_of_mem {a : α} {l₂ : list α} (h : a ∈ l₂) (l₁ : list α) : (a :: l₁).diff l₂ = l₁.diff (l₂.erase a) := by rw [cons_diff, if_pos h] lemma cons_diff_of_not_mem {a : α} {l₂ : list α} (h : a ∉ l₂) (l₁ : list α) : (a :: l₁).diff l₂ = a :: l₁.diff l₂ := by rw [cons_diff, if_neg 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 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 @[simp] lemma enum_nil : enum ([] : list α) = [] := rfl @[simp] lemma enum_from_nil (n : ℕ) : enum_from n ([] : list α) = [] := rfl @[simp] lemma enum_from_cons (x : α) (xs : list α) (n : ℕ) : enum_from n (x :: xs) = (n, x) :: enum_from (n + 1) xs := rfl @[simp] lemma enum_cons (x : α) (xs : list α) : enum (x :: xs) = (0, x) :: enum_from 1 xs := rfl @[simp] lemma enum_from_singleton (x : α) (n : ℕ) : enum_from n [x] = [(n, x)] := rfl @[simp] lemma enum_singleton (x : α) : enum [x] = [(0, x)] := rfl lemma enum_from_append (xs ys : list α) (n : ℕ) : enum_from n (xs ++ ys) = enum_from n xs ++ enum_from (n + xs.length) ys := begin induction xs with x xs IH generalizing ys n, { simp }, { rw [cons_append, enum_from_cons, IH, ←cons_append, ←enum_from_cons, length, add_right_comm, add_assoc] } end lemma enum_append (xs ys : list α) : enum (xs ++ ys) = enum xs ++ enum_from xs.length ys := by simp [enum, enum_from_append] lemma map_fst_add_enum_from_eq_enum_from (l : list α) (n k : ℕ) : map (prod.map (+ n) id) (enum_from k l) = enum_from (n + k) l := begin induction l with hd tl IH generalizing n k, { simp [enum_from] }, { simp only [enum_from, map, zero_add, prod.map_mk, id.def, eq_self_iff_true, true_and], simp [IH, add_comm n k, add_assoc, add_left_comm] } end lemma map_fst_add_enum_eq_enum_from (l : list α) (n : ℕ) : map (prod.map (+ n) id) (enum l) = enum_from n l := map_fst_add_enum_from_eq_enum_from l _ _ lemma nth_le_enum_from (l : list α) (n i : ℕ) (hi' : i < (l.enum_from n).length) (hi : i < l.length := by simpa [length_enum_from] using hi') : (l.enum_from n).nth_le i hi' = (n + i, l.nth_le i hi) := begin rw [←option.some_inj, ←nth_le_nth], simp [enum_from_nth, nth_le_nth hi] end lemma nth_le_enum (l : list α) (i : ℕ) (hi' : i < l.enum.length) (hi : i < l.length := by simpa [length_enum] using hi') : l.enum.nth_le i hi' = (i, l.nth_le i hi) := by { convert nth_le_enum_from _ _ _ hi', exact (zero_add _).symm } 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 tsub_lt_self (length_pos_iff_ne_nil.2 x0) (succ_pos _) }, end end to_chunks /-! ### all₂ -/ section all₂ variables {p q : α → Prop} {l : list α} @[simp] lemma all₂_cons (p : α → Prop) (x : α) : ∀ (l : list α), all₂ p (x :: l) ↔ p x ∧ all₂ p l | [] := (and_true _).symm | (x :: l) := iff.rfl lemma all₂_iff_forall : ∀ {l : list α}, all₂ p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ ball_nil _).symm | (x :: l) := by rw [ball_cons, all₂_cons, all₂_iff_forall] lemma all₂.imp (h : ∀ x, p x → q x) : ∀ {l : list α}, all₂ p l → all₂ q l | [] := id | (x :: l) := by simpa using and.imp (h x) all₂.imp @[simp] lemma all₂_map_iff {p : β → Prop} (f : α → β) : all₂ p (l.map f) ↔ all₂ (p ∘ f) l := by induction l; simp * instance (p : α → Prop) [decidable_pred p] : decidable_pred (all₂ p) := λ l, decidable_of_iff' _ all₂_iff_forall end all₂ /-! ### Retroattributes The list definitions happen earlier than `to_additive`, so here we tag the few multiplicative definitions that couldn't be tagged earlier. -/ attribute [to_additive] list.prod -- `list.sum` attribute [to_additive] alternating_prod -- `list.alternating_sum` /-! ### Miscellaneous lemmas -/ lemma last_reverse {l : list α} (hl : l.reverse ≠ []) (hl' : 0 < l.length := by { contrapose! hl, simpa [length_eq_zero] using hl }) : l.reverse.last hl = l.nth_le 0 hl' := begin rw [last_eq_nth_le, nth_le_reverse'], { simp, }, { simpa using hl' } end 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 @[simp] theorem mem_map_swap (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, }, { unfold_wf, apply xs_ih _ _ h, apply lt_of_succ_lt_succ hi, } }, end /-! ### nthd and inth -/ section nthd variables (l : list α) (x : α) (xs : list α) (d : α) (n : ℕ) @[simp] lemma nthd_nil : nthd d [] n = d := rfl @[simp] lemma nthd_cons_zero : nthd d (x::xs) 0 = x := rfl @[simp] lemma nthd_cons_succ : nthd d (x::xs) (n + 1) = nthd d xs n := rfl lemma nthd_eq_nth_le {n : ℕ} (hn : n < l.length) : l.nthd d n = l.nth_le n hn := begin induction l with hd tl IH generalizing n, { exact absurd hn (not_lt_of_ge (nat.zero_le _)) }, { cases n, { exact nthd_cons_zero _ _ _ }, { exact IH _ } } end lemma nthd_eq_default {n : ℕ} (hn : l.length ≤ n) : l.nthd d n = d := begin induction l with hd tl IH generalizing n, { exact nthd_nil _ _ }, { cases n, { refine absurd (nat.zero_lt_succ _) (not_lt_of_ge hn) }, { exact IH (nat.le_of_succ_le_succ hn) } } end /-- An empty list can always be decidably checked for the presence of an element. Not an instance because it would clash with `decidable_eq α`. -/ def decidable_nthd_nil_ne {α} (a : α) : decidable_pred (λ (i : ℕ), nthd a ([] : list α) i ≠ a) := λ i, is_false $ λ H, H (nthd_nil _ _) @[simp] lemma nthd_singleton_default_eq (n : ℕ) : [d].nthd d n = d := by { cases n; simp } @[simp] lemma nthd_repeat_default_eq (r n : ℕ) : (repeat d r).nthd d n = d := begin induction r with r IH generalizing n, { simp }, { cases n; simp [IH] } end lemma nthd_append (l l' : list α) (d : α) (n : ℕ) (h : n < l.length) (h' : n < (l ++ l').length := h.trans_le ((length_append l l').symm ▸ le_self_add)) : (l ++ l').nthd d n = l.nthd d n := by rw [nthd_eq_nth_le _ _ h', nth_le_append h' h, nthd_eq_nth_le] lemma nthd_append_right (l l' : list α) (d : α) (n : ℕ) (h : l.length ≤ n) : (l ++ l').nthd d n = l'.nthd d (n - l.length) := begin cases lt_or_le _ _ with h' h', { rw [nthd_eq_nth_le _ _ h', nth_le_append_right h h', nthd_eq_nth_le] }, { rw [nthd_eq_default _ _ h', nthd_eq_default], rwa [le_tsub_iff_left h, ←length_append] } end lemma nthd_eq_get_or_else_nth (n : ℕ) : l.nthd d n = (l.nth n).get_or_else d := begin cases lt_or_le _ _ with h h, { rw [nthd_eq_nth_le _ _ h, nth_le_nth h, option.get_or_else_some] }, { rw [nthd_eq_default _ _ h, nth_eq_none_iff.mpr h, option.get_or_else_none] } end end nthd section inth variables [inhabited α] (l : list α) (x : α) (xs : list α) (n : ℕ) @[simp] lemma inth_nil : inth ([] : list α) n = default := rfl @[simp] lemma inth_cons_zero : inth (x::xs) 0 = x := rfl @[simp] lemma inth_cons_succ : inth (x::xs) (n + 1) = inth xs n := rfl lemma inth_eq_nth_le {n : ℕ} (hn : n < l.length) : l.inth n = l.nth_le n hn := nthd_eq_nth_le _ _ _ lemma inth_eq_default {n : ℕ} (hn : l.length ≤ n) : l.inth n = default := nthd_eq_default _ _ hn lemma nthd_default_eq_inth : l.nthd default = l.inth := rfl lemma inth_append (l l' : list α) (n : ℕ) (h : n < l.length) (h' : n < (l ++ l').length := h.trans_le ((length_append l l').symm ▸ le_self_add)) : (l ++ l').inth n = l.inth n := nthd_append _ _ _ _ h h' lemma inth_append_right (l l' : list α) (n : ℕ) (h : l.length ≤ n) : (l ++ l').inth n = l'.inth (n - l.length) := nthd_append_right _ _ _ _ h lemma inth_eq_iget_nth (n : ℕ) : l.inth n = (l.nth n).iget := by rw [←nthd_default_eq_inth, nthd_eq_get_or_else_nth, option.get_or_else_default_eq_iget] lemma inth_zero_eq_head : l.inth 0 = l.head := by { cases l; refl, } end inth end list
b961790939f735cec85aca9539816971cd12ce80
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/ParserCompiler.lean
5a5440d80351c3d2aceb27a152efabb3ff486e0c
[ "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
7,557
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Util.ReplaceExpr import Lean.Meta.Basic import Lean.Meta.ReduceEval import Lean.Meta.WHNF import Lean.ParserCompiler.Attribute import Lean.Parser.Extension /-! Gadgets for compiling parser declarations into other programs, such as pretty printers. -/ namespace Lean namespace ParserCompiler structure Context (α : Type) where varName : Name categoryAttr : KeyedDeclsAttribute α combinatorAttr : CombinatorAttribute def Context.tyName {α} (ctx : Context α) : Name := ctx.categoryAttr.defn.valueTypeName /-- Replace all references of `Parser` with `tyName` -/ def replaceParserTy {α} (ctx : Context α) (e : Expr) : Expr := e.replace fun e => -- strip `optParam` let e := if e.isOptParam then e.appFn!.appArg! else e if e.isConstOf `Lean.Parser.Parser then mkConst ctx.tyName else none open Meta Parser in /-- Takes an expression of type `Parser`, and determines the syntax kind of the root node it produces. -/ partial def parserNodeKind? (e : Expr) : MetaM (Option Name) := do let reduceEval? e : MetaM (Option Name) := do try pure <| some (← reduceEval e) catch _ => pure none let e ← whnfCore e if e matches Expr.lam .. then lambdaLetTelescope e fun _ e => parserNodeKind? e else if e.isAppOfArity ``nodeWithAntiquot 4 then reduceEval? (e.getArg! 1) else if e.isAppOfArity ``withAntiquot 2 then parserNodeKind? (e.getArg! 1) else if e.isAppOfArity ``leadingNode 3 || e.isAppOfArity ``trailingNode 4 || e.isAppOfArity ``node 2 then reduceEval? (e.getArg! 0) else return none section open Meta variable {α} (ctx : Context α) (builtin : Bool) (force : Bool) in /-- Translate an expression of type `Parser` into one of type `tyName`, tagging intermediary constants with `ctx.combinatorAttr`. If `force` is `false`, refuse to do so for imported constants. -/ partial def compileParserExpr (e : Expr) : MetaM Expr := do let e ← whnfCore e match e with | .lam .. => lambdaLetTelescope e fun xs b => compileParserExpr b >>= mkLambdaFVars xs | .fvar .. => return e | _ => do let fn := e.getAppFn let .const c .. := fn | throwError "call of unknown parser at '{e}'" -- call the translated `p` with (a prefix of) the arguments of `e`, recursing for arguments -- of type `ty` (i.e. formerly `Parser`) let mkCall (p : Name) := do let ty ← inferType (mkConst p) forallTelescope ty fun params _ => do let mut p := mkConst p let args := e.getAppArgs for i in [:Nat.min params.size args.size] do let param := params[i]! let arg := args[i]! let paramTy ← inferType param let resultTy ← forallTelescope paramTy fun _ b => pure b let arg ← if resultTy.isConstOf ctx.tyName then compileParserExpr arg else pure arg p := mkApp p arg return p let env ← getEnv match ctx.combinatorAttr.getDeclFor? env c with | some p => mkCall p | none => let c' := c ++ ctx.varName let cinfo ← getConstInfo c let resultTy ← forallTelescope cinfo.type fun _ b => pure b if resultTy.isConstOf `Lean.Parser.TrailingParser || resultTy.isConstOf `Lean.Parser.Parser then do -- synthesize a new `[combinatorAttr c]` let some value ← pure cinfo.value? | throwError "don't know how to generate {ctx.varName} for non-definition '{e}'" unless (env.getModuleIdxFor? c).isNone || force do throwError "refusing to generate code for imported parser declaration '{c}'; use `@[runParserAttributeHooks]` on its definition instead." let value ← compileParserExpr <| replaceParserTy ctx value let ty ← forallTelescope cinfo.type fun params _ => params.foldrM (init := mkConst ctx.tyName) fun param ty => do let paramTy ← replaceParserTy ctx <$> inferType param return mkForall `_ BinderInfo.default paramTy ty let decl := Declaration.defnDecl { name := c', levelParams := [] type := ty, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.safe } let env ← getEnv let env ← match env.addAndCompile {} decl with | Except.ok env => pure env | Except.error kex => do throwError (← (kex.toMessageData {}).toString) setEnv <| ctx.combinatorAttr.setDeclFor env c c' if cinfo.type.isConst then if let some kind ← parserNodeKind? cinfo.value! then -- If the parser is parameter-less and produces a node of kind `kind`, -- then tag the compiled definition as `[(builtin)Parenthesizer kind]` -- (or `[(builtin)Formatter kind]`, resp.) let attrName := if builtin then ctx.categoryAttr.defn.builtinName else ctx.categoryAttr.defn.name -- Create syntax node for a simple attribute of the form -- `def simple := leading_parser ident >> optional (ident <|> priorityParser)` let stx := mkNode `Lean.Parser.Attr.simple #[mkIdent attrName, mkNullNode #[mkIdent kind]] Attribute.add c' attrName stx mkCall c' else -- if this is a generic function, e.g. `AndThen.andthen`, it's easier to just unfold it until we are -- back to parser combinators let some e' ← unfoldDefinition? e | throwError "don't know how to generate {ctx.varName} for non-parser combinator '{e}'" compileParserExpr e' end variable {α} (ctx : Context α) (builtin : Bool) in def compileEmbeddedParsers : ParserDescr → MetaM Unit | ParserDescr.const _ => pure () | ParserDescr.unary _ d => compileEmbeddedParsers d | ParserDescr.binary _ d₁ d₂ => compileEmbeddedParsers d₁ *> compileEmbeddedParsers d₂ | ParserDescr.parser constName => discard <| compileParserExpr ctx (mkConst constName) (builtin := builtin) (force := false) | ParserDescr.node _ _ d => compileEmbeddedParsers d | ParserDescr.nodeWithAntiquot _ _ d => compileEmbeddedParsers d | ParserDescr.sepBy p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.sepBy1 p _ psep _ => compileEmbeddedParsers p *> compileEmbeddedParsers psep | ParserDescr.trailingNode _ _ _ d => compileEmbeddedParsers d | ParserDescr.symbol _ => pure () | ParserDescr.nonReservedSymbol _ _ => pure () | ParserDescr.cat _ _ => pure () /-- Precondition: `α` must match `ctx.tyName`. -/ unsafe def registerParserCompiler {α} (ctx : Context α) : IO Unit := do Parser.registerParserAttributeHook { postAdd := fun catName constName builtin => do let info ← getConstInfo constName if info.type.isConstOf `Lean.ParserDescr || info.type.isConstOf `Lean.TrailingParserDescr then let d ← evalConstCheck ParserDescr `Lean.ParserDescr constName <|> evalConstCheck TrailingParserDescr `Lean.TrailingParserDescr constName compileEmbeddedParsers ctx d (builtin := builtin) |>.run' else -- `[runBuiltinParserAttributeHooks]` => force compilation even if imported, do not apply `ctx.categoryAttr`. let force := catName.isAnonymous discard (compileParserExpr ctx (mkConst constName) (builtin := builtin) (force := force)).run' } end ParserCompiler end Lean
82475e7cf8d4bad15b86c3611467c7d7b44cf4ba
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/analysis/ODE/gronwall.lean
f603ab7b77d7e0d83c37c2aa66ebcc20d4426dab
[ "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
13,229
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.mean_value import analysis.special_functions.exp_log /-! # Grönwall's inequality The main technical result of this file is the Grönwall-like inequality `norm_le_gronwall_bound_of_norm_deriv_right_le`. It states that if `f : ℝ → E` satisfies `∥f a∥ ≤ δ` and `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then for all `x ∈ [a, b]` we have `∥f x∥ ≤ δ * exp (K * x) + (ε / K) * (exp (K * x) - 1)`. Then we use this inequality to prove some estimates on the possible rate of growth of the distance between two approximate or exact solutions of an ordinary differential equation. The proofs are based on [Hubbard and West, *Differential Equations: A Dynamical Systems Approach*, Sec. 4.5][HubbardWest-ode], where `norm_le_gronwall_bound_of_norm_deriv_right_le` is called “Fundamental Inequality”. ## TODO - Once we have FTC, prove an inequality for a function satisfying `∥f' x∥ ≤ K x * ∥f x∥ + ε`, or more generally `liminf_{y→x+0} (f y - f x)/(y - x) ≤ K x * f x + ε` with any sign of `K x` and `f x`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics filter real open_locale classical topological_space nnreal /-! ### Technical lemmas about `gronwall_bound` -/ /-- Upper bound used in several Grönwall-like inequalities. -/ noncomputable def gronwall_bound (δ K ε x : ℝ) : ℝ := if K = 0 then δ + ε * x else δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) lemma gronwall_bound_K0 (δ ε : ℝ) : gronwall_bound δ 0 ε = λ x, δ + ε * x := funext $ λ x, if_pos rfl lemma gronwall_bound_of_K_ne_0 {δ K ε : ℝ} (hK : K ≠ 0) : gronwall_bound δ K ε = λ x, δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) := funext $ λ x, if_neg hK lemma has_deriv_at_gronwall_bound (δ K ε x : ℝ) : has_deriv_at (gronwall_bound δ K ε) (K * (gronwall_bound δ K ε x) + ε) x := begin by_cases hK : K = 0, { subst K, simp only [gronwall_bound_K0, zero_mul, zero_add], convert ((has_deriv_at_id x).const_mul ε).const_add δ, rw [mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK], convert (((has_deriv_at_id x).const_mul K).exp.const_mul δ).add ((((has_deriv_at_id x).const_mul K).exp.sub_const 1).const_mul (ε / K)) using 1, simp only [id, mul_add, (mul_assoc _ _ _).symm, mul_comm _ K, mul_div_cancel' _ hK], ring } end lemma has_deriv_at_gronwall_bound_shift (δ K ε x a : ℝ) : has_deriv_at (λ y, gronwall_bound δ K ε (y - a)) (K * (gronwall_bound δ K ε (x - a)) + ε) x := begin convert (has_deriv_at_gronwall_bound δ K ε _).comp x ((has_deriv_at_id x).sub_const a), rw [id, mul_one] end lemma gronwall_bound_x0 (δ K ε : ℝ) : gronwall_bound δ K ε 0 = δ := begin by_cases hK : K = 0, { simp only [gronwall_bound, if_pos hK, mul_zero, add_zero] }, { simp only [gronwall_bound, if_neg hK, mul_zero, exp_zero, sub_self, mul_one, add_zero] } end lemma gronwall_bound_ε0 (δ K x : ℝ) : gronwall_bound δ K 0 x = δ * exp (K * x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK, zero_mul, exp_zero, add_zero, mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK, zero_div, zero_mul, add_zero] } end lemma gronwall_bound_ε0_δ0 (K x : ℝ) : gronwall_bound 0 K 0 x = 0 := by simp only [gronwall_bound_ε0, zero_mul] lemma gronwall_bound_continuous_ε (δ K x : ℝ) : continuous (λ ε, gronwall_bound δ K ε x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK], exact continuous_const.add (continuous_id.mul continuous_const) }, { simp only [gronwall_bound_of_K_ne_0 hK], exact continuous_const.add ((continuous_id.mul continuous_const).mul continuous_const) } end /-! ### Inequality and corollaries -/ /-- A Grönwall-like inequality: if `f : ℝ → ℝ` is continuous on `[a, b]` and satisfies the inequalities `f a ≤ δ` and `∀ x ∈ [a, b), liminf_{z→x+0} (f z - f x)/(z - x) ≤ K * (f x) + ε`, then `f x` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. See also `norm_le_gronwall_bound_of_norm_deriv_right_le` for a version bounding `∥f x∥`, `f : ℝ → E`. -/ theorem le_gronwall_bound_of_liminf_deriv_right_le {f f' : ℝ → ℝ} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) (ha : f a ≤ δ) (bound : ∀ x ∈ Ico a b, f' x ≤ K * f x + ε) : ∀ x ∈ Icc a b, f x ≤ gronwall_bound δ K ε (x - a) := begin have H : ∀ x ∈ Icc a b, ∀ ε' ∈ Ioi ε, f x ≤ gronwall_bound δ K ε' (x - a), { assume x hx ε' hε', apply image_le_of_liminf_slope_right_lt_deriv_boundary hf hf', { rwa [sub_self, gronwall_bound_x0] }, { exact λ x, has_deriv_at_gronwall_bound_shift δ K ε' x a }, { assume x hx hfB, rw [← hfB], apply lt_of_le_of_lt (bound x hx), exact add_lt_add_left hε' _ }, { exact hx } }, assume x hx, change f x ≤ (λ ε', gronwall_bound δ K ε' (x - a)) ε, convert continuous_within_at_const.closure_le _ _ (H x hx), { simp only [closure_Ioi, left_mem_Ici] }, exact (gronwall_bound_continuous_ε δ K (x - a)).continuous_within_at end /-- A Grönwall-like inequality: if `f : ℝ → E` is continuous on `[a, b]`, has right derivative `f' x` at every point `x ∈ [a, b)`, and satisfies the inequalities `∥f a∥ ≤ δ`, `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then `∥f x∥` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. -/ theorem norm_le_gronwall_bound_of_norm_deriv_right_le {f f' : ℝ → E} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (ha : ∥f a∥ ≤ δ) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ K * ∥f x∥ + ε) : ∀ x ∈ Icc a b, ∥f x∥ ≤ gronwall_bound δ K ε (x - a) := le_gronwall_bound_of_liminf_deriv_right_le (continuous_norm.comp_continuous_on hf) (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha bound /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_approx_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := begin simp only [dist_eq_norm] at ha ⊢, have h_deriv : ∀ t ∈ Ico a b, has_deriv_within_at (λ t, f t - g t) (f' t - g' t) (Ici t) t, from λ t ht, (hf' t ht).sub (hg' t ht), apply norm_le_gronwall_bound_of_norm_deriv_right_le (hf.sub hg) h_deriv ha, assume t ht, have := dist_triangle4_right (f' t) (g' t) (v t (f t)) (v t (g t)), rw [dist_eq_norm] at this, apply le_trans this, apply le_trans (add_le_add (add_le_add (f_bound t ht) (g_bound t ht)) (hv t (f t) (g t) (hfs t ht) (hgs t ht))), rw [dist_eq_norm, add_comm] end /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_approx_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_approx_trajectories_ODE_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' f_bound hfs hg hg' g_bound (λ t ht, trivial) ha /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := begin have f_bound : ∀ t ∈ Ico a b, dist (v t (f t)) (v t (f t)) ≤ 0, by { intros, rw [dist_self] }, have g_bound : ∀ t ∈ Ico a b, dist (v t (g t)) (v t (g t)) ≤ 0, by { intros, rw [dist_self] }, assume t ht, have := dist_le_of_approx_trajectories_ODE_of_mem_set hv hf hf' f_bound hfs hg hg' g_bound hgs ha t ht, rwa [zero_add, gronwall_bound_ε0] at this, end /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_trajectories_ODE_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) in a set `s ⊆ ℝ × E` with a given initial value provided that RHS is Lipschitz continuous in `x` within `s`, and we consider only solutions included in `s`. -/ theorem ODE_solution_unique_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := begin assume t ht, have := dist_le_of_trajectories_ODE_of_mem_set hv hf hf' hfs hg hg' hgs (dist_le_zero.2 ha) t ht, rwa [zero_mul, dist_le_zero] at this end /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) with a given initial value provided that RHS is Lipschitz continuous in `x`. -/ theorem ODE_solution_unique {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, ODE_solution_unique_of_mem_set (λ t x y hx hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha
296a9e08d5c76501ae0731297203d30093a44187
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/algebra/punit_instances.lean
1478559f48a3e7cd8fcac69895cf8b6ac06afa25
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
3,469
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import order.basic import algebra.module algebra.group universes u open lattice namespace punit variables (x y : punit.{u+1}) (s : set punit.{u+1}) instance : comm_ring punit := by refine { add := λ _ _, star, zero := star, neg := λ _, star, mul := λ _ _, star, one := star, .. }; intros; exact subsingleton.elim _ _ instance : comm_group punit := { inv := λ _, star, mul_left_inv := λ _, subsingleton.elim _ _, .. punit.comm_ring } instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, sub := λ _ _, star, .. punit.comm_ring, .. }; intros; trivial instance : canonically_ordered_monoid punit := by refine { lt_of_add_lt_add_left := λ _ _ _, id, le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.lattice.complete_boolean_algebra, .. }; intros; trivial instance : decidable_linear_ordered_cancel_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, add_right_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_monoid } instance : module punit punit := module.of_core $ by refine { smul := λ _ _, star, .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma zero_eq : (0 : punit) = star := rfl @[simp] lemma one_eq : (1 : punit) = star := rfl attribute [to_additive punit.zero_eq] punit.one_eq @[simp] lemma add_eq : x + y = star := rfl @[simp] lemma mul_eq : x * y = star := rfl attribute [to_additive punit.add_eq] punit.mul_eq @[simp] lemma neg_eq : -x = star := rfl @[simp] lemma inv_eq : x⁻¹ = star := rfl attribute [to_additive punit.neg_eq] punit.inv_eq @[simp] lemma smul_eq : x • y = star := rfl @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false instance {α : Type*} [monoid α] (f : α → punit) : is_monoid_hom f := ⟨subsingleton.elim _ _, λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [add_monoid α] (f : α → punit) : is_add_monoid_hom f := ⟨subsingleton.elim _ _, λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [group α] (f : α → punit) : is_group_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [add_group α] (f : α → punit) : is_add_group_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [semiring α] (f : α → punit) : is_semiring_hom f := { .. punit.is_monoid_hom f, .. punit.is_add_monoid_hom f } instance {α : Type*} [ring α] (f : α → punit) : is_ring_hom f := { .. punit.is_semiring_hom f } end punit
a224ff6ecc6e57110e34d48241efd8a83cc7a369
367134ba5a65885e863bdc4507601606690974c1
/src/measure_theory/bochner_integration.lean
4dc767c6dce3accfcdbee2890903bfb5734a2eae
[ "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
67,825
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov, Sébastien Gouëzel -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps import measure_theory.l1_space import topology.sequences /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ℝ≥0∞`.) 2. Use `α →ₛ E` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ[μ] E`. 3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ℝ≥0∞`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `integrable.induction` in the file `set_integral`, which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on `ℝ≥0∞`-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `L1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `L1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/lp_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions * `∫ a, f a ∂μ` : integral of `f` with respect to a measure `μ` * `∫ a, f a` : integral of `f` with respect to `volume`, the default measure on the ambient type We also define notations for integral on a set, which are described in the file `measure_theory/set_integral`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators nnreal ennreal namespace measure_theory variables {α E : Type*} [measurable_space α] [linear_order E] [has_zero E] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext a, rw coe_sub, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric variables {α E F : Type*} [measurable_space α] local infixr ` →ₛ `:25 := simple_func namespace simple_func section integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group E] [measurable_space E] [normed_group F] variables {μ : measure α} /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_meas_supp {f : α →ₛ E} {μ : measure α} : integrable f μ ↔ f.fin_meas_supp μ := calc integrable f μ ↔ ∫⁻ x, f.map (coe ∘ nnnorm : E → ℝ≥0∞) x ∂μ < ∞ : and_iff_right f.ae_measurable ... ↔ (f.map (coe ∘ nnnorm : E → ℝ≥0∞)).lintegral μ < ∞ : by rw lintegral_eq_lintegral ... ↔ (f.map (coe ∘ nnnorm : E → ℝ≥0∞)).fin_meas_supp μ : iff.symm $ fin_meas_supp.iff_lintegral_lt_top $ eventually_of_forall $ λ x, coe_lt_top ... ↔ _ : fin_meas_supp.map_iff $ λ b, coe_eq_zero.trans nnnorm_eq_zero lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ := integrable_iff_fin_meas_supp.2 h lemma integrable_pair [measurable_space F] {f : α →ₛ E} {g : α →ₛ F} : integrable f μ → integrable g μ → integrable (pair f g) μ := by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair variables [normed_space ℝ F] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/ def integral (μ : measure α) (f : α →ₛ F) : F := ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x lemma integral_eq_sum_filter (f : α →ₛ F) (μ) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _ /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {μ : measure α} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [disjoint_singleton_left, hx] end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := begin -- We start as in the proof of `map_lintegral` simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.measurable_set_preimage _)], -- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive. by_cases ha : g (f a) = 0, { simp only [ha, smul_zero], refine (sum_eq_zero $ λ x hx, _).symm, simp only [mem_filter] at hx, simp [hx.2] }, { rw [to_real_sum, sum_smul], { refine sum_congr rfl (λ x hx, _), simp only [mem_filter] at hx, rw [hx.2] }, { intros x hx, simp only [mem_filter] at hx, refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _, exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } }, end /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ℝ≥0∞} (hf : integrable f μ) (hg0 : g 0 = 0) (hgt : ∀b, g b < ∞): (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, { apply mul_lt_top (hgt a) (hf'.meas_preimage_singleton_ne_zero a0) } }, { simp [hg0] } end variables [normed_space ℝ E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g): f.integral μ = g.integral μ := show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from begin have inte := integrable_pair hf (hf.congr h), rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` is not a `normed_space`, we need some form of coercion. -/ lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], { exact integral_congr hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := calc integral μ (f + g) = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_integral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ : begin rw [map_integral (pair f g), map_integral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = integral μ f + integral μ g : rfl lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl ... = - integral μ f : begin rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma integral_sub [borel_space E] {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := begin rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg], exact hg.neg end lemma integral_smul (r : ℝ) {f : α →ₛ E} (hf : integrable f μ) : integral μ (r • f) = r • integral μ f := calc integral μ (r • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • r • x : by rw [smul_eq_map r f, map_integral f _ hf (smul_zero _)] ... = ∑ x in f.range, ((ennreal.to_real (μ (f ⁻¹' {x}))) * r) • x : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • integral μ f : by simp only [integral, smul_sum, smul_smul, mul_comm] lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin rw [map_integral f norm hf norm_zero, integral], calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • ∥x∥ : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply], refine sum_congr rfl (λ x hx, _), rw [to_real_add]; refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero (mem_filter.1 hx).2), exacts [hf.left_of_add_measure, hf.right_of_add_measure] end end integral end simple_func namespace L1 open ae_eq_fun variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {μ : measure α} variables (α E μ) /-- `L1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : add_subgroup (Lp E 1 μ) := { carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.ae_measurable : α →ₘ[μ] E) = f}, zero_mem' := ⟨0, rfl⟩, add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩, ⟨s + t, by simp only [←hs, ←ht, mk_add_mk, add_subgroup.coe_add, mk_eq_mk, simple_func.coe_add]⟩, neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [←hs, neg_mk, simple_func.coe_neg, mk_eq_mk, add_subgroup.coe_neg]⟩ } variables {α E μ} notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.L1.simple_func α E μ namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g := subtype.ext_iff.symm @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = g ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `normed_group`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the Bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ[μ] E) := by apply_instance local attribute [instance] simple_func.normed_group /-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/ instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hs⟩⟩, use k • s, apply eq.trans (smul_mk k s s.ae_measurable).symm _, rw hs, refl, end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ[μ] E) : ((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ[μ] E) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } local attribute [instance] simple_func.normed_group simple_func.semimodule /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the Bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section to_L1 /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def to_L1 (f : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) := ⟨hf.to_L1 f, ⟨f, rfl⟩⟩ lemma to_L1_eq_to_L1 (f : α →ₛ E) (hf : integrable f μ) : (to_L1 f hf : α →₁[μ] E) = hf.to_L1 f := rfl lemma to_L1_eq_mk (f : α →ₛ E) (hf : integrable f μ) : (to_L1 f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.ae_measurable := rfl lemma to_L1_zero : to_L1 (0 : α →ₛ E) (integrable_zero α E μ) = 0 := rfl lemma to_L1_add (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f + g) (hf.add hg) = to_L1 f hf + to_L1 g hg := rfl lemma to_L1_neg (f : α →ₛ E) (hf : integrable f μ) : to_L1 (-f) hf.neg = -to_L1 f hf := rfl lemma to_L1_sub (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : to_L1 (f - g) (hf.sub hg) = to_L1 f hf - to_L1 g hg := by { simp only [sub_eq_add_neg, ← to_L1_neg, ← to_L1_add], refl } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma to_L1_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) : to_L1 (c • f) (hf.smul c) = c • to_L1 f hf := rfl lemma norm_to_L1 (f : α →ₛ E) (hf : integrable f μ) : ∥to_L1 f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := by simp [to_L1, integrable.norm_to_L1] end to_L1 section to_simple_func /-- Find a representative of a `L1.simple_func`. -/ def to_simple_func (f : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2 /-- `(to_simple_func f)` is measurable. -/ protected lemma measurable (f : α →₁ₛ[μ] E) : measurable (to_simple_func f) := (to_simple_func f).measurable protected lemma ae_measurable (f : α →₁ₛ[μ] E) : ae_measurable (to_simple_func f) μ := (simple_func.measurable f).ae_measurable /-- `to_simple_func f` is integrable. -/ protected lemma integrable (f : α →₁ₛ[μ] E) : integrable (to_simple_func f) μ := begin apply (integrable_mk (simple_func.ae_measurable f)).1, convert integrable_coe_fn f.val, exact classical.some_spec f.2 end lemma to_L1_to_simple_func (f : α →₁ₛ[μ] E) : to_L1 (to_simple_func f) (simple_func.integrable f) = f := by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 } lemma to_simple_func_to_L1 (f : α →ₛ E) (hfi : integrable f μ) : to_simple_func (to_L1 f hfi) =ᵐ[μ] f := by { rw ← mk_eq_mk, exact classical.some_spec (to_L1 f hfi).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : to_simple_func f =ᵐ[μ] f := begin simp_rw [← integrable.to_L1_eq_to_L1_iff (to_simple_func f) f (simple_func.integrable f) (integrable_coe_fn ↑f), subtype.ext_iff], convert classical.some_spec f.coe_prop, exact integrable.to_L1_coe_fn _ _, end variables (E μ) lemma zero_to_simple_func : to_simple_func (0 : α →₁ₛ[μ] E) =ᵐ[μ] 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), Lp.coe_fn_zero E 1 μ], assume a h₁ h₂, rwa h₁, end variables {E μ} lemma add_to_simple_func (f g : α →₁ₛ[μ] E) : to_simple_func (f + g) =ᵐ[μ] to_simple_func f + to_simple_func g := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, Lp.coe_fn_add (f : α →₁[μ] E) g], assume a, simp only [← coe_coe, coe_add, pi.add_apply], iterate 4 { assume h, rw h } end lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : to_simple_func (-f) =ᵐ[μ] - to_simple_func f := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, Lp.coe_fn_neg (f : α →₁[μ] E)], assume a, simp only [pi.neg_apply, coe_neg, ← coe_coe], repeat { assume h, rw h } end lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) : to_simple_func (f - g) =ᵐ[μ] to_simple_func f - to_simple_func g := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, Lp.coe_fn_sub (f : α →₁[μ] E) g], assume a, simp only [coe_sub, pi.sub_apply, ← coe_coe], repeat { assume h, rw h } end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) : to_simple_func (k • f) =ᵐ[μ] k • to_simple_func f := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, Lp.coe_fn_smul k (f : α →₁[μ] E)], assume a, simp only [pi.smul_apply, coe_smul, ← coe_coe], repeat { assume h, rw h } end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) : ∫⁻ (x : α), edist (to_simple_func f x) (to_simple_func g x) ∂μ < ∞ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_lt_top (integrable_coe_fn _) (integrable_coe_fn _) end lemma dist_to_simple_func (f g : α →₁ₛ[μ] E) : dist f g = ennreal.to_real (∫⁻ x, edist (to_simple_func f x) (to_simple_func g x) ∂μ) := begin rw [dist_eq, L1.dist_def, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact lintegral_edist_lt_top (integrable_coe_fn _) (integrable_coe_fn _) }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist ((to_simple_func f) x) (to_simple_func (0 : α →₁ₛ[μ] E) x) ∂μ) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) ((to_simple_func f) x) ∂μ) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : ∫⁻ x, edist ((to_simple_func f) x) ((to_simple_func (0 : α →₁ₛ[μ] E)) x) ∂μ = ∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ, { refine lintegral_congr_ae ((zero_to_simple_func E μ).mono (λ a h, _)), rw [h, pi.zero_apply] }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = ((to_simple_func f).map norm).integral μ := begin rw [norm_to_simple_func, simple_func.integral_eq_lintegral], { simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] }, { exact (simple_func.integrable f).norm }, { exact eventually_of_forall (λ x, norm_nonneg _) } end end to_simple_func section coe_to_L1 protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := begin apply simple_func.uniform_embedding.dense_embedding, assume f, rw mem_closure_iff_seq_limit, have hfi' : integrable f μ := integrable_coe_fn f, refine ⟨λ n, ↑(to_L1 (simple_func.approx_on f (Lp.measurable f) univ 0 trivial n) (simple_func.integrable_approx_on_univ (Lp.measurable f) hfi' n)), λ n, mem_range_self _, _⟩, convert simple_func.tendsto_approx_on_univ_L1 (Lp.measurable f) hfi', rw integrable.to_L1_coe_fn end protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 E] variables (α E) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_L1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) := { to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := L1.simple_func.uniform_continuous.continuous, } variables {α E 𝕜} end coe_to_L1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨Lp.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, Lp.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (pos_part f : α →₁[μ] ℝ) = Lp.pos_part (f : α →₁[μ] ℝ) := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (neg_part f : α →₁[μ] ℝ) = Lp.neg_part (f : α →₁[μ] ℝ) := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ[μ] E` and prove basic properties of this integral. -/ variables [normed_space ℝ E] /-- The Bochner integral over simple functions in L1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := ((to_simple_func f)).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = ((to_simple_func f)).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] (to_simple_func f)) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real ((to_simple_func f) a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral (simple_func.integrable f) h_pos] lemma integral_congr {f g : α →₁ₛ[μ] E} (h : to_simple_func f =ᵐ[μ] to_simple_func g) : integral f = integral g := simple_func.integral_congr (simple_func.integrable f) h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.integral_add (simple_func.integrable f) (simple_func.integrable g), apply measure_theory.simple_func.integral_congr (simple_func.integrable (f + g)), apply add_to_simple_func end lemma integral_smul (r : ℝ) (f : α →₁ₛ[μ] E) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.integral_smul _ (simple_func.integrable f), apply measure_theory.simple_func.integral_congr (simple_func.integrable (r • f)), apply smul_to_simple_func end lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥integral f∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact (to_simple_func f).norm_integral_le_integral_norm (simple_func.integrable f) end variables (α E μ) /-- The Bochner integral over simple functions in L1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) variables {α E μ} local notation `Integral` := integral_clm α E μ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (pos_part f) =ᵐ[μ] (to_simple_func f).pos_part := begin have eq : ∀ a, (to_simple_func f).pos_part a = max ((to_simple_func f) a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, to_simple_func (pos_part f) a = max ((to_simple_func f) a) 0, { filter_upwards [to_simple_func_eq_to_fun (pos_part f), Lp.coe_fn_pos_part (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], assume a h₁ h₂ h₃, rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (neg_part f) =ᵐ[μ] (to_simple_func f).neg_part := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : (to_simple_func f).pos_part =ᵐ[μ] (to_simple_func (pos_part f)).map norm, { filter_upwards [pos_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : (to_simple_func f).neg_part =ᵐ[μ] (to_simple_func (neg_part f)).map norm, { filter_upwards [neg_part_to_simple_func f], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ᵐ a ∂μ, (to_simple_func f).pos_part a - (to_simple_func f).neg_part a = (to_simple_func (pos_part f)).map norm a - (to_simple_func (neg_part f)).map norm a, { filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show (to_simple_func f).integral μ = ((to_simple_func (pos_part f)).map norm - (to_simple_func (neg_part f)).map norm).integral μ, apply measure_theory.simple_func.integral_congr (simple_func.integrable f), filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := (to_simple_func f).pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact (simple_func.integrable f).max_zero.congr ae_eq₁ }, { exact (simple_func.integrable f).neg.max_zero.congr ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ variables [normed_space ℝ E] [normed_space ℝ F] [complete_space E] section integration_in_L1 local notation `to_L1` := coe_to_L1 α E ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in L1 space as a continuous linear map. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := (integral_clm α E μ).extend to_L1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in L1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl @[norm_cast] lemma simple_func.integral_L1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = (simple_func.integral f) := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range (simple_func.integral_clm α E μ).uniform_continuous _ variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁[μ] E) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : ℝ≥0) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), integral f) := by simp [L1.integral, L1.integral_clm.continuous] section pos_part local attribute [instance] fact_one_le_one_ennreal lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥) L1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp Lp.continuous_pos_part) (continuous_norm.comp Lp.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_L1 end L1 variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral (μ : measure α) (f : α → E) : E := if hf : integrable f μ then L1.integral (hf.to_L1 f) else 0 /-! In the notation for integrals, an expression like `∫ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = L1.integral (hf.to_L1 f) := dif_pos hf lemma L1.integral_eq_integral (f : α →₁[μ] E) : L1.integral f = ∫ a, f a ∂μ := by rw [integral_eq _ (L1.integrable_coe_fn f), integrable.to_L1_coe_fn] lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_ae_measurable (h : ¬ ae_measurable f μ) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := by { rw [integral_eq _ (integrable_zero α E μ)], exact L1.integral_zero _ _ } @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := begin rw [integral_eq, integral_eq f hf, integral_eq g hg, ← L1.integral_add], { refl }, { exact hf.add hg } end lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, - f a) hf.neg, ← L1.integral_neg], refl }, { rw [integral_undef hf, integral_undef, neg_zero], rwa [← integrable_neg_iff] at hf } end lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by { simp only [sub_eq_add_neg, ← integral_neg], exact integral_add hf hg.neg } lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul (r : ℝ) (f : α → E) : ∫ a, r • (f a) ∂μ = r • ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, r • (f a)), integrable.to_L1_smul, L1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬ integrable (λ x, r • f x) μ, { change ¬ integrable (r • f) μ, rwa [integrable_smul_iff hr f] }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := begin by_cases hfi : integrable f μ, { have hgi : integrable g μ := hfi.congr h, rw [integral_eq f hfi, integral_eq g hgi, (integrable.to_L1_eq_to_L1_iff f g hfi hgi).2 h] }, { have hgi : ¬ integrable g μ, { rw integrable_congr h at hfi, exact hfi }, rw [integral_undef hfi, integral_undef hgi] }, end @[simp] lemma L1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (hf.to_L1 f) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae $ by simp [integrable.coe_fn_to_L1] @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← L1.integral_eq_integral], exact L1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← integrable.norm_to_L1_eq_lintegral_norm f hf], exact L1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ℝ≥0∞) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := if hfm : ae_measurable f μ then by simp [integral_congr_ae hf, integral_zero] else integral_non_ae_measurable hfm /-- If `f` has finite integral, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma has_finite_integral.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : has_finite_integral f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := begin rw [tendsto_zero_iff_norm_tendsto_zero], simp_rw [← coe_nnnorm, ← nnreal.coe_zero, nnreal.tendsto_coe, ← ennreal.tendsto_coe, ennreal.coe_zero], exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (tendsto_set_lintegral_zero hf hs) (λ i, zero_le _) (λ i, ennnorm_integral_le_lintegral_ennnorm _) end /-- If `f` is integrable, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma integrable.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : integrable f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := hf.2.tendsto_set_integral_nhds_zero hs /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_L1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi, edist_dist, dist_eq_norm], apply norm_integral_le_lintegral_norm end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (bound_integrable : integrable bound μ) (h_bound : ∀ n, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := (tendsto_to_real zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable.has_finite_integral h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, ae_measurable (F n) μ) (f_measurable : ae_measurable f μ) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - min (f a) 0) ∂μ) := let f₁ := hf.to_L1 f in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) = ∥Lp.pos_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_pos_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real, nnnorm], congr' 1, apply nnreal.eq, simp [real.norm_of_nonneg, le_max_right, nnreal.coe_of_real] end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ -min (f a) 0) ∂μ) = ∥Lp.neg_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_neg_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real, nnnorm], congr' 1, apply nnreal.eq, simp [real.norm_of_nonneg, min_le_right, nnreal.coe_of_real, neg_nonneg], end, begin rw [eq₁, eq₂, integral, dif_pos], exact L1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : ae_measurable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_max_sub_lintegral_min hfi, have h_min : ∫⁻ a, ennreal.of_real (-min (f a) 0) ∂μ = 0, { rw lintegral_eq_zero_iff', { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { exact measurable_of_real.comp_ae_measurable (measurable_id.neg.comp_ae_measurable $ hfm.min ae_measurable_const) } }, have h_max : ∫⁻ a, ennreal.of_real (max (f a) 0) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ, { refine lintegral_congr_ae (hf.mono (λ a h, _)), rw [pi.zero_apply] at h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : ae_measurable f μ, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_ae_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → ℝ≥0) (hfi : integrable (λ x, (f x : real)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.ae_measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [nnreal.nnnorm_eq] end lemma integral_to_real {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hf : ∀ᵐ x ∂μ, f x < ∞) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff' (ennreal.measurable_of_real.comp_ae_measurable hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, pos_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma L1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := begin simp only [snorm, snorm', ennreal.one_to_real, ennreal.rpow_one, Lp.norm_def, if_false, ennreal.one_ne_top, one_ne_zero, _root_.div_one], rw integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (by simp [norm_nonneg])) (continuous_norm.measurable.comp_ae_measurable (Lp.ae_measurable f)), simp [of_real_norm_eq_coe_nnnorm] end lemma L1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥hf.to_L1 f∥ = ∫ a, ∥f a∥ ∂μ := begin rw L1.norm_eq_integral_norm, refine integral_congr_ae _, apply hf.coe_fn_to_L1.mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) @[mono] lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : ae_measurable f μ, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_ae_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _), classical.by_cases ( λh : ae_measurable f μ, calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ ae_measurable.norm h).symm ) ( λh : ¬ae_measurable f μ, begin rw [integral_non_ae_measurable h, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← L1.simple_func.to_L1_eq_to_L1, L1.simple_func.integral_L1_eq_integral, L1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (L1.simple_func.to_simple_func_to_L1 _ _).symm end @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin by_cases hμ : μ univ < ∞, { haveI : finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : _, rw [simple_func.integral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ⟩ }, simp only [not_lt, top_le_iff] at hμ, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ_of_measurable {f : α → E} (fmeas : measurable f) (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f fmeas univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f fmeas univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_L1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ fmeas hf) (simple_func.tendsto_approx_on_univ_L1_edist fmeas hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ fmeas hf] end variable {ν : measure α} private lemma integral_add_measure_of_measurable {f : α → E} (fmeas : measurable f) (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable fmeas hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ fmeas hfi _)] using (tendsto_integral_approx_on_univ_of_measurable fmeas hμ).add (tendsto_integral_approx_on_univ_of_measurable fmeas hν) end lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have h : ae_measurable f (μ + ν) := hμ.ae_measurable.add_measure hν.ae_measurable, let g := h.mk f, have A : f =ᵐ[μ + ν] g := h.ae_eq_mk, have B : f =ᵐ[μ] g := A.filter_mono (ae_mono (measure.le_add_right (le_refl μ))), have C : f =ᵐ[ν] g := A.filter_mono (ae_mono (measure.le_add_left (le_refl ν))), calc ∫ x, f x ∂(μ + ν) = ∫ x, g x ∂(μ + ν) : integral_congr_ae A ... = ∫ x, g x ∂μ + ∫ x, g x ∂ν : integral_add_measure_of_measurable h.measurable_mk ((integrable_congr B).1 hμ) ((integrable_congr C).1 hν) ... = ∫ x, f x ∂μ + ∫ x, f x ∂ν : by { congr' 1, { exact integral_congr_ae B.symm }, { exact integral_congr_ae C.symm } } end @[simp] lemma integral_zero_measure (f : α → E) : ∫ x, f x ∂0 = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp private lemma integral_smul_measure_aux {f : α → E} {c : ℝ≥0∞} (h0 : 0 < c) (hc : c < ∞) (fmeas : measurable f) (hfi : integrable f μ) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ_of_measurable fmeas hfi)), convert tendsto_integral_approx_on_univ_of_measurable fmeas (hfi.smul_measure hc), simp only [simple_func.integral, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul] end @[simp] lemma integral_smul_measure (f : α → E) (c : ℝ≥0∞) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `c = 0` rcases (zero_le c).eq_or_lt with rfl|h0, { simp }, -- `f` is not almost everywhere measurable by_cases hfm : ae_measurable f μ, swap, { have : ¬ (ae_measurable f (c • μ)), by simpa [ne_of_gt h0] using hfm, simp [integral_non_ae_measurable, hfm, this] }, -- `c = ∞` rcases (le_top : c ≤ ∞).eq_or_lt with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[∞ • μ] 0 := ae_smul_measure hf ∞, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro (hfm.smul_measure ∞), true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff' hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ∞` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_lt_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel (ne_of_gt h0) (ne_of_lt hc), one_smul] }, -- Main case: `0 < c < ∞`, `f` is almost everywhere measurable and integrable let g := hfm.mk f, calc ∫ x, f x ∂(c • μ) = ∫ x, g x ∂(c • μ) : integral_congr_ae $ ae_smul_measure hfm.ae_eq_mk c ... = c.to_real • ∫ x, g x ∂μ : integral_smul_measure_aux h0 hc hfm.measurable_mk $ hfi.congr hfm.ae_eq_mk ... = c.to_real • ∫ x, f x ∂μ : by { congr' 1, exact integral_congr_ae (hfm.ae_eq_mk.symm) } end lemma integral_map_of_measurable {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hfm.ae_measurable hφ] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable hfm hfi) _, convert tendsto_integral_approx_on_univ_of_measurable (hfm.comp hφ) ((integrable_map_measure hfm.ae_measurable hφ).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral, measure.map_apply, hφ, simple_func.measurable_set_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : ae_measurable f (measure.map φ μ)) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := let g := hfm.mk f in calc ∫ y, f y ∂(measure.map φ μ) = ∫ y, g y ∂(measure.map φ μ) : integral_congr_ae hfm.ae_eq_mk ... = ∫ x, g (φ x) ∂μ : integral_map_of_measurable hφ hfm.measurable_mk ... = ∫ x, f (φ x) ∂μ : integral_congr_ae $ ae_eq_comp hφ (hfm.ae_eq_mk).symm lemma integral_dirac' (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac' hfm ... = f a : by simp [measure.dirac_apply_of_mem] lemma integral_dirac [measurable_singleton_class α] (f : α → E) (a : α) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac f ... = f a : by simp [measure.dirac_apply_of_mem] end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul L1.integral_add L1.integral_sub L1.integral_smul L1.integral_neg attribute [irreducible] integral L1.integral end measure_theory
ca09401d18160ba1f54e4694ed891aaa5d55e299
43390109ab88557e6090f3245c47479c123ee500
/src/Euclid_old/Euclids_Props.lean
06410d529de15ca644147fc22bc425c8afe7afd6
[ "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
1,194
lean
import Euclid.axioms open Euclidean_plane variables {point : Type} [Euclidean_plane point] theorem prop1 (a b : point) : ∃ c, eqd a b a c → eqd a b b c := sorry theorem prop2 (a b c : point) : ∃ d, eqd a d b c := sorry theorem prop3 (a b c d : point) (h : ¬eqd a b c d) : (∃ x, B a x b → eqd a x c d) ∨ (∃ x, B c x d → eqd a b c x) := sorry --theorem prop4 --theorem prop5 --theorem prop6 theorem prop7 (a b c d c' d' x : point) : eqd a c a c' → eqd b c b c' → B a d b → B a d' b → B c d x → B c' d' x → d ≠ x → d' ≠ x → c = c' := unique_tri a b c d c' d' x --theorem prop8 --theorem prop9 theorem prop10 (a b : point) : ∃ c, B a c b → eqd a c b c := sorry --theorem prop11 --theorem prop12 --theorem prop13 --theorem prop14 --theorem prop15 --theorem prop16 --theorem prop17 --theorem prop18 --theorem prop19 --theorem prop20 --theorem prop21 --theorem prop22 --theorem prop23 --theorem prop24 --theorem prop25 --theorem prop26 --theorem prop27 --theorem prop28 --theorem prop29 theorem prop30 (a b c d e f : point) {h1 : a ≠ b} {h2 : c ≠ d} {h3 : e ≠ f} : parallel a b c d h1 h2 → parallel a b e f h1 h3 → parallel c d e f h2 h3:= sorry
3fd26710ebbe256832bb969399027306ca3003b1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/back3.lean
25f7a44daf90aeca18d690f6cec48d6e290da669
[ "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
1,277
lean
/- Lean has a backward chaining tactic that can be configured using attributes. -/ open list tactic universe variable u lemma in_tail {α : Type u} {a : α} (b : α) {l : list α} : a ∈ l → a ∈ b::l := mem_cons_of_mem _ lemma in_head {α : Type u} (a : α) (l : list α) : a ∈ a::l := mem_cons_self _ _ lemma in_left {α : Type u} {a : α} {l : list α} (r : list α) : a ∈ l → a ∈ l ++ r := mem_append_left _ lemma in_right {α : Type u} {a : α} (l : list α) {r : list α} : a ∈ r → a ∈ l ++ r := mem_append_right _ /- It is trivial to define mk_mem_list using backward chaining -/ attribute [intro] in_tail in_head in_left in_right meta def mk_mem_list : tactic unit := solve1 (back_chaining) example (a b c : nat) : a ∈ [b, c] ++ [b, a, b] := by mk_mem_list set_option trace.tactic.back_chaining true example (a b c : nat) : a ∈ [b, c] ++ [b, a, b] := by mk_mem_list example (a b c : nat) : a ∈ [b, c] ++ [b, c, c] ++ [b, a, b] := by mk_mem_list example (a b c : nat) (l : list nat) : a ∈ l → a ∈ [b, c] ++ b::l := begin intros, mk_mem_list end example (a b c : nat) (l₁ l₂ : list nat) : a ∈ l₁ → a ∈ b::b::c::l₂ ++ b::c::l₁ ++ [c, c, b] := begin intros, mk_mem_list end
59fa7d3a877f67fb249dda30d5dcf9b9b81990c9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Log.lean
55793e7c535b946103a3f1f78187c3014442a1bc
[ "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
4,383
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.Sorry namespace Lean /-- The `MonadLog` interface for logging error messages. -/ class MonadLog (m : Type → Type) extends MonadFileMap m where /-- Return the current reference syntax being used to provide position information. -/ getRef : m Syntax /-- The name of the file being processed. -/ getFileName : m String /-- Return `true` if errors have been logged. -/ hasErrors : m Bool /-- Log a new message. -/ logMessage : Message → m Unit export MonadLog (getFileName logMessage) instance (m n) [MonadLift m n] [MonadLog m] : MonadLog n where getRef := liftM (MonadLog.getRef : m _) getFileMap := liftM (getFileMap : m _) getFileName := liftM (getFileName : m _) hasErrors := liftM (MonadLog.hasErrors : m _) logMessage := fun msg => liftM (logMessage msg : m _ ) variable [Monad m] [MonadLog m] [AddMessageContext m] [MonadOptions m] /-- Return the position (as `String.pos`) associated with the current reference syntax (i.e., the syntax object returned by `getRef`.) -/ def getRefPos : m String.Pos := do let ref ← MonadLog.getRef return ref.getPos?.getD 0 /-- Return the line and column numbers associated with the current reference syntax (i.e., the syntax object returned by `getRef`.) -/ def getRefPosition : m Position := do let fileMap ← getFileMap return fileMap.toPosition (← getRefPos) /-- If `warningAsError` is set to `true`, then warning messages are treated as errors. -/ register_builtin_option warningAsError : Bool := { defValue := false descr := "treat warnings as errors" } /-- Log the message `msgData` at the position provided by `ref` with the given `severity`. If `getRef` has position information but `ref` does not, we use `getRef`. We use the `fileMap` to find the line and column numbers for the error message. -/ def logAt (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error) : m Unit := unless severity == .error && msgData.hasSyntheticSorry do let severity := if severity == .warning && warningAsError.get (← getOptions) then .error else severity let ref := replaceRef ref (← MonadLog.getRef) let pos := ref.getPos?.getD 0 let endPos := ref.getTailPos?.getD pos let fileMap ← getFileMap let msgData ← addMessageContext msgData logMessage { fileName := (← getFileName), pos := fileMap.toPosition pos, endPos := fileMap.toPosition endPos, data := msgData, severity := severity } /-- Log a new error message using the given message data. The position is provided by `ref`. -/ def logErrorAt (ref : Syntax) (msgData : MessageData) : m Unit := logAt ref msgData MessageSeverity.error /-- Log a new warning message using the given message data. The position is provided by `ref`. -/ def logWarningAt [MonadOptions m] (ref : Syntax) (msgData : MessageData) : m Unit := do logAt ref msgData .warning /-- Log a new information message using the given message data. The position is provided by `ref`. -/ def logInfoAt (ref : Syntax) (msgData : MessageData) : m Unit := logAt ref msgData MessageSeverity.information /-- Log a new error/warning/information message using the given message data and `severity`. The position is provided by `getRef`. -/ def log (msgData : MessageData) (severity : MessageSeverity := MessageSeverity.error): m Unit := do let ref ← MonadLog.getRef logAt ref msgData severity /-- Log a new error message using the given message data. The position is provided by `getRef`. -/ def logError (msgData : MessageData) : m Unit := log msgData MessageSeverity.error /-- Log a new warning message using the given message data. The position is provided by `getRef`. -/ def logWarning [MonadOptions m] (msgData : MessageData) : m Unit := do log msgData (if warningAsError.get (← getOptions) then .error else .warning) /-- Log a new information message using the given message data. The position is provided by `getRef`. -/ def logInfo (msgData : MessageData) : m Unit := log msgData MessageSeverity.information /-- Log the error message "unknown declaration" -/ def logUnknownDecl (declName : Name) : m Unit := logError m!"unknown declaration '{declName}'" end Lean
17672359f98050f515751db149165e353397b6e3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Util/EquipT.lean
918161b74ec6747e366ad211eba463706b7c744b
[ "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
2,915
lean
/- Copyright (c) 2022 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ namespace Lake /-- A monad transformer that equips a monad with a value. This is a generalization of `ReaderT` where the value is not necessarily directly readable through the monad. -/ def EquipT (ρ : Type u) (m : Type v → Type w) (α : Type v) := ρ → m α variable {ρ : Type u} {m : Type v → Type w} instance {α : Type v} [Inhabited (m α)] : Inhabited (EquipT ρ m α) where default := fun _ => default namespace EquipT @[inline] protected def run {α : Type v} (self : EquipT ρ m α) (r : ρ) : m α := self r @[inline] protected def map [Functor m] {α β : Type v} (f : α → β) (self : EquipT ρ m α) : EquipT ρ m β := fun fetch => Functor.map f (self fetch) instance [Functor m] : Functor (EquipT ρ m) where map := EquipT.map @[inline] protected def pure [Pure m] {α : Type v} (a : α) : EquipT ρ m α := fun _ => pure a instance [Pure m] : Pure (EquipT ρ m) where pure := EquipT.pure @[inline] protected def compose {α₁ α₂ β : Type v} (f : m α₁ → (Unit → m α₂) → m β) (x₁ : EquipT ρ m α₁) (x₂ : Unit → EquipT ρ m α₂) : EquipT ρ m β := fun fetch => f (x₁ fetch) (fun _ => x₂ () fetch) @[inline] protected def seq [Seq m] {α β : Type v} : EquipT ρ m (α → β) → (Unit → EquipT ρ m α) → EquipT ρ m β := EquipT.compose Seq.seq instance [Seq m] : Seq (EquipT ρ m) where seq := EquipT.seq instance [Applicative m] : Applicative (EquipT ρ m) := {} @[inline] protected def bind [Bind m] {α β : Type v} (self : EquipT ρ m α) (f : α → EquipT ρ m β) : EquipT ρ m β := fun fetch => bind (self fetch) fun a => f a fetch instance [Bind m] : Bind (EquipT ρ m) where bind := EquipT.bind instance [Monad m] : Monad (EquipT ρ m) := {} @[inline] protected def lift {α : Type v} (t : m α) : EquipT ρ m α := fun _ => t instance : MonadLift m (EquipT ρ m) where monadLift := EquipT.lift @[inline] protected def failure [Alternative m] {α : Type v} : EquipT ρ m α := fun _ => failure @[inline] protected def orElse [Alternative m] {α : Type v} : EquipT ρ m α → (Unit → EquipT ρ m α) → EquipT ρ m α := EquipT.compose Alternative.orElse instance [Alternative m] : Alternative (EquipT ρ m) where failure := EquipT.failure orElse := EquipT.orElse @[inline] protected def throw {ε : Type v} [MonadExceptOf ε m] {α : Type v} (e : ε) : EquipT ρ m α := fun _ => throw e @[inline] protected def tryCatch {ε : Type v} [MonadExceptOf ε m] {α : Type v} (self : EquipT ρ m α) (c : ε → EquipT ρ m α) : EquipT ρ m α := fun f => tryCatchThe ε (self f) fun e => (c e) f instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (EquipT ρ m) where throw := EquipT.throw tryCatch := EquipT.tryCatch
3d5ec7b9657e86e44e0f4f7abd9b004ffda1fb6c
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/ordered_group.lean
04250eaa45ae4bec3a6a679505e5495c2b75c7b9
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
45,727
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.ordered_monoid import order.order_dual /-! # Ordered groups This file develops the basics of ordered groups. ## Implementation details Unfortunately, the number of `'` appended to lemmas in this file may differ between the multiplicative and the additive version of a lemma. The reason is that we did not want to change existing names in the library. -/ set_option old_structure_cmd true open function universe u variable {α : Type u} @[to_additive] instance group.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (*) (≤)] : contravariant_class α α (*) (≤) := group.covconv @[to_additive] instance group.swap.covariant_class_le.to_contravariant_class_le [group α] [has_le α] [covariant_class α α (swap (*)) (≤)] : contravariant_class α α (swap (*)) (≤) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... ≤ c * a * a⁻¹ : mul_le_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } @[to_additive] instance group.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (*) (<)] : contravariant_class α α (*) (<) := { elim := λ a b c bc, calc b = a⁻¹ * (a * b) : eq_inv_mul_of_mul_eq rfl ... < a⁻¹ * (a * c) : mul_lt_mul_left' bc a⁻¹ ... = c : inv_mul_cancel_left a c } @[to_additive] instance group.swap.covariant_class_lt.to_contravariant_class_lt [group α] [has_lt α] [covariant_class α α (swap (*)) (<)] : contravariant_class α α (swap (*)) (<) := { elim := λ a b c bc, calc b = b * a * a⁻¹ : eq_mul_inv_of_mul_eq rfl ... < c * a * a⁻¹ : mul_lt_mul_right' bc a⁻¹ ... = c : mul_inv_eq_of_eq_mul rfl } /-- An ordered additive commutative group is an additive commutative group with a partial order in which addition is strictly monotone. -/ @[protect_proj, ancestor add_comm_group partial_order] class ordered_add_comm_group (α : Type u) extends add_comm_group α, partial_order α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) /-- An ordered commutative group is an commutative group with a partial order in which multiplication is strictly monotone. -/ @[protect_proj, ancestor comm_group partial_order] class ordered_comm_group (α : Type u) extends comm_group α, partial_order α := (mul_le_mul_left : ∀ a b : α, a ≤ b → ∀ c : α, c * a ≤ c * b) attribute [to_additive] ordered_comm_group @[to_additive] instance ordered_comm_group.to_covariant_class_left_le (α : Type u) [ordered_comm_group α] : covariant_class α α (*) (≤) := { elim := λ a b c bc, ordered_comm_group.mul_le_mul_left b c bc a } /--The units of an ordered commutative monoid form an ordered commutative group. -/ @[to_additive] instance units.ordered_comm_group [ordered_comm_monoid α] : ordered_comm_group (units α) := { mul_le_mul_left := λ a b h c, (mul_le_mul_left' (h : (a : α) ≤ b) _ : (c : α) * a ≤ c * b), .. units.partial_order, .. units.comm_group } @[priority 100, to_additive] -- see Note [lower instance priority] instance ordered_comm_group.to_ordered_cancel_comm_monoid (α : Type u) [s : ordered_comm_group α] : ordered_cancel_comm_monoid α := { mul_left_cancel := λ a b c, (mul_right_inj a).mp, le_of_mul_le_mul_left := λ a b c, (mul_le_mul_iff_left a).mp, ..s } @[priority 100, to_additive] instance ordered_comm_group.has_exists_mul_of_le (α : Type u) [ordered_comm_group α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨b * a⁻¹, (mul_inv_cancel_comm_assoc a b).symm⟩⟩ @[to_additive] instance [h : has_inv α] : has_inv (order_dual α) := h @[to_additive] instance [h : has_div α] : has_div (order_dual α) := h @[to_additive] instance [h : div_inv_monoid α] : div_inv_monoid (order_dual α) := h @[to_additive] instance [h : group α] : group (order_dual α) := h @[to_additive] instance [h : comm_group α] : comm_group (order_dual α) := h @[to_additive] instance [ordered_comm_group α] : ordered_comm_group (order_dual α) := { .. order_dual.ordered_comm_monoid, .. order_dual.group } section group variables [group α] section typeclasses_left_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_nonpos_iff] lemma left.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_left a], simp } /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.nonneg_neg_iff] lemma left.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_left a], simp } @[simp, to_additive] lemma le_inv_mul_iff_mul_le : b ≤ a⁻¹ * c ↔ a * b ≤ c := by { rw ← mul_le_mul_iff_left a, simp } @[simp, to_additive] lemma inv_mul_le_iff_le_mul : b⁻¹ * a ≤ c ↔ a ≤ b * c := by rw [← mul_le_mul_iff_left b, mul_inv_cancel_left] @[to_additive neg_le_iff_add_nonneg'] lemma inv_le_iff_one_le_mul' : a⁻¹ ≤ b ↔ 1 ≤ a * b := (mul_le_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_iff_mul_le_one_left : a ≤ b⁻¹ ↔ b * a ≤ 1 := (mul_le_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma le_inv_mul_iff_le : 1 ≤ b⁻¹ * a ↔ b ≤ a := by rw [← mul_le_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_le_one_iff : a⁻¹ * b ≤ 1 ↔ b ≤ a := trans (inv_mul_le_iff_le_mul) $ by rw mul_one end typeclasses_left_le section typeclasses_left_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c : α} /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_pos_iff] lemma left.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] /-- Uses `left` co(ntra)variant. -/ @[simp, to_additive left.neg_neg_iff] lemma left.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_left a, mul_inv_self, mul_one] @[simp, to_additive] lemma lt_inv_mul_iff_mul_lt : b < a⁻¹ * c ↔ a * b < c := by { rw [← mul_lt_mul_iff_left a], simp } @[simp, to_additive] lemma inv_mul_lt_iff_lt_mul : b⁻¹ * a < c ↔ a < b * c := by rw [← mul_lt_mul_iff_left b, mul_inv_cancel_left] @[to_additive] lemma inv_lt_iff_one_lt_mul' : a⁻¹ < b ↔ 1 < a * b := (mul_lt_mul_iff_left a).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_iff_mul_lt_one' : a < b⁻¹ ↔ b * a < 1 := (mul_lt_mul_iff_left b).symm.trans $ by rw mul_inv_self @[to_additive] lemma lt_inv_mul_iff_lt : 1 < b⁻¹ * a ↔ b < a := by rw [← mul_lt_mul_iff_left b, mul_one, mul_inv_cancel_left] @[to_additive] lemma inv_mul_lt_one_iff : a⁻¹ * b < 1 ↔ b < a := trans (inv_mul_lt_iff_lt_mul) $ by rw mul_one end typeclasses_left_lt section typeclasses_right_le variables [has_le α] [covariant_class α α (swap (*)) (≤)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_nonpos_iff] lemma right.inv_le_one_iff : a⁻¹ ≤ 1 ↔ 1 ≤ a := by { rw [← mul_le_mul_iff_right a], simp } /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.nonneg_neg_iff] lemma right.one_le_inv_iff : 1 ≤ a⁻¹ ↔ a ≤ 1 := by { rw [← mul_le_mul_iff_right a], simp } @[to_additive neg_le_iff_add_nonneg] lemma inv_le_iff_one_le_mul : a⁻¹ ≤ b ↔ 1 ≤ b * a := (mul_le_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma le_inv_iff_mul_le_one_right : a ≤ b⁻¹ ↔ a * b ≤ 1 := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_le_iff_le_mul : a * b⁻¹ ≤ c ↔ a ≤ c * b := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma le_mul_inv_iff_mul_le : c ≤ a * b⁻¹ ↔ c * b ≤ a := (mul_le_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma mul_inv_le_one_iff_le : a * b⁻¹ ≤ 1 ↔ a ≤ b := mul_inv_le_iff_le_mul.trans $ by rw one_mul @[to_additive] lemma le_mul_inv_iff_le : 1 ≤ a * b⁻¹ ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_le_one_iff : b * a⁻¹ ≤ 1 ↔ b ≤ a := trans (mul_inv_le_iff_le_mul) $ by rw one_mul end typeclasses_right_le section typeclasses_right_lt variables [has_lt α] [covariant_class α α (swap (*)) (<)] {a b c : α} /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_neg_iff] lemma right.inv_lt_one_iff : a⁻¹ < 1 ↔ 1 < a := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] /-- Uses `right` co(ntra)variant. -/ @[simp, to_additive right.neg_pos_iff] lemma right.one_lt_inv_iff : 1 < a⁻¹ ↔ a < 1 := by rw [← mul_lt_mul_iff_right a, inv_mul_self, one_mul] @[to_additive] lemma inv_lt_iff_one_lt_mul : a⁻¹ < b ↔ 1 < b * a := (mul_lt_mul_iff_right a).symm.trans $ by rw inv_mul_self @[to_additive] lemma lt_inv_iff_mul_lt_one : a < b⁻¹ ↔ a * b < 1 := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_self @[simp, to_additive] lemma mul_inv_lt_iff_lt_mul : a * b⁻¹ < c ↔ a < c * b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right] @[simp, to_additive] lemma lt_mul_inv_iff_mul_lt : c < a * b⁻¹ ↔ c * b < a := (mul_lt_mul_iff_right b).symm.trans $ by rw inv_mul_cancel_right @[simp, to_additive] lemma inv_mul_lt_one_iff_lt : a * b⁻¹ < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, inv_mul_cancel_right, one_mul] @[to_additive] lemma lt_mul_inv_iff_lt : 1 < a * b⁻¹ ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, inv_mul_cancel_right] @[to_additive] lemma mul_inv_lt_one_iff : b * a⁻¹ < 1 ↔ b < a := trans (mul_inv_lt_iff_lt_mul) $ by rw one_mul end typeclasses_right_lt section typeclasses_left_right_le variables [has_le α] [covariant_class α α (*) (≤)] [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma inv_le_inv_iff : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by { rw [← mul_le_mul_iff_left a, ← mul_le_mul_iff_right b], simp } alias neg_le_neg_iff ↔ le_of_neg_le_neg _ section variable (α) /-- `x ↦ x⁻¹` as an order-reversing equivalence. -/ @[to_additive "`x ↦ -x` as an order-reversing equivalence.", simps] def order_iso.inv : α ≃o order_dual α := { to_equiv := (equiv.inv α).trans order_dual.to_dual, map_rel_iff' := λ a b, @inv_le_inv_iff α _ _ _ _ _ _ } end @[to_additive neg_le] lemma inv_le' : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := (order_iso.inv α).symm_apply_le alias inv_le' ↔ inv_le_of_inv_le' _ attribute [to_additive neg_le_of_neg_le] inv_le_of_inv_le' @[to_additive le_neg] lemma le_inv' : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := (order_iso.inv α).le_symm_apply @[to_additive] lemma mul_inv_le_inv_mul_iff : a * b⁻¹ ≤ d⁻¹ * c ↔ d * a ≤ c * b := by rw [← mul_le_mul_iff_left d, ← mul_le_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_le_self_iff (a : α) {b : α} : a / b ≤ a ↔ 1 ≤ b := by simp [div_eq_mul_inv] alias sub_le_self_iff ↔ _ sub_le_self end typeclasses_left_right_le section typeclasses_left_right_lt variables [has_lt α] [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma inv_lt_inv_iff : a⁻¹ < b⁻¹ ↔ b < a := by { rw [← mul_lt_mul_iff_left a, ← mul_lt_mul_iff_right b], simp } @[to_additive neg_lt] lemma inv_lt' : a⁻¹ < b ↔ b⁻¹ < a := by rw [← inv_lt_inv_iff, inv_inv] @[to_additive lt_neg] lemma lt_inv' : a < b⁻¹ ↔ b < a⁻¹ := by rw [← inv_lt_inv_iff, inv_inv] alias lt_inv' ↔ lt_inv_of_lt_inv _ attribute [to_additive] lt_inv_of_lt_inv alias inv_lt' ↔ inv_lt_of_inv_lt' _ attribute [to_additive neg_lt_of_neg_lt] inv_lt_of_inv_lt' @[to_additive] lemma mul_inv_lt_inv_mul_iff : a * b⁻¹ < d⁻¹ * c ↔ d * a < c * b := by rw [← mul_lt_mul_iff_left d, ← mul_lt_mul_iff_right b, mul_inv_cancel_left, mul_assoc, inv_mul_cancel_right] @[simp, to_additive] lemma div_lt_self_iff (a : α) {b : α} : a / b < a ↔ 1 < b := by simp [div_eq_mul_inv] alias sub_lt_self_iff ↔ _ sub_lt_self end typeclasses_left_right_lt section pre_order variable [preorder α] section left_le variables [covariant_class α α (*) (≤)] {a : α} @[to_additive] lemma left.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (left.inv_le_one_iff.mpr h) h alias left.neg_le_self ← neg_le_self @[to_additive] lemma left.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (left.one_le_inv_iff.mpr h) end left_le section left_lt variables [covariant_class α α (*) (<)] {a : α} @[to_additive] lemma left.inv_lt_self (h : 1 < a) : a⁻¹ < a := (left.inv_lt_one_iff.mpr h).trans h alias left.neg_lt_self ← neg_lt_self @[to_additive] lemma left.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (left.one_lt_inv_iff.mpr h) end left_lt section right_le variables [covariant_class α α (swap (*)) (≤)] {a : α} @[to_additive] lemma right.inv_le_self (h : 1 ≤ a) : a⁻¹ ≤ a := le_trans (right.inv_le_one_iff.mpr h) h @[to_additive] lemma right.self_le_inv (h : a ≤ 1) : a ≤ a⁻¹ := le_trans h (right.one_le_inv_iff.mpr h) end right_le section right_lt variables [covariant_class α α (swap (*)) (<)] {a : α} @[to_additive] lemma right.inv_lt_self (h : 1 < a) : a⁻¹ < a := (right.inv_lt_one_iff.mpr h).trans h @[to_additive] lemma right.self_lt_inv (h : a < 1) : a < a⁻¹ := lt_trans h (right.one_lt_inv_iff.mpr h) end right_lt end pre_order end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive] lemma inv_mul_le_iff_le_mul' : c⁻¹ * a ≤ b ↔ a ≤ b * c := by rw [inv_mul_le_iff_le_mul, mul_comm] @[simp, to_additive] lemma mul_inv_le_iff_le_mul' : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [← inv_mul_le_iff_le_mul, mul_comm] @[to_additive add_neg_le_add_neg_iff] lemma mul_inv_le_mul_inv_iff' : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := by rw [mul_comm c, mul_inv_le_inv_mul_iff, mul_comm] end has_le section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive] lemma inv_mul_lt_iff_lt_mul' : c⁻¹ * a < b ↔ a < b * c := by rw [inv_mul_lt_iff_lt_mul, mul_comm] @[simp, to_additive] lemma mul_inv_lt_iff_le_mul' : a * b⁻¹ < c ↔ a < b * c := by rw [← inv_mul_lt_iff_lt_mul, mul_comm] @[to_additive add_neg_lt_add_neg_iff] lemma mul_inv_lt_mul_inv_iff' : a * b⁻¹ < c * d⁻¹ ↔ a * d < c * b := by rw [mul_comm c, mul_inv_lt_inv_mul_iff, mul_comm] end has_lt end comm_group alias le_inv' ↔ le_inv_of_le_inv _ attribute [to_additive] le_inv_of_le_inv alias left.inv_le_one_iff ↔ one_le_of_inv_le_one _ attribute [to_additive] one_le_of_inv_le_one alias left.one_le_inv_iff ↔ le_one_of_one_le_inv _ attribute [to_additive nonpos_of_neg_nonneg] le_one_of_one_le_inv alias inv_lt_inv_iff ↔ lt_of_inv_lt_inv _ attribute [to_additive] lt_of_inv_lt_inv alias left.inv_lt_one_iff ↔ one_lt_of_inv_lt_one _ attribute [to_additive] one_lt_of_inv_lt_one alias left.inv_lt_one_iff ← inv_lt_one_iff_one_lt attribute [to_additive] inv_lt_one_iff_one_lt alias left.inv_lt_one_iff ← inv_lt_one' attribute [to_additive neg_lt_zero] inv_lt_one' alias left.one_lt_inv_iff ↔ inv_of_one_lt_inv _ attribute [to_additive neg_of_neg_pos] inv_of_one_lt_inv alias left.one_lt_inv_iff ↔ _ one_lt_inv_of_inv attribute [to_additive neg_pos_of_neg] one_lt_inv_of_inv alias le_inv_mul_iff_mul_le ↔ mul_le_of_le_inv_mul _ attribute [to_additive] mul_le_of_le_inv_mul alias le_inv_mul_iff_mul_le ↔ _ le_inv_mul_of_mul_le attribute [to_additive] le_inv_mul_of_mul_le alias inv_mul_le_iff_le_mul ↔ _ inv_mul_le_of_le_mul attribute [to_additive] inv_mul_le_iff_le_mul alias lt_inv_mul_iff_mul_lt ↔ mul_lt_of_lt_inv_mul _ attribute [to_additive] mul_lt_of_lt_inv_mul alias lt_inv_mul_iff_mul_lt ↔ _ lt_inv_mul_of_mul_lt attribute [to_additive] lt_inv_mul_of_mul_lt alias inv_mul_lt_iff_lt_mul ↔ lt_mul_of_inv_mul_lt inv_mul_lt_of_lt_mul attribute [to_additive] lt_mul_of_inv_mul_lt attribute [to_additive] inv_mul_lt_of_lt_mul alias lt_mul_of_inv_mul_lt ← lt_mul_of_inv_mul_lt_left attribute [to_additive] lt_mul_of_inv_mul_lt_left alias left.inv_le_one_iff ← inv_le_one' attribute [to_additive neg_nonpos] inv_le_one' alias left.one_le_inv_iff ← one_le_inv' attribute [to_additive neg_nonneg] one_le_inv' alias left.one_lt_inv_iff ← one_lt_inv' attribute [to_additive neg_pos] one_lt_inv' alias mul_lt_mul_left' ← ordered_comm_group.mul_lt_mul_left' attribute [to_additive ordered_add_comm_group.add_lt_add_left] ordered_comm_group.mul_lt_mul_left' alias le_of_mul_le_mul_left' ← ordered_comm_group.le_of_mul_le_mul_left attribute [to_additive ordered_add_comm_group.le_of_add_le_add_left] ordered_comm_group.le_of_mul_le_mul_left alias lt_of_mul_lt_mul_left' ← ordered_comm_group.lt_of_mul_lt_mul_left attribute [to_additive ordered_add_comm_group.lt_of_add_lt_add_left] ordered_comm_group.lt_of_mul_lt_mul_left /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group [ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul, ..hf.comm_group f one mul inv div } /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_le α] section right variables [covariant_class α α (swap (*)) (≤)] {a b c d : α} @[simp, to_additive] lemma div_le_div_iff_right (c : α) : a / c ≤ b / c ↔ a ≤ b := by simpa only [div_eq_mul_inv] using mul_le_mul_iff_right _ @[to_additive sub_le_sub_right] lemma div_le_div_right' (h : a ≤ b) (c : α) : a / c ≤ b / c := (div_le_div_iff_right c).2 h @[simp, to_additive sub_nonneg] lemma one_le_div' : 1 ≤ a / b ↔ b ≤ a := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonneg ↔ le_of_sub_nonneg sub_nonneg_of_le @[simp, to_additive sub_nonpos] lemma div_le_one' : a / b ≤ 1 ↔ a ≤ b := by rw [← mul_le_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_nonpos ↔ le_of_sub_nonpos sub_nonpos_of_le @[to_additive] lemma le_div_iff_mul_le : a ≤ c / b ↔ a * b ≤ c := by rw [← mul_le_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias le_sub_iff_add_le ↔ add_le_of_le_sub_right le_sub_right_of_add_le @[to_additive] lemma div_le_iff_le_mul : a / c ≤ b ↔ a ≤ b * c := by rw [← mul_le_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] /-- `equiv.mul_right` as an `order_iso`. See also `order_embedding.mul_right`. -/ @[to_additive "`equiv.add_right` as an `order_iso`. See also `order_embedding.add_right`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_right (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_right a, to_equiv := equiv.mul_right a } @[simp, to_additive] lemma order_iso.mul_right_symm (a : α) : (order_iso.mul_right a).symm = order_iso.mul_right a⁻¹ := by { ext x, refl } end right section left variables [covariant_class α α (*) (≤)] /-- `equiv.mul_left` as an `order_iso`. See also `order_embedding.mul_left`. -/ @[to_additive "`equiv.add_left` as an `order_iso`. See also `order_embedding.add_left`.", simps to_equiv apply {simp_rhs := tt}] def order_iso.mul_left (a : α) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_iff_left a, to_equiv := equiv.mul_left a } @[simp, to_additive] lemma order_iso.mul_left_symm (a : α) : (order_iso.mul_left a).symm = order_iso.mul_left a⁻¹ := by { ext x, refl } variables [covariant_class α α (swap (*)) (≤)] {a b c : α} @[simp, to_additive] lemma div_le_div_iff_left (a : α) : a / b ≤ a / c ↔ c ≤ b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_le_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_le_inv_iff] @[to_additive sub_le_sub_left] lemma div_le_div_left' (h : a ≤ b) (c : α) : c / b ≤ c / a := (div_le_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_le variables [has_le α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub_iff] lemma div_le_div_iff' : a / b ≤ c / d ↔ a * d ≤ c * b := by simpa only [div_eq_mul_inv] using mul_inv_le_mul_inv_iff' @[to_additive] lemma le_div_iff_mul_le' : b ≤ c / a ↔ a * b ≤ c := by rw [le_div_iff_mul_le, mul_comm] alias le_sub_iff_add_le' ↔ add_le_of_le_sub_left le_sub_left_of_add_le @[to_additive] lemma div_le_iff_le_mul' : a / b ≤ c ↔ a ≤ b * c := by rw [div_le_iff_le_mul, mul_comm] alias sub_le_iff_le_add' ↔ le_add_of_sub_left_le sub_left_le_of_le_add @[simp, to_additive] lemma inv_le_div_iff_le_mul : b⁻¹ ≤ a / c ↔ c ≤ a * b := le_div_iff_mul_le.trans inv_mul_le_iff_le_mul' @[to_additive] lemma inv_le_div_iff_le_mul' : a⁻¹ ≤ b / c ↔ c ≤ a * b := by rw [inv_le_div_iff_le_mul, mul_comm] @[to_additive sub_le] lemma div_le'' : a / b ≤ c ↔ a / c ≤ b := div_le_iff_le_mul'.trans div_le_iff_le_mul.symm @[to_additive le_sub] lemma le_div'' : a ≤ b / c ↔ c ≤ b / a := le_div_iff_mul_le'.trans le_div_iff_mul_le.symm end has_le section preorder variables [preorder α] [covariant_class α α (*) (≤)] {a b c d : α} @[to_additive sub_le_sub] lemma div_le_div'' (hab : a ≤ b) (hcd : c ≤ d) : a / d ≤ b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_le_inv_mul_iff, mul_comm], exact mul_le_mul' hab hcd end end preorder end comm_group /- Most of the lemmas that are primed in this section appear in ordered_field. -/ /- I (DT) did not try to minimise the assumptions. -/ section group variables [group α] [has_lt α] section right variables [covariant_class α α (swap (*)) (<)] {a b c d : α} @[simp, to_additive] lemma div_lt_div_iff_right (c : α) : a / c < b / c ↔ a < b := by simpa only [div_eq_mul_inv] using mul_lt_mul_iff_right _ @[to_additive sub_lt_sub_right] lemma div_lt_div_right' (h : a < b) (c : α) : a / c < b / c := (div_lt_div_iff_right c).2 h @[simp, to_additive sub_pos] lemma one_lt_div' : 1 < a / b ↔ b < a := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_pos ↔ lt_of_sub_pos sub_pos_of_lt @[simp, to_additive sub_neg] lemma div_lt_one' : a / b < 1 ↔ a < b := by rw [← mul_lt_mul_iff_right b, one_mul, div_eq_mul_inv, inv_mul_cancel_right] alias sub_neg ↔ lt_of_sub_neg sub_neg_of_lt alias sub_neg ← sub_lt_zero @[to_additive] lemma lt_div_iff_mul_lt : a < c / b ↔ a * b < c := by rw [← mul_lt_mul_iff_right b, div_eq_mul_inv, inv_mul_cancel_right] alias lt_sub_iff_add_lt ↔ add_lt_of_lt_sub_right lt_sub_right_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul : a / c < b ↔ a < b * c := by rw [← mul_lt_mul_iff_right c, div_eq_mul_inv, inv_mul_cancel_right] alias sub_lt_iff_lt_add ↔ lt_add_of_sub_right_lt sub_right_lt_of_lt_add end right section left variables [covariant_class α α (*) (<)] [covariant_class α α (swap (*)) (<)] {a b c : α} @[simp, to_additive] lemma div_lt_div_iff_left (a : α) : a / b < a / c ↔ c < b := by rw [div_eq_mul_inv, div_eq_mul_inv, ← mul_lt_mul_iff_left a⁻¹, inv_mul_cancel_left, inv_mul_cancel_left, inv_lt_inv_iff] @[simp, to_additive] lemma inv_lt_div_iff_lt_mul : a⁻¹ < b / c ↔ c < a * b := by rw [div_eq_mul_inv, lt_mul_inv_iff_mul_lt, inv_mul_lt_iff_lt_mul] @[to_additive sub_lt_sub_left] lemma div_lt_div_left' (h : a < b) (c : α) : c / b < c / a := (div_lt_div_iff_left c).2 h end left end group section comm_group variables [comm_group α] section has_lt variables [has_lt α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub_iff] lemma div_lt_div_iff' : a / b < c / d ↔ a * d < c * b := by simpa only [div_eq_mul_inv] using mul_inv_lt_mul_inv_iff' @[to_additive] lemma lt_div_iff_mul_lt' : b < c / a ↔ a * b < c := by rw [lt_div_iff_mul_lt, mul_comm] alias lt_sub_iff_add_lt' ↔ add_lt_of_lt_sub_left lt_sub_left_of_add_lt @[to_additive] lemma div_lt_iff_lt_mul' : a / b < c ↔ a < b * c := by rw [div_lt_iff_lt_mul, mul_comm] alias sub_lt_iff_lt_add' ↔ lt_add_of_sub_left_lt sub_left_lt_of_lt_add @[to_additive] lemma inv_lt_div_iff_lt_mul' : b⁻¹ < a / c ↔ c < a * b := lt_div_iff_mul_lt.trans inv_mul_lt_iff_lt_mul' @[to_additive sub_lt] lemma div_lt'' : a / b < c ↔ a / c < b := div_lt_iff_lt_mul'.trans div_lt_iff_lt_mul.symm @[to_additive lt_sub] lemma lt_div'' : a < b / c ↔ c < b / a := lt_div_iff_mul_lt'.trans lt_div_iff_mul_lt.symm end has_lt section preorder variables [preorder α] [covariant_class α α (*) (<)] {a b c d : α} @[to_additive sub_lt_sub] lemma div_lt_div'' (hab : a < b) (hcd : c < d) : a / d < b / c := begin rw [div_eq_mul_inv, div_eq_mul_inv, mul_comm b, mul_inv_lt_inv_mul_iff, mul_comm], exact mul_lt_mul_of_lt_of_lt hab hcd end end preorder end comm_group section linear_order variables [group α] [linear_order α] [covariant_class α α (*) (≤)] section variable_names variables {a b c : α} @[to_additive] lemma le_of_forall_one_lt_lt_mul (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_not_lt (λ h₁, lt_irrefl a (by simpa using (h _ (lt_inv_mul_iff_lt.mpr h₁)))) @[to_additive] lemma le_iff_forall_one_lt_lt_mul : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul⟩ /- I (DT) introduced this lemma to prove (the additive version `sub_le_sub_flip` of) `div_le_div_flip` below. Now I wonder what is the point of either of these lemmas... -/ @[to_additive] lemma div_le_inv_mul_iff [covariant_class α α (swap (*)) (≤)] : a / b ≤ a⁻¹ * b ↔ a ≤ b := begin rw [div_eq_mul_inv, mul_inv_le_inv_mul_iff], exact ⟨λ h, not_lt.mp (λ k, not_lt.mpr h (mul_lt_mul''' k k)), λ h, mul_le_mul' h h⟩, end /- What is the point of this lemma? See comment about `div_le_inv_mul_iff` above. -/ @[simp, to_additive] lemma div_le_div_flip {α : Type*} [comm_group α] [linear_order α] [covariant_class α α (*) (≤)] {a b : α}: a / b ≤ b / a ↔ a ≤ b := begin rw [div_eq_mul_inv b, mul_comm], exact div_le_inv_mul_iff, end @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end variable_names section densely_ordered variables [densely_ordered α] {a b c : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ c hc, calc a ≤ b * (b⁻¹ * c) : h _ (lt_inv_mul_iff_lt.mpr hc) ... = c : mul_inv_cancel_left b c @[to_additive] lemma le_of_forall_lt_one_mul_le (h : ∀ ε < 1, a * ε ≤ b) : a ≤ b := @le_of_forall_one_lt_le_mul (order_dual α) _ _ _ _ _ _ h @[to_additive] lemma le_of_forall_one_lt_div_le (h : ∀ ε : α, 1 < ε → a / ε ≤ b) : a ≤ b := le_of_forall_lt_one_mul_le $ λ ε ε1, by simpa only [div_eq_mul_inv, inv_inv] using h ε⁻¹ (left.one_lt_inv_iff.2 ε1) @[to_additive] lemma le_iff_forall_one_lt_le_mul : a ≤ b ↔ ∀ ε, 1 < ε → a ≤ b * ε := ⟨λ h ε ε_pos, le_mul_of_le_of_one_le h ε_pos.le, le_of_forall_one_lt_le_mul⟩ @[to_additive] lemma le_iff_forall_lt_one_mul_le : a ≤ b ↔ ∀ ε < 1, a * ε ≤ b := @le_iff_forall_one_lt_le_mul (order_dual α) _ _ _ _ _ _ end densely_ordered end linear_order /-! ### Linearly ordered commutative groups -/ /-- A linearly ordered additive commutative group is an additive commutative group with a linear order in which addition is monotone. -/ @[protect_proj, ancestor ordered_add_comm_group linear_order] class linear_ordered_add_comm_group (α : Type u) extends ordered_add_comm_group α, linear_order α /-- A linearly ordered commutative monoid with an additively absorbing `⊤` element. Instances should include number systems with an infinite element adjoined.` -/ @[protect_proj, ancestor linear_ordered_add_comm_monoid_with_top sub_neg_monoid nontrivial] class linear_ordered_add_comm_group_with_top (α : Type*) extends linear_ordered_add_comm_monoid_with_top α, sub_neg_monoid α, nontrivial α := (neg_top : - (⊤ : α) = ⊤) (add_neg_cancel : ∀ a:α, a ≠ ⊤ → a + (- a) = 0) /-- A linearly ordered commutative group is a commutative group with a linear order in which multiplication is monotone. -/ @[protect_proj, ancestor ordered_comm_group linear_order, to_additive] class linear_ordered_comm_group (α : Type u) extends ordered_comm_group α, linear_order α @[to_additive] instance [linear_ordered_comm_group α] : linear_ordered_comm_group (order_dual α) := { .. order_dual.ordered_comm_group, .. order_dual.linear_order α } section linear_ordered_comm_group variables [linear_ordered_comm_group α] {a b c : α} @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_linear_ordered_cancel_comm_monoid : linear_ordered_cancel_comm_monoid α := { le_of_mul_le_mul_left := λ x y z, le_of_mul_le_mul_left', mul_left_cancel := λ x y z, mul_left_cancel, ..‹linear_ordered_comm_group α› } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) : linear_ordered_comm_group β := { ..linear_order.lift f hf, ..hf.ordered_comm_group f one mul inv div } @[to_additive linear_ordered_add_comm_group.add_lt_add_left] lemma linear_ordered_comm_group.mul_lt_mul_left' (a b : α) (h : a < b) (c : α) : c * a < c * b := mul_lt_mul_left' h c @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α (order_dual α) _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] @[to_additive eq_zero_of_neg_eq] lemma eq_one_of_inv_eq' (h : a⁻¹ = a) : a = 1 := match lt_trichotomy a 1 with | or.inl h₁ := have 1 < a, from h ▸ one_lt_inv_of_inv h₁, absurd h₁ this.asymm | or.inr (or.inl h₁) := h₁ | or.inr (or.inr h₁) := have a < 1, from h ▸ inv_lt_one'.mpr h₁, absurd h₁ this.asymm end @[to_additive exists_zero_lt] lemma exists_one_lt' [nontrivial α] : ∃ (a:α), 1 < a := begin obtain ⟨y, hy⟩ := decidable.exists_ne (1 : α), cases hy.lt_or_lt, { exact ⟨y⁻¹, one_lt_inv'.mpr h⟩ }, { exact ⟨y, h⟩ } end @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_top_order [nontrivial α] : no_top_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a * y, lt_mul_of_one_lt_right' a hy⟩ end ⟩ @[priority 100, to_additive] -- see Note [lower instance priority] instance linear_ordered_comm_group.to_no_bot_order [nontrivial α] : no_bot_order α := ⟨ begin obtain ⟨y, hy⟩ : ∃ (a:α), 1 < a := exists_one_lt', exact λ a, ⟨a / y, (div_lt_self_iff a).mpr hy⟩ end ⟩ end linear_ordered_comm_group section covariant_add_le section has_neg variables [has_neg α] [linear_order α] {a b: α} /-- `mabs a` is the multiplicative absolute value of `a`. -/ @[to_additive abs "`abs a` is the additive absolute value of `a`." ] def mabs {α : Type*} [has_inv α] [lattice α] (a : α) : α := a ⊔ (a⁻¹) lemma abs_eq_max_neg {α : Type*} [has_neg α] [linear_order α] (a : α) : abs a = max a (-a) := begin exact rfl, end lemma abs_choice (x : α) : abs x = x ∨ abs x = -x := max_choice _ _ lemma abs_le' : abs a ≤ b ↔ a ≤ b ∧ -a ≤ b := max_le_iff lemma le_abs : a ≤ abs b ↔ a ≤ b ∨ a ≤ -b := le_max_iff lemma le_abs_self (a : α) : a ≤ abs a := le_max_left _ _ lemma neg_le_abs_self (a : α) : -a ≤ abs a := le_max_right _ _ lemma lt_abs : a < abs b ↔ a < b ∨ a < -b := lt_max_iff theorem abs_le_abs (h₀ : a ≤ b) (h₁ : -a ≤ b) : abs a ≤ abs b := (abs_le'.2 ⟨h₀, h₁⟩).trans (le_abs_self b) lemma abs_by_cases (P : α → Prop) {a : α} (h1 : P a) (h2 : P (-a)) : P (abs a) := sup_ind _ _ h1 h2 end has_neg section add_group variables [add_group α] [linear_order α] @[simp] lemma abs_neg (a : α) : abs (-a) = abs a := begin rw [abs_eq_max_neg, max_comm, neg_neg, abs_eq_max_neg] end lemma eq_or_eq_neg_of_abs_eq {a b : α} (h : abs a = b) : a = b ∨ a = -b := by simpa only [← h, eq_comm, eq_neg_iff_eq_neg] using abs_choice a lemma abs_eq_abs {a b : α} : abs a = abs b ↔ a = b ∨ a = -b := begin refine ⟨λ h, _, λ h, _⟩, { obtain rfl | rfl := eq_or_eq_neg_of_abs_eq h; simpa only [neg_eq_iff_neg_eq, neg_inj, or.comm, @eq_comm _ (-b)] using abs_choice b }, { cases h; simp only [h, abs_neg] }, end lemma abs_sub_comm (a b : α) : abs (a - b) = abs (b - a) := calc abs (a - b) = abs (- (b - a)) : congr_arg _ (neg_sub b a).symm ... = abs (b - a) : abs_neg (b - a) variables [covariant_class α α (+) (≤)] {a b c : α} lemma abs_of_nonneg (h : 0 ≤ a) : abs a = a := max_eq_left $ (neg_nonpos.2 h).trans h lemma abs_of_pos (h : 0 < a) : abs a = a := abs_of_nonneg h.le lemma abs_of_nonpos (h : a ≤ 0) : abs a = -a := max_eq_right $ h.trans (neg_nonneg.2 h) lemma abs_of_neg (h : a < 0) : abs a = -a := abs_of_nonpos h.le @[simp] lemma abs_zero : abs 0 = (0:α) := abs_of_nonneg le_rfl @[simp] lemma abs_pos : 0 < abs a ↔ a ≠ 0 := begin rcases lt_trichotomy a 0 with (ha|rfl|ha), { simp [abs_of_neg ha, neg_pos, ha.ne, ha] }, { simp }, { simp [abs_of_pos ha, ha, ha.ne.symm] } end lemma abs_pos_of_pos (h : 0 < a) : 0 < abs a := abs_pos.2 h.ne.symm lemma abs_pos_of_neg (h : a < 0) : 0 < abs a := abs_pos.2 h.ne lemma neg_abs_le_self (a : α) : -abs a ≤ a := begin cases le_total 0 a with h h, { calc -abs a = - a : congr_arg (has_neg.neg) (abs_of_nonneg h) ... ≤ 0 : neg_nonpos.mpr h ... ≤ a : h }, { calc -abs a = - - a : congr_arg (has_neg.neg) (abs_of_nonpos h) ... ≤ a : (neg_neg a).le } end lemma abs_nonneg (a : α) : 0 ≤ abs a := (le_total 0 a).elim (λ h, h.trans (le_abs_self a)) (λ h, (neg_nonneg.2 h).trans $ neg_le_abs_self a) @[simp] lemma abs_abs (a : α) : abs (abs a) = abs a := abs_of_nonneg $ abs_nonneg a @[simp] lemma abs_eq_zero : abs a = 0 ↔ a = 0 := decidable.not_iff_not.1 $ ne_comm.trans $ (abs_nonneg a).lt_iff_ne.symm.trans abs_pos @[simp] lemma abs_nonpos_iff {a : α} : abs a ≤ 0 ↔ a = 0 := (abs_nonneg a).le_iff_eq.trans abs_eq_zero variable [covariant_class α α (swap (+)) (≤)] lemma abs_lt : abs a < b ↔ - b < a ∧ a < b := max_lt_iff.trans $ and.comm.trans $ by rw [neg_lt] lemma neg_lt_of_abs_lt (h : abs a < b) : -b < a := (abs_lt.mp h).1 lemma lt_of_abs_lt (h : abs a < b) : a < b := (abs_lt.mp h).2 lemma max_sub_min_eq_abs' (a b : α) : max a b - min a b = abs (a - b) := begin cases le_total a b with ab ba, { rw [max_eq_right ab, min_eq_left ab, abs_of_nonpos, neg_sub], rwa sub_nonpos }, { rw [max_eq_left ba, min_eq_right ba, abs_of_nonneg], rwa sub_nonneg } end lemma max_sub_min_eq_abs (a b : α) : max a b - min a b = abs (b - a) := by { rw abs_sub_comm, exact max_sub_min_eq_abs' _ _ } end add_group section add_comm_group variables [add_comm_group α] [linear_order α] [covariant_class α α (+) (≤)] {a b c d : α} lemma abs_le : abs a ≤ b ↔ - b ≤ a ∧ a ≤ b := by rw [abs_le', and.comm, neg_le] lemma neg_le_of_abs_le (h : abs a ≤ b) : -b ≤ a := (abs_le.mp h).1 lemma le_of_abs_le (h : abs a ≤ b) : a ≤ b := (abs_le.mp h).2 /-- The **triangle inequality** in `linear_ordered_add_comm_group`s. -/ lemma abs_add (a b : α) : abs (a + b) ≤ abs a + abs b := abs_le.2 ⟨(neg_add (abs a) (abs b)).symm ▸ add_le_add (neg_le.2 $ neg_le_abs_self _) (neg_le.2 $ neg_le_abs_self _), add_le_add (le_abs_self _) (le_abs_self _)⟩ theorem abs_sub (a b : α) : abs (a - b) ≤ abs a + abs b := by { rw [sub_eq_add_neg, ←abs_neg b], exact abs_add a _ } lemma abs_sub_le_iff : abs (a - b) ≤ c ↔ a - b ≤ c ∧ b - a ≤ c := by rw [abs_le, neg_le_sub_iff_le_add, sub_le_iff_le_add', and_comm, sub_le_iff_le_add'] lemma abs_sub_lt_iff : abs (a - b) < c ↔ a - b < c ∧ b - a < c := by rw [abs_lt, neg_lt_sub_iff_lt_add', sub_lt_iff_lt_add', and_comm, sub_lt_iff_lt_add'] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := sub_le.1 $ (abs_sub_le_iff.1 h).2 lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub_comm a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := sub_lt.1 $ (abs_sub_lt_iff.1 h).2 lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub_comm a b ▸ h) lemma abs_sub_abs_le_abs_sub (a b : α) : abs a - abs b ≤ abs (a - b) := sub_le_iff_le_add.2 $ calc abs a = abs (a - b + b) : by rw [sub_add_cancel] ... ≤ abs (a - b) + abs b : abs_add _ _ lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := abs_sub_le_iff.2 ⟨abs_sub_abs_le_abs_sub _ _, by rw abs_sub_comm; apply abs_sub_abs_le_abs_sub⟩ lemma abs_eq (hb : 0 ≤ b) : abs a = b ↔ a = b ∨ a = -b := begin refine ⟨eq_or_eq_neg_of_abs_eq, _⟩, rintro (rfl|rfl); simp only [abs_neg, abs_of_nonneg hb] end lemma abs_le_max_abs_abs (hab : a ≤ b) (hbc : b ≤ c) : abs b ≤ max (abs a) (abs c) := abs_le'.2 ⟨by simp [hbc.trans (le_abs_self c)], by simp [(neg_le_neg_iff.mpr hab).trans (neg_le_abs_self a)]⟩ lemma eq_of_abs_sub_eq_zero {a b : α} (h : abs (a - b) = 0) : a = b := sub_eq_zero.1 $ abs_eq_zero.1 h lemma abs_sub_le (a b c : α) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rw [sub_add_sub_cancel] ... ≤ abs (a - b) + abs (b - c) : abs_add _ _ lemma abs_add_three (a b c : α) : abs (a + b + c) ≤ abs a + abs b + abs c := (abs_add _ _).trans (add_le_add_right (abs_add _ _) _) lemma dist_bdd_within_interval {a b lb ub : α} (hal : lb ≤ a) (hau : a ≤ ub) (hbl : lb ≤ b) (hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := abs_sub_le_iff.2 ⟨sub_le_sub hau hbl, sub_le_sub hbu hal⟩ lemma eq_of_abs_sub_nonpos (h : abs (a - b) ≤ 0) : a = b := eq_of_abs_sub_eq_zero (le_antisymm h (abs_nonneg (a - b))) lemma abs_max_sub_max_le_abs (a b c : α) : abs (max a c - max b c) ≤ abs (a - b) := begin simp_rw [abs_le, le_sub_iff_add_le, sub_le_iff_le_add, ← max_add_add_left], split; apply max_le_max; simp only [← le_sub_iff_add_le, ← sub_le_iff_le_add, sub_self, neg_le, neg_le_abs_self, neg_zero, abs_nonneg, le_abs_self] end end add_comm_group end covariant_add_le section linear_ordered_add_comm_group variable [linear_ordered_add_comm_group α] instance with_top.linear_ordered_add_comm_group_with_top : linear_ordered_add_comm_group_with_top (with_top α) := { neg := option.map (λ a : α, -a), neg_top := @option.map_none _ _ (λ a : α, -a), add_neg_cancel := begin rintro (a | a) ha, { exact (ha rfl).elim }, { exact with_top.coe_add.symm.trans (with_top.coe_eq_coe.2 (add_neg_self a)) } end, .. with_top.linear_ordered_add_comm_monoid_with_top, .. option.nontrivial } end linear_ordered_add_comm_group /-- This is not so much a new structure as a construction mechanism for ordered groups, by specifying only the "positive cone" of the group. -/ class nonneg_add_comm_group (α : Type*) extends add_comm_group α := (nonneg : α → Prop) (pos : α → Prop := λ a, nonneg a ∧ ¬ nonneg (neg a)) (pos_iff : ∀ a, pos a ↔ nonneg a ∧ ¬ nonneg (-a) . order_laws_tac) (zero_nonneg : nonneg 0) (add_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a + b)) (nonneg_antisymm : ∀ {a}, nonneg a → nonneg (-a) → a = 0) namespace nonneg_add_comm_group variable [s : nonneg_add_comm_group α] include s @[reducible, priority 100] -- see Note [lower instance priority] instance to_ordered_add_comm_group : ordered_add_comm_group α := { le := λ a b, nonneg (b - a), lt := λ a b, pos (b - a), lt_iff_le_not_le := λ a b, by simp; rw [pos_iff]; simp, le_refl := λ a, by simp [zero_nonneg], le_trans := λ a b c nab nbc, by simp [-sub_eq_add_neg]; rw ← sub_add_sub_cancel; exact add_nonneg nbc nab, le_antisymm := λ a b nab nba, eq_of_sub_eq_zero $ nonneg_antisymm nba (by rw neg_sub; exact nab), add_le_add_left := λ a b nab c, by simpa [(≤), preorder.le] using nab, ..s } theorem nonneg_def {a : α} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem pos_def {a : α} : pos a ↔ 0 < a := show _ ↔ pos _, by simp theorem not_zero_pos : ¬ pos (0 : α) := mt pos_def.1 (lt_irrefl _) theorem zero_lt_iff_nonneg_nonneg {a : α} : 0 < a ↔ nonneg a ∧ ¬ nonneg (-a) := pos_def.symm.trans (pos_iff _) theorem nonneg_total_iff : (∀ a : α, nonneg a ∨ nonneg (-a)) ↔ (∀ a b : α, a ≤ b ∨ b ≤ a) := ⟨λ h a b, by have := h (b - a); rwa [neg_sub] at this, λ h a, by rw [nonneg_def, nonneg_def, neg_nonneg]; apply h⟩ /-- A `nonneg_add_comm_group` is a `linear_ordered_add_comm_group` if `nonneg` is total and decidable. -/ def to_linear_ordered_add_comm_group [decidable_pred (@nonneg α _)] (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_ordered_add_comm_group α := { le := (≤), lt := (<), le_total := nonneg_total_iff.1 nonneg_total, decidable_le := by apply_instance, decidable_lt := by apply_instance, ..@nonneg_add_comm_group.to_ordered_add_comm_group _ s } end nonneg_add_comm_group namespace prod variables {G H : Type*} @[to_additive] instance [ordered_comm_group G] [ordered_comm_group H] : ordered_comm_group (G × H) := { .. prod.comm_group, .. prod.partial_order G H, .. prod.ordered_cancel_comm_monoid } end prod section type_tags instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group } end type_tags section norm_num_lemmas /- The following lemmas are stated so that the `norm_num` tactic can use them with the expected signatures. -/ variables [ordered_comm_group α] {a b : α} @[to_additive neg_le_neg] lemma inv_le_inv' : a ≤ b → b⁻¹ ≤ a⁻¹ := inv_le_inv_iff.mpr @[to_additive neg_lt_neg] lemma inv_lt_inv' : a < b → b⁻¹ < a⁻¹ := inv_lt_inv_iff.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] theorem inv_lt_one_of_one_lt : 1 < a → a⁻¹ < 1 := inv_lt_one_iff_one_lt.mpr /- The additive version is also a `linarith` lemma. -/ @[to_additive] lemma inv_le_one_of_one_le : 1 ≤ a → a⁻¹ ≤ 1 := inv_le_one'.mpr @[to_additive neg_nonneg_of_nonpos] lemma one_le_inv_of_le_one : a ≤ 1 → 1 ≤ a⁻¹ := one_le_inv'.mpr end norm_num_lemmas
c72837e3d8beb298d4c36bff7017ba5ba309417c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/succ_pred/relation.lean
31eacfbe6c891deafe91d83a62f22a222d714a88
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,786
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 order.succ_pred.basic /-! # Relations on types with a `succ_order` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains properties about relations on types with a `succ_order` and their closure operations (like the transitive closure). -/ open function order relation set section partial_succ variables {α : Type*} [partial_order α] [succ_order α] [is_succ_archimedean α] /-- For `n ≤ m`, `(n, m)` is in the reflexive-transitive closure of `~` if `i ~ succ i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_succ_of_le (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ico n m, r i (succ i)) (hnm : n ≤ m) : refl_trans_gen r n m := begin revert h, refine succ.rec _ _ hnm, { intros h, exact refl_trans_gen.refl }, { intros m hnm ih h, have : refl_trans_gen r n m := ih (λ i hi, h i ⟨hi.1, hi.2.trans_le $ le_succ m⟩), cases (le_succ m).eq_or_lt with hm hm, { rwa [← hm] }, exact this.tail (h m ⟨hnm, hm⟩) } end /-- For `m ≤ n`, `(n, m)` is in the reflexive-transitive closure of `~` if `succ i ~ i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_succ_of_ge (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ico m n, r (succ i) i) (hmn : m ≤ n) : refl_trans_gen r n m := by { rw [← refl_trans_gen_swap], exact refl_trans_gen_of_succ_of_le (swap r) h hmn } /-- For `n < m`, `(n, m)` is in the transitive closure of a relation `~` if `i ~ succ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_succ_of_lt (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ico n m, r i (succ i)) (hnm : n < m) : trans_gen r n m := (refl_trans_gen_iff_eq_or_trans_gen.mp $ refl_trans_gen_of_succ_of_le r h hnm.le).resolve_left hnm.ne' /-- For `m < n`, `(n, m)` is in the transitive closure of a relation `~` if `succ i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_succ_of_gt (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ico m n, r (succ i) i) (hmn : m < n) : trans_gen r n m := (refl_trans_gen_iff_eq_or_trans_gen.mp $ refl_trans_gen_of_succ_of_ge r h hmn.le).resolve_left hmn.ne end partial_succ section linear_succ variables {α : Type*} [linear_order α] [succ_order α] [is_succ_archimedean α] /-- `(n, m)` is in the reflexive-transitive closure of `~` if `i ~ succ i` and `succ i ~ i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_succ (r : α → α → Prop) {n m : α} (h1 : ∀ i ∈ Ico n m, r i (succ i)) (h2 : ∀ i ∈ Ico m n, r (succ i) i) : refl_trans_gen r n m := (le_total n m).elim (refl_trans_gen_of_succ_of_le r h1) $ refl_trans_gen_of_succ_of_ge r h2 /-- For `n ≠ m`,`(n, m)` is in the transitive closure of a relation `~` if `i ~ succ i` and `succ i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_succ_of_ne (r : α → α → Prop) {n m : α} (h1 : ∀ i ∈ Ico n m, r i (succ i)) (h2 : ∀ i ∈ Ico m n, r (succ i) i) (hnm : n ≠ m) : trans_gen r n m := (refl_trans_gen_iff_eq_or_trans_gen.mp (refl_trans_gen_of_succ r h1 h2)).resolve_left hnm.symm /-- `(n, m)` is in the transitive closure of a reflexive relation `~` if `i ~ succ i` and `succ i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_succ_of_reflexive (r : α → α → Prop) {n m : α} (hr : reflexive r) (h1 : ∀ i ∈ Ico n m, r i (succ i)) (h2 : ∀ i ∈ Ico m n, r (succ i) i) : trans_gen r n m := begin rcases eq_or_ne m n with rfl|hmn, { exact trans_gen.single (hr m) }, exact trans_gen_of_succ_of_ne r h1 h2 hmn.symm end end linear_succ section partial_pred variables {α : Type*} [partial_order α] [pred_order α] [is_pred_archimedean α] /-- For `m ≤ n`, `(n, m)` is in the reflexive-transitive closure of `~` if `i ~ pred i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_pred_of_ge (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ioc m n, r i (pred i)) (hnm : m ≤ n) : refl_trans_gen r n m := @refl_trans_gen_of_succ_of_le αᵒᵈ _ _ _ r n m (λ x hx, h x ⟨hx.2, hx.1⟩) hnm /-- For `n ≤ m`, `(n, m)` is in the reflexive-transitive closure of `~` if `pred i ~ i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_pred_of_le (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ioc n m, r (pred i) i) (hmn : n ≤ m) : refl_trans_gen r n m := @refl_trans_gen_of_succ_of_ge αᵒᵈ _ _ _ r n m (λ x hx, h x ⟨hx.2, hx.1⟩) hmn /-- For `m < n`, `(n, m)` is in the transitive closure of a relation `~` for `n ≠ m` if `i ~ pred i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_pred_of_gt (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ioc m n, r i (pred i)) (hnm : m < n) : trans_gen r n m := @trans_gen_of_succ_of_lt αᵒᵈ _ _ _ r _ _ (λ x hx, h x ⟨hx.2, hx.1⟩) hnm /-- For `n < m`, `(n, m)` is in the transitive closure of a relation `~` for `n ≠ m` if `pred i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_pred_of_lt (r : α → α → Prop) {n m : α} (h : ∀ i ∈ Ioc n m, r (pred i) i) (hmn : n < m) : trans_gen r n m := @trans_gen_of_succ_of_gt αᵒᵈ _ _ _ r _ _ (λ x hx, h x ⟨hx.2, hx.1⟩) hmn end partial_pred section linear_pred variables {α : Type*} [linear_order α] [pred_order α] [is_pred_archimedean α] /-- `(n, m)` is in the reflexive-transitive closure of `~` if `i ~ pred i` and `pred i ~ i` for all `i` between `n` and `m`. -/ lemma refl_trans_gen_of_pred (r : α → α → Prop) {n m : α} (h1 : ∀ i ∈ Ioc m n, r i (pred i)) (h2 : ∀ i ∈ Ioc n m, r (pred i) i) : refl_trans_gen r n m := @refl_trans_gen_of_succ αᵒᵈ _ _ _ r n m (λ x hx, h1 x ⟨hx.2, hx.1⟩) (λ x hx, h2 x ⟨hx.2, hx.1⟩) /-- For `n ≠ m`, `(n, m)` is in the transitive closure of a relation `~` if `i ~ pred i` and `pred i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_pred_of_ne (r : α → α → Prop) {n m : α} (h1 : ∀ i ∈ Ioc m n, r i (pred i)) (h2 : ∀ i ∈ Ioc n m, r (pred i) i) (hnm : n ≠ m) : trans_gen r n m := @trans_gen_of_succ_of_ne αᵒᵈ _ _ _ r n m (λ x hx, h1 x ⟨hx.2, hx.1⟩) (λ x hx, h2 x ⟨hx.2, hx.1⟩) hnm /-- `(n, m)` is in the transitive closure of a reflexive relation `~` if `i ~ pred i` and `pred i ~ i` for all `i` between `n` and `m`. -/ lemma trans_gen_of_pred_of_reflexive (r : α → α → Prop) {n m : α} (hr : reflexive r) (h1 : ∀ i ∈ Ioc m n, r i (pred i)) (h2 : ∀ i ∈ Ioc n m, r (pred i) i) : trans_gen r n m := @trans_gen_of_succ_of_reflexive αᵒᵈ _ _ _ r n m hr (λ x hx, h1 x ⟨hx.2, hx.1⟩) (λ x hx, h2 x ⟨hx.2, hx.1⟩) end linear_pred
2d3d6b2451cd5a13d7b65e383b0672087945e85d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Util/FindExpr.lean
ef36cd64c96c617f2d2e0e811221f9d8b3218c23
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach" ]
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,734
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean namespace Expr namespace FindImpl abbrev cacheSize : USize := 8192 structure State where keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr abbrev FindM := StateT State Id unsafe def visited (e : Expr) (size : USize) : FindM Bool := do let s ← get let h := ptrAddrUnsafe e let i := h % size let k := s.keys.uget i lcProof if ptrAddrUnsafe k == h then pure true else modify fun s => { keys := s.keys.uset i e lcProof } pure false unsafe def findM? (p : Expr → Bool) (size : USize) (e : Expr) : OptionT FindM Expr := let rec visit (e : Expr) := do if (← visited e size) then failure else if p e then pure e else match e with | Expr.forallE _ d b _ => visit d <|> visit b | Expr.lam _ d b _ => visit d <|> visit b | Expr.mdata _ b => visit b | Expr.letE _ t v b _ => visit t <|> visit v <|> visit b | Expr.app f a => visit f <|> visit a | Expr.proj _ _ b => visit b | _ => failure visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()) } unsafe def findUnsafe? (p : Expr → Bool) (e : Expr) : Option Expr := Id.run <| findM? p cacheSize e |>.run' initCache end FindImpl @[implementedBy FindImpl.findUnsafe?] def find? (p : Expr → Bool) (e : Expr) : Option Expr := /- This is a reference implementation for the unsafe one above -/ if p e then some e else match e with | Expr.forallE _ d b _ => find? p d <|> find? p b | Expr.lam _ d b _ => find? p d <|> find? p b | Expr.mdata _ b => find? p b | Expr.letE _ t v b _ => find? p t <|> find? p v <|> find? p b | Expr.app f a => find? p f <|> find? p a | Expr.proj _ _ b => find? p b | _ => none /-- Return true if `e` occurs in `t` -/ def occurs (e : Expr) (t : Expr) : Bool := (t.find? fun s => s == e).isSome /-- Return type for `findExt?` function argument. -/ inductive FindStep where /-- Found desired subterm -/ | found /-- Search subterms -/ | visit /-- Do not search subterms -/ | done namespace FindExtImpl unsafe def findM? (p : Expr → FindStep) (size : USize) (e : Expr) : OptionT FindImpl.FindM Expr := visit e where visitApp (e : Expr) := match e with | Expr.app f a .. => visitApp f <|> visit a | e => visit e visit (e : Expr) := do if (← FindImpl.visited e size) then failure else match p e with | FindStep.done => failure | FindStep.found => pure e | FindStep.visit => match e with | Expr.forallE _ d b _ => visit d <|> visit b | Expr.lam _ d b _ => visit d <|> visit b | Expr.mdata _ b => visit b | Expr.letE _ t v b _ => visit t <|> visit v <|> visit b | Expr.app .. => visitApp e | Expr.proj _ _ b => visit b | _ => failure unsafe def findUnsafe? (p : Expr → FindStep) (e : Expr) : Option Expr := Id.run <| findM? p FindImpl.cacheSize e |>.run' FindImpl.initCache end FindExtImpl /-- Similar to `find?`, but `p` can return `FindStep.done` to interrupt the search on subterms. Remark: Differently from `find?`, we do not invoke `p` for partial applications of an application. -/ @[implementedBy FindExtImpl.findUnsafe?] opaque findExt? (p : Expr → FindStep) (e : Expr) : Option Expr end Expr end Lean
fcab812d33e9da79d744caedad7f6307a7675430
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/calc1.lean
28a3986f803d4eb0350bd9e340ea8539a4579f34
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,570
lean
prelude constant A : Type.{1} definition bool : Type.{1} := Type.{0} constant eq : A → A → bool infixl `=`:50 := eq axiom subst (P : A → bool) (a b : A) (H1 : a = b) (H2 : P a) : P b axiom eq_trans (a b c : A) (H1 : a = b) (H2 : b = c) : a = c axiom eq_refl (a : A) : a = a constant le : A → A → bool infixl `≤`:50 := le axiom le_trans (a b c : A) (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c axiom le_refl (a : A) : a ≤ a axiom eq_le_trans (a b c : A) (H1 : a = b) (H2 : b ≤ c) : a ≤ c axiom le_eq_trans (a b c : A) (H1 : a ≤ b) (H2 : b = c) : a ≤ c calc_subst subst calc_refl eq_refl calc_refl le_refl calc_trans eq_trans calc_trans le_trans calc_trans eq_le_trans calc_trans le_eq_trans constants a b c d e f : A axiom H1 : a = b axiom H2 : b ≤ c axiom H3 : c ≤ d axiom H4 : d = e check calc a = b : H1 ... ≤ c : H2 ... ≤ d : H3 ... = e : H4 constant lt : A → A → bool infixl `<`:50 := lt axiom lt_trans (a b c : A) (H1 : a < b) (H2 : b < c) : a < c axiom le_lt_trans (a b c : A) (H1 : a ≤ b) (H2 : b < c) : a < c axiom lt_le_trans (a b c : A) (H1 : a < b) (H2 : b ≤ c) : a < c axiom H5 : c < d check calc b ≤ c : H2 ... < d : H5 -- Error le_lt_trans was not registered yet calc_trans le_lt_trans check calc b ≤ c : H2 ... < d : H5 constant le2 : A → A → bool infixl `≤`:50 := le2 constant le2_trans (a b c : A) (H1 : le2 a b) (H2 : le2 b c) : le2 a c calc_trans le2_trans print raw calc b ≤ c : H2 ... ≤ d : H3 ... ≤ e : H4