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
6f42fbbf4a9934112b77f1feaceb306cf34749b6
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/order/lower_topology.lean
0ed69357c94a12c601225f35a4d9eb43420c31f8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,420
lean
/- Copyright (c) 2023 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.homeomorph import topology.order.lattice import order.hom.complete_lattice /-! # Lower topology > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file introduces the lower topology on a preorder as the topology generated by the complements of the closed intervals to infinity. ## Main statements - `lower_topology.t0_space` - the lower topology on a partial order is T₀ - `is_topological_basis.is_topological_basis` - the complements of the upper closures of finite subsets form a basis for the lower topology - `lower_topology.to_has_continuous_inf` - the inf map is continuous with respect to the lower topology ## Implementation notes A type synonym `with_lower_topology` is introduced and for a preorder `α`, `with_lower_topology α` is made an instance of `topological_space` by the topology generated by the complements of the closed intervals to infinity. We define a mixin class `lower_topology` for the class of types which are both a preorder and a topology and where the topology is generated by the complements of the closed intervals to infinity. It is shown that `with_lower_topology α` is an instance of `lower_topology`. ## Motivation The lower topology is used with the `Scott` topology to define the Lawson topology. The restriction of the lower topology to the spectrum of a complete lattice coincides with the hull-kernel topology. ## References * [Gierz et al, *A Compendium of Continuous Lattices*][GierzEtAl1980] ## Tags lower topology, preorder -/ variables (α β : Type*) open set topological_space /-- Type synonym for a preorder equipped with the lower topology -/ def with_lower_topology := α variables {α β} namespace with_lower_topology /-- `to_lower` is the identity function to the `with_lower_topology` of a type. -/ @[pattern] def to_lower : α ≃ with_lower_topology α := equiv.refl _ /-- `of_lower` is the identity function from the `with_lower_topology` of a type. -/ @[pattern] def of_lower : with_lower_topology α ≃ α := equiv.refl _ @[simp] lemma to_with_lower_topology_symm_eq : (@to_lower α).symm = of_lower := rfl @[simp] lemma of_with_lower_topology_symm_eq : (@of_lower α).symm = to_lower := rfl @[simp] lemma to_lower_of_lower (a : with_lower_topology α) : to_lower (of_lower a) = a := rfl @[simp] lemma of_lower_to_lower (a : α) : of_lower (to_lower a) = a := rfl @[simp] lemma to_lower_inj {a b : α} : to_lower a = to_lower b ↔ a = b := iff.rfl @[simp] lemma of_lower_inj {a b : with_lower_topology α} : of_lower a = of_lower b ↔ a = b := iff.rfl /-- A recursor for `with_lower_topology`. Use as `induction x using with_lower_topology.rec`. -/ protected def rec {β : with_lower_topology α → Sort*} (h : Π a, β (to_lower a)) : Π a, β a := λ a, h (of_lower a) instance [nonempty α] : nonempty (with_lower_topology α) := ‹nonempty α› instance [inhabited α] : inhabited (with_lower_topology α) := ‹inhabited α› variables [preorder α] instance : preorder (with_lower_topology α) := ‹preorder α› instance : topological_space (with_lower_topology α) := generate_from {s | ∃ a, (Ici a)ᶜ = s} lemma is_open_preimage_of_lower (S : set α) : is_open (with_lower_topology.of_lower ⁻¹' S) ↔ (generate_from {s : set α | ∃ (a : α), (Ici a)ᶜ = s}).is_open S := iff.rfl lemma is_open_def (T : set (with_lower_topology α)) : is_open T ↔ (generate_from {s : set α | ∃ (a : α), (Ici a)ᶜ = s}).is_open (with_lower_topology.to_lower ⁻¹' T) := iff.rfl end with_lower_topology /-- The lower topology is the topology generated by the complements of the closed intervals to infinity. -/ class lower_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (topology_eq_lower_topology [] : t = generate_from {s | ∃ a, (Ici a)ᶜ = s}) instance [preorder α] : lower_topology (with_lower_topology α) := ⟨rfl⟩ namespace lower_topology /-- The complements of the upper closures of finite sets are a collection of lower sets which form a basis for the lower topology. -/ def lower_basis (α : Type*) [preorder α] := {s : set α | ∃ t : set α, t.finite ∧ (upper_closure t : set α)ᶜ = s} section preorder variables [preorder α] [topological_space α] [lower_topology α] {s : set α} /-- If `α` is equipped with the lower topology, then it is homeomorphic to `with_lower_topology α`. -/ def with_lower_topology_homeomorph : with_lower_topology α ≃ₜ α := { continuous_to_fun := by { convert continuous_id, apply topology_eq_lower_topology }, continuous_inv_fun := by { convert ← continuous_id, apply topology_eq_lower_topology }, ..with_lower_topology.of_lower } lemma is_open_iff_generate_Ici_compl : is_open s ↔ generate_open {t | ∃ a, (Ici a)ᶜ = t} s := by rw topology_eq_lower_topology α; refl /-- Left-closed right-infinite intervals [a, ∞) are closed in the lower topology. -/ lemma is_closed_Ici (a : α) : is_closed (Ici a) := is_open_compl_iff.1 $ is_open_iff_generate_Ici_compl.2 $ generate_open.basic _ ⟨a, rfl⟩ /-- The upper closure of a finite set is closed in the lower topology. -/ lemma is_closed_upper_closure (h : s.finite) : is_closed (upper_closure s : set α) := begin simp only [← upper_set.infi_Ici, upper_set.coe_infi], exact is_closed_bUnion h (λ a h₁, is_closed_Ici a), end /-- Every set open in the lower topology is a lower set. -/ lemma is_lower_set_of_is_open (h : is_open s) : is_lower_set s := begin rw is_open_iff_generate_Ici_compl at h, induction h, case generate_open.basic : u h { obtain ⟨a, rfl⟩ := h, exact (is_upper_set_Ici a).compl }, case univ : { exact is_lower_set_univ }, case inter : u v hu1 hv1 hu2 hv2 { exact hu2.inter hv2 }, case sUnion : _ _ ih { exact is_lower_set_sUnion ih }, end lemma is_upper_set_of_is_closed (h : is_closed s) : is_upper_set s := is_lower_set_compl.1 $ is_lower_set_of_is_open h.is_open_compl /-- The closure of a singleton `{a}` in the lower topology is the left-closed right-infinite interval [a, ∞). -/ @[simp] lemma closure_singleton (a : α) : closure {a} = Ici a := subset_antisymm (closure_minimal (λ b h, h.ge) $ is_closed_Ici a) $ (is_upper_set_of_is_closed is_closed_closure).Ici_subset $ subset_closure rfl protected lemma is_topological_basis : is_topological_basis (lower_basis α) := begin convert is_topological_basis_of_subbasis (topology_eq_lower_topology α), simp_rw [lower_basis, coe_upper_closure, compl_Union], ext s, split, { rintro ⟨F, hF, rfl⟩, refine ⟨(λ a, (Ici a)ᶜ) '' F, ⟨hF.image _, image_subset_iff.2 $ λ _ _, ⟨_, rfl⟩⟩, _⟩, rw sInter_image }, { rintro ⟨F, ⟨hF, hs⟩, rfl⟩, haveI := hF.to_subtype, rw [subset_def, subtype.forall'] at hs, choose f hf using hs, exact ⟨_, finite_range f, by simp_rw [bInter_range, hf, sInter_eq_Inter]⟩ } end end preorder section partial_order variables [partial_order α] [topological_space α] [lower_topology α] /-- The lower topology on a partial order is T₀. -/ @[priority 90] -- see Note [lower instance priority] instance : t0_space α := (t0_space_iff_inseparable α).2 $ λ x y h, Ici_injective $ by simpa only [inseparable_iff_closure_eq, closure_singleton] using h end partial_order end lower_topology instance [preorder α] [topological_space α] [lower_topology α] [order_bot α] [preorder β] [topological_space β] [lower_topology β] [order_bot β] : lower_topology (α × β) := { topology_eq_lower_topology := begin refine le_antisymm (le_generate_from _) _, { rintro _ ⟨x, rfl⟩, exact ((lower_topology.is_closed_Ici _).prod $ lower_topology.is_closed_Ici _).is_open_compl }, rw [(lower_topology.is_topological_basis.prod lower_topology.is_topological_basis).eq_generate_from, le_generate_from_iff_subset_is_open, image2_subset_iff], rintro _ ⟨s, hs, rfl⟩ _ ⟨t, ht, rfl⟩, dsimp, simp_rw [coe_upper_closure, compl_Union, prod_eq, preimage_Inter, preimage_compl], -- Note: `refine` doesn't work here because it tries using `prod.topological_space`. apply (is_open_bInter hs $ λ a _, _).inter (is_open_bInter ht $ λ b _, _), { exact generate_open.basic _ ⟨(a, ⊥), by simp [Ici_prod_eq, prod_univ]⟩ }, { exact generate_open.basic _ ⟨(⊥, b), by simp [Ici_prod_eq, univ_prod]⟩ }, all_goals { apply_instance }, end } section complete_lattice variables [complete_lattice α] [complete_lattice β] [topological_space α] [lower_topology α] [topological_space β] [lower_topology β] lemma Inf_hom.continuous (f : Inf_hom α β) : continuous f := begin convert continuous_generated_from _, { exact lower_topology.topology_eq_lower_topology β }, rintro _ ⟨b, rfl⟩, rw [preimage_compl, is_open_compl_iff], convert lower_topology.is_closed_Ici (Inf $ f ⁻¹' Ici b), refine subset_antisymm (λ a, Inf_le) (λ a ha, le_trans _ $ order_hom_class.mono f ha), simp [map_Inf], end @[priority 90] -- see Note [lower instance priority] instance lower_topology.to_has_continuous_inf : has_continuous_inf α := ⟨(inf_Inf_hom : Inf_hom (α × α) α).continuous⟩ end complete_lattice
5d7c75ff00cedda4470e447e96164358a356027a
cb3da1b91380e7462b579b426a278072c688954a
/src/iteration.lean
46166b9e528db34fa5ca9d976374f074cd374103
[]
no_license
hcheval/tikhonov-mann
35c93e46a8287f6479a848a9d4f02013e0bc2035
6ab7fcefe9e1156c20bd5d1998a7deabd1eeb018
refs/heads/master
1,689,232,126,344
1,630,182,255,000
1,630,182,255,000
399,859,996
0
0
null
null
null
null
UTF-8
Lean
false
false
26,319
lean
import wspace import rates import xu import utils open metric_space local notation `|` x `|` := abs x @[simp] def tikhonov_mann {X : Type*} [whyperbolic_space X] (T : X → X) (o : X) (l β : ℕ → ℝ) (x₀ : X) : ℕ → X | 0 := x₀ | (n + 1) := wmap (l n) (wmap (β n) o (tikhonov_mann n)) (T (wmap (β n) o (tikhonov_mann n))) section open whyperbolic_space -- using parameters for the hypotheses was a bad idea. -- do not repeat parameters {X : Type*} [whyperbolic_space X] parameters (T : X → X) (o : X) (l β : ℕ → ℝ) (x₀ : X) (p : X) parameters (Tne : ∀ s t : X, dist (T s) (T t) ≤ dist s t) (p_fp_T : T p = p) (h_p_neq_o : p ≠ o) parameters (l_pos : ∀ {n : ℕ}, 0 < l n) (hl1 : ∀ {n : ℕ}, l n ≤ 1) parameters (β_pos : ∀ {n : ℕ}, 0 < β n) (hβ1 : ∀ {n : ℕ}, β n ≤ 1) include Tne p_fp_T h_p_neq_o l_pos hl1 β_pos hβ1 def x : ℕ → X := tikhonov_mann T o l β x₀ def y (n : ℕ) : X := wmap (β n) o (x n) noncomputable def M := max (dist p x₀) (dist p o) lemma x_y : ∀ n : ℕ, x (n + 1) = wmap (l n) (y n) (T $ y n) := by intros n; induction n; simp [x, y] lemma hl0 : ∀ {n : ℕ}, 0 ≤ l n := λ _, le_of_lt l_pos lemma hβ0 : ∀ {n : ℕ}, 0 ≤ β n := λ _, le_of_lt β_pos lemma dist_p_o_pos : 0 < dist p o := begin refine (ne.le_iff_lt _).mp dist_nonneg, intros h, have : dist p o = 0 := h.symm, have := metric_space.eq_of_dist_eq_zero this, contradiction, end lemma M_pos : 0 < M := lt_max_of_lt_right dist_p_o_pos lemma M_nonneg : 0 ≤ M := le_of_lt M_pos lemma M_double_nonneg : 0 ≤ 2 * M := mul_nonneg zero_le_two M_nonneg lemma left_le_M : dist p x₀ ≤ M := by simp [M] lemma right_le_M : dist p o ≤ M := by simp [M] -- # Corresponding to lemmas 3.1 and 3.2 lemma l_3_1_i : ∀ n : ℕ, dist p (x $ n + 1) ≤ (1 - (β n)) * (dist p o) + (β n) * (dist p (x n)) := λ n, calc dist p (x $ n + 1) ≤ (1 - l n) * (dist p (y n)) + (l n) * (dist p (T $ y n)) : dist_conv _ _ _ hl0 hl1 ... = (1 - l n) * (dist p (y n)) + (l n) * dist (T p) (T $ y n) : by rw p_fp_T ... ≤ (1 - l n) * (dist p (y n)) + (l n) * dist p (y n) : by { have := @hl0 n, have := @hl1 n, nlinarith [Tne p (y n)], } ... = dist p (y n) : by { ring, } ... ≤ (1 - (β n)) * (dist p o) + (β n) * (dist p (x n)) : dist_conv _ _ _ hβ0 hβ1 lemma l_3_1_ii_i : ∀ n : ℕ, dist p (x n) ≤ M := begin intros n, induction n, case zero { simp [M, x], }, case succ: n ih { calc dist p (x $ n + 1) ≤ (1 - (β n)) * (dist p o) + (β n) * (dist p (x n)) : l_3_1_i n ... ≤ (1 - (β n)) * M + (β n) * (dist p (x n)) : by { have : dist p o ≤ M := by simp [M], nlinarith [@hβ0 n, @hβ1 n], } ... ≤ (1 - (β n)) * M + (β n) * M : by { nlinarith [@hβ0 n, @hβ1 n, ih], } ... ≤ M : by ring, } end lemma l_3_1_ii_ii : ∀ n : ℕ, dist (x n) o ≤ 2 * M := λ n, calc dist (x n) o ≤ dist (x n) p + dist p o : dist_triangle _ _ _ ... ≤ M + dist p o : by{ nth_rewrite 0 dist_comm, linarith [l_3_1_ii_i n], } ... ≤ M + M : by {have : dist p o ≤ M := by simp [M], linarith, } ... = 2 * M : by ring lemma l_3_1_iii_i : ∀ n : ℕ, dist p (y n) ≤ M := λ n, calc dist p (y n) ≤ (1 - β n) * (dist p o) + (β n) * (dist p (x n)) : dist_conv _ _ _ hβ0 hβ1 ... ≤ (1 - β n) * M + (β n) * (dist p (x n)) : by nlinarith [right_le_M, @hβ0 n, @hβ1 n] ... ≤ (1 - β n) * M + (β n) * M : by nlinarith [@hβ0 n, @hβ1 n, @l_3_1_ii_i n] ... = M : by ring lemma l_3_1_iii_ii : ∀ n : ℕ, dist (y n) (T $ y n) ≤ 2 * M := λ n, calc dist (y n) (T $ y n) ≤ dist (y n) p + dist p (T $ y n) : dist_triangle _ _ _ ... = dist (y n) p + dist (T p) (T $ y n) : by rw p_fp_T ... ≤ dist (y n) p + dist p (y n) : by nlinarith [Tne p (y n)] ... = dist p (y n) + dist p (y n) : by rw dist_comm ... ≤ M + M : by nlinarith [l_3_1_iii_i n] ... = 2 * M : by ring lemma l_3_2_i : ∀ n : ℕ, dist (y $ n + 1) (y n) ≤ (β $ n + 1) * (dist (x $ n + 1) (x n)) + 2 * M * |(β $ n + 1) - β n| := λ n, calc dist (y $ n + 1) (y n) ≤ (β $ n + 1) * (dist (x $ n + 1) (x n)) + |(β $ n + 1) - β n| * (dist o (x n)) : @dist_wmap_same_first _ _ _ _ o (x $ n + 1)(x n) (@hβ0 $ n + 1) (@hβ1 $ n + 1) (@hβ0 n) (@hβ1 n) ... ≤ (β $ n + 1) * (dist (x $ n + 1) (x n)) + |(β $ n + 1) - β n| * (2 * M) : by { nth_rewrite 1 dist_comm, nlinarith [M_pos, l_3_1_ii_ii n, abs_nonneg (β (n + 1) - β n)], } ... = (β $ n + 1) * (dist (x $ n + 1) (x n)) + 2 * M * |(β $ n + 1) - β n| : by ring lemma l_3_2_ii : ∀ n : ℕ, dist (x $ n + 2) (x $ n + 1) ≤ (β $ n + 1) * (dist (x $ n + 1) (x n)) + 2 * M * (|(β $ n + 1) - β n| + |(l $ n + 1) - l n|) := λ n, calc dist (x $ n + 2) (x $ n + 1) = dist (wmap (l $ n + 1) (y $ n + 1) (T $ y $ n + 1)) (wmap (l n) (y n) (T $ y n)) : by simp [x_y] ... ≤ (1 - l (n + 1)) * (dist (y $ n + 1) (y n)) + (l $ n + 1) * (dist (T $ y $ n + 1) (T $ y $ n)) + |l (n + 1) - l n| * (dist (y n) (T $ y $ n)) : dist_wmap hl0 hl1 hl0 hl1 ... ≤ (1 - l (n + 1)) * (dist (y $ n + 1) (y n)) + (l $ n + 1) * (dist (y $ n + 1) (y n)) + |l (n + 1) - l n| * (dist (y n) (T $ y $ n)) : by nlinarith [Tne (y $ n + 1) (y n), @hl0 (n + 1)] ... = dist (y $ n + 1) (y n) + |l (n + 1) - l n| * (dist (y n) (T $ y n)) : by ring ... ≤ dist (y $ n + 1) (y n) + |l (n + 1) - l n| * (2 * M) : by nlinarith [l_3_1_iii_ii n, abs_nonneg (l (n + 1) - l n)] ... ≤ (β $ n + 1) * (dist (x $ n + 1) (x n)) + 2 * M * |(β $ n + 1) - β n| + |l (n + 1) - l n| * (2 * M) : by nlinarith [l_3_2_i n, abs_nonneg (l (n + 1) - l n)] ... = (β $ n + 1) * (dist (x $ n + 1) (x n)) + 2 * M * (|(β $ n + 1) - β n| + |(l $ n + 1) - l n|) : by ring lemma l_3_2_iii : ∀ n : ℕ, dist (x n) (y n) = (1 - β n) * (dist o (x n)) := begin intros n, have h₁ := @hβ0 n, have h₂ := @hβ1 n, simp only [y], rw [dist_self_wmap_right h₁ h₂], end lemma l_3_2_iv : ∀ n : ℕ, dist (x n) (T $ x n) ≤ dist (x n) (x $ n + 1) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) := λ n, calc dist (x n) (T $ x n) ≤ dist (x n) (x $ n + 1) + dist (x $ n + 1) (T $ x n) : dist_triangle _ _ _ ... = dist (x n) (x $ n + 1) + dist (wmap (l n) (y n) (T $ y n)) (T $ x n) : by simp [x_y] ... = dist (x n) (x $ n + 1) + dist (T $ x n) (wmap (l n) (y n) (T $ y n)) : by nth_rewrite 1 dist_comm ... ≤ (dist (x n) (x $ n + 1)) + (1 - l n) * (dist (y n) (T $ x n)) + (l n) * (dist (T $ y n) (T $ x n)) : by{ rw [dist_comm (y n) (T $ x n), dist_comm (T $ y n) (T $ x n)], nlinarith [dist_conv (y n) (T $ y n) (T $ x n) (@hl0 n) (@hl1 n)], } ... ≤ (dist (x n) (x $ n + 1)) + (1 - l n) * (dist (y n) (T $ x n)) + (l n) * (dist (y n) (x n)) : by nlinarith [Tne (y n) (x n), @hl0 n] ... ≤ (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (dist (y n) (T $ x n)) : by ring ... ≤ (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (dist (y n) (wmap (β n) o (T $ x n)) + dist (wmap (β n) o (T $ x n)) (T $ x n)) : by nlinarith [dist_triangle (y n) (wmap (β n) o (T $ x n)) (T $ x n), @hl0 n, sub_nonneg.mpr (@hl1 n)] ... = (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (dist (y n) (wmap (β n) o (T $ x n))) + (1 - l n) * (dist (wmap (β n) o (T $ x n)) (T $ x n)) : by ring ... = (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (dist (y n) (wmap (β n) o (T $ x n))) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) : by { rw [dist_comm (wmap (β n) o (T $ x n)) (T $ x n), dist_self_wmap_right hβ0 hβ1], ring, } ... = (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) + (1 - l n) * (dist (y n) (wmap (β n) o (T $ x n))) : by ring ... = (dist (x n) (x $ n + 1)) + (l n) * (dist (y n) (x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) + (1 - l n) * (dist (wmap (β n) o (x n)) (wmap (β n) o (T $ x n))) : by simp [y] ... = (dist (x n) (x $ n + 1)) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) + (1 - l n) * (dist (wmap (β n) o (x n)) (wmap (β n) o (T $ x n))) : by { rw [dist_comm (y n) (x n)], have : dist (x n) (y n) = (1 - β n) * dist o (x n) := l_3_2_iii n, simp only [*, add_left_inj, add_right_inj], ring, } ... ≤ (dist (x n) (x $ n + 1)) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) : by nlinarith [sub_nonneg.mpr (@hl1 n), @wmap_same_coeff_same_firt _ _ _ o (x n) (T $ x n) (@hβ0 n) (@hβ1 n)] ... = dist (x n) (x $ n + 1) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) : by ring lemma l_3_2_v : ∀ n : ℕ, (l n) * (dist (x n) (T $ x n)) ≤ dist (x n) (x $ n + 1) + 2 * M * (1 - β n) := λ n, begin have h₁ : dist (x n) (T $ x n) ≤ dist (x n) (x $ n + 1) + (1 - β n) * (2 * M) + (1 - l n) * (dist (x n) (T $ x n)), calc dist (x n) (T $ x n) ≤ dist (x n) (x $ n + 1) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) + (1 - l n) * (1 - β n) * (dist o (T $ x n)) : by apply l_3_2_iv ... ≤ dist (x n) (x $ n + 1) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) + (1 - l n) * (1 - β n) * ((dist o (x n)) + (dist (x n) (T $ x n))) : by nlinarith [mul_nonneg (sub_nonneg.mpr $ @hl1 n) (sub_nonneg.mpr $ @hβ1 n), dist_triangle o (x n) (T $ x n)] ... = dist (x n) (x $ n + 1) + (l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (β n) * (dist (x n) (T $ x n)) + (1 - l n) * (1 - β n) * (dist o (x n)) + (1 - l n) * (1 - β n) * (dist (x n) (T $ x n)) : by ring ... ≤ dist (x n) (x $ n + 1) + (1 - β n) * (dist o (x n)) + (1 - l n) * (dist (x n) (T $ x n)) : by ring ... ≤ dist (x n) (x $ n + 1) + (1 - β n) * (2 * M) + (1 - l n) * (dist (x n) (T $ x n)) : by { rw [dist_comm o (x n)], nlinarith [sub_nonneg.mpr (@hβ1 n), l_3_1_ii_ii n], }, have h₂ : dist (x n) (T $ x n) - (1 - l n) * (dist (x n) (T $ x n)) ≤ dist (x n) (x $ n + 1) + (1 - β n) * (2 * M) := sub_le_iff_le_add.mpr h₁, have h₃ : dist (x n) (T $ x n) - (1 - l n) * (dist (x n) (T $ x n)) = (l n) * (dist (x n) (T $ x n)) := by ring, rw [h₃, mul_comm (1 - β n) (2 * M)] at h₂, exact h₂, end -- # Main results parameters {σ₂ σ₃ σ₄ σ₅ : ℕ → ℕ} {Λ NΛ : ℕ} (Λ_pos : 0 < Λ) include Λ_pos open_locale big_operators open finset (range) def cond₂ : Prop := is_rate_of_convergence_towards σ₂ (λ n, ∏ i in range (n + 1), (β $ i + 1)) 0 def cond₃ : Prop := is_cauchy_modulus σ₃ (λ n, ∑ i in range (n + 1), |β (i + 1) - β i|) def cond₄ : Prop := is_cauchy_modulus σ₄ (λ n, ∑ i in range (n + 1), |l (i + 1) - l i|) def cond₅ : Prop := is_rate_of_convergence_towards σ₅ β 1 def cond₆ : Prop := ∀ n : ℕ, NΛ ≤ n → 1 / (Λ : ℝ) ≤ l n parameters (K : ℕ) (h_M_le_K : (M : ℝ) ≤ (K : ℝ)) (ψ : ℕ → ℕ) (hψ_pos : ∀ k : ℕ, 0 < ψ k) include h_M_le_K def L := 2 * K def s (n : ℕ) : ℝ := dist (x $ n + 1) (x n) def a (n : ℕ) : ℝ := 1 - (β $ n + 1) def P (n : ℕ) : ℝ := ∏ i in range (n + 1), (1 - a i) noncomputable def c (n : ℕ) : ℝ := 2 * M * (|β (n + 1) - (β n)| + |l (n + 1) - l n|) noncomputable def c' (n : ℕ) : ℝ := ∑ i in range (n + 1), c i lemma a_pos : ∀ {n : ℕ}, 0 ≤ a n := by { intros n, simp only [a, sub_nonneg], exact hβ1, } lemma one_sub_a_nonneg : ∀ {n : ℕ}, 0 ≤ (1 - a n) := by { intros n, simp only [a, sub_sub_cancel], exact hβ0, } lemma a_lt_one : ∀ {n : ℕ}, a n < 1 := by { intros n, simp only [a, sub_lt_self_iff], exact β_pos, } lemma c_pos : ∀ {n : ℕ}, 0 ≤ c n := begin intros n, simp only [c], exact mul_nonneg (mul_nonneg zero_le_two M_nonneg) (add_nonneg (abs_nonneg _) (abs_nonneg _)), end lemma s_pos : ∀ {n : ℕ}, 0 ≤ s n := begin intros n, simp only [s], exact dist_nonneg, end lemma P_pos : ∀ {n : ℕ}, 0 ≤ (P n) := begin intros n, simp only [P], exact finset.prod_nonneg (λ i _, one_sub_a_nonneg), end lemma xu_ineq_s_a_c : ∀ {n : ℕ}, s (n + 1) ≤ (1 - a n) * s n + c n := begin intros n, simp only [s, a, c, sub_sub_cancel], have : n + 1 + 1 = n + 2 := by ring, rw this, exact l_3_2_ii n, end lemma s_le_L : ∀ {n : ℕ}, s n ≤ (L : ℝ) := begin simp only [L, s, nat.cast_bit0, nat.cast_one, nat.cast_mul], intros n, calc dist (x $ n + 1) (x n) ≤ dist (x $ n + 1) p + dist p (x n) : dist_triangle _ _ _ ... = dist p (x $ n + 1) + dist p (x n) : by rw dist_comm ... ≤ M + M : add_le_add (l_3_1_ii_i _) (l_3_1_ii_i _) ... ≤ K + K : add_le_add h_M_le_K h_M_le_K ... = 2 * K : by ring, end set_option pp.all false lemma σ₂_rate_conv_P : cond₂ → is_rate_of_convergence_towards σ₂ P 0 := begin intros hc₂, intros k n h, rw [real.dist_eq, sub_zero, abs_eq_self.mpr P_pos], simp only [P, a, one_div, sub_sub_cancel, nat.cast_add, nat.cast_one], dunfold cond₂ at hc₂, specialize hc₂ k n h, dsimp only at hc₂, have : 0 ≤ ∏ i in range (n + 1), β (i + 1) := finset.prod_nonneg (λ i _, hβ0), rw [real.dist_eq, sub_zero, abs_eq_self.mpr this] at hc₂, clear this, ring_nf at hc₂, simp only [nat.cast_add, nat.cast_one] at hc₂, exact hc₂, end lemma L_def : L = 2 * K := rfl lemma K_pos : 0 < K := (@nat.cast_pos ℝ _ _ K).mp (lt_of_lt_of_le M_pos h_M_le_K) lemma M_le_L : M ≤ L := begin simp only [L, nat.cast_bit0, nat.cast_one, nat.cast_mul], nlinarith [M_pos], end lemma L_pos : 0 < L := nat.succ_mul_pos 1 K_pos lemma L_pos_real : (0 : ℝ) < L := nat.cast_pos.mpr L_pos def χ (k : ℕ) : ℕ := max (σ₃ $ 8 * K * (k + 1) - 1) (σ₄ $ 8 * K * (k + 1) - 1) def Ω (k : ℕ) : ℕ := max (σ₂ $ 6 * K * (k + 1) * (ψ k) - 1) (χ (3 * k + 2) + 1) + 1 def Φ (k : ℕ) : ℕ := (max3 NΛ (Ω $ 2 * Λ * (k + 1) - 1) (σ₅ $ 4 * K * Λ * (k + 1) - 1)) + 1 def Γ (φ : ℕ → ℕ) (k : ℕ) : ℕ := (max3 NΛ (φ $ 2 * Λ * (k + 1) - 1) (σ₅ $ 4 * K * Λ * (k + 1) - 1)) + 1 parameter (hψ : ∀ k : ℕ, 1 / (ψ k : ℝ) ≤ P (χ $ 3 * k + 2)) -- set_option pp.all true lemma l_5_3 (hc₃ : cond₃) (hc₄ : cond₄) : is_cauchy_modulus χ c' := begin intros k n j h, have hσ₃_le_n : σ₃ (8 * K * (k + 1) - 1) ≤ n := le_of_max_le_left h, have hσ₄_le_n : σ₄ (8 * K * (k + 1) - 1) ≤ n := le_of_max_le_right h, have hc₃' := hc₃ _ _ j hσ₃_le_n, have hc₄' := hc₄ _ _ j hσ₄_le_n, set β' : ℕ → ℝ := λ n, ∑ i in range (n + 1), |β (i + 1) - β i|, set l' : ℕ → ℝ := λ n, ∑ i in range (n + 1), |l (i + 1) - l i|, rw [real.dist_eq] at hc₃' hc₄', have : 8 * K = 4 * L := by { dsimp only [L], ring, }, rw this at *, clear this, have h_4LK_pos : 0 < 4 * L * (k + 1) := mul_pos (mul_pos zero_lt_four L_pos) (nat.succ_pos k), have : 4 * L * (k + 1) - 1 + 1 = 4 * L * (k + 1) := nat.succ_pred_eq_of_pos h_4LK_pos, rw this at *, clear this, have h_c_β_l : ∀ m : ℕ, c' m = 2 * M * (β' m + l' m) := begin intros m, simp only [c', c, β', l'], rw [finset.sum_hom, finset.sum_add_distrib], end, have h_β'_sub_abs : |β' (n + j) - β' n| = β' (n + j) - β' n := by { apply abs_eq_self.mpr, dsimp only [β'], have : n + j + 1 = (n + 1) + j := by ring, rw this, apply nonneg_sub_of_nonneg_sum, intros, apply abs_nonneg, }, have h_l'_sub_abs : |l' (n + j) - l' n| = l' (n + j) - l' n := by { apply abs_eq_self.mpr, dsimp only [l'], have : n + j + 1 = (n + 1) + j := by ring, rw this, apply nonneg_sub_of_nonneg_sum, intros, apply abs_nonneg, }, rw h_β'_sub_abs at hc₃', rw h_l'_sub_abs at hc₄', have h_2M_pos : 0 < 2 * M := mul_pos zero_lt_two M_pos, have h_c'_le : c' (n + j) - c' n ≤ 1 / ↑(k + 1) := calc c' (n + j) - c' n = 2 * M * (β' (n + j) + l' (n + j)) - 2 * M * (β' n + l' n) : by repeat { rw [h_c_β_l] } ... = 2 * M * ((β' (n + j) - β' n) + (l' (n + j) - l' n)) : by ring ... ≤ 2 * M * (1 / ↑(4 * L * (k + 1)) + 1 / ↑(4 * L * (k + 1))) : by nlinarith ... = 2 * M * (2 / ↑(4 * L * (k + 1))) : by ring ... = 2 * M * (2 / (4 * ↑L * (↑k + 1))) : by simp only [nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul] ... = 4 * M / (4 * ↑L * (↑k + 1)) : by ring ... = 4 * M / (4 * (↑L * (↑k + 1))) : by rw mul_assoc ... = M / (↑L * (↑k + 1)) : mul_div_mul_left _ _ (by norm_num) ... = (M / ↑L) * (1 / (↑k + 1)) : by { ring_nf, rw [mul_inv', mul_comm (↑L)⁻¹ _], } ... ≤ 1 * (1 / ↑(k + 1)) : by { -- have : (0 : ℝ) < ↑L := L_pos_real, have h_M_div_L_le_one : (M / (L : ℝ)) ≤ 1 := (@div_le_one ℝ _ M ↑L L_pos_real).mpr M_le_L, have h_one_div_k_succ_pos : (0 : ℝ) < 1 / ↑(k + 1) := one_div_pos.mpr (nat.cast_pos.mpr $ nat.succ_pos k), exact (mul_le_mul_right h_one_div_k_succ_pos).mpr h_M_div_L_le_one, } ... = 1 / ↑(k + 1) : one_mul _, have h_c'_sub_abs : |c' (n + j) - c' n| = c' (n + j) - c' n := by { apply abs_eq_self.mpr, dsimp only [c'], have : n + j + 1 = (n + 1) + j := by ring, rw this, clear this, apply nonneg_sub_of_nonneg_sum, intros, have : 0 ≤ |β (i + 1) - β i| + |l (i + 1) - l i| := add_nonneg (abs_nonneg _) (abs_nonneg _), nlinarith, }, rw [real.dist_eq, h_c'_sub_abs], exact h_c'_le, end lemma Λ_pos_real : 0 < (Λ : ℝ) := nat.cast_pos.mpr Λ_pos lemma add_div_two_self (a : ℝ) (h : a ≠ 0) : 1 / (2 * a) + 1 / (2 * a) = 1 / a := calc 1 / (2 * a) + 1 / (2 * a) = (2 / (2 * a)) : by ring ... = (1 / a) : by rw [div_mul_right a two_ne_zero] lemma β_sub_one_neg : ∀ {n : ℕ}, β n - 1 ≤ 0 := λ n, by nlinarith [@hβ1 n] lemma l_5_5 (hc₅ : cond₅) (hc₆ : cond₆) (Θ : ℕ → ℕ) (Θar : is_rate_of_asymptotic_regularity Θ x) : is_rate_of_asymptotic_regularity_with_respect_to (Γ Θ) x T := begin intros k n h, dsimp only at ⊢, rw [real.dist_eq, sub_zero, abs_eq_self.mpr dist_nonneg], have h_le₁ : NΛ ≤ n := le_trans (le_trans max3_le₁ (nat.le_succ _)) h, have h_le₂ : Θ (2 * Λ * (k + 1) - 1) ≤ n := le_trans (le_trans max3_le₂ (nat.le_succ _)) h, have h_le₃ : σ₅ (4 * K * Λ * (k + 1) - 1) ≤ n := le_trans (le_trans max3_le₃ (nat.le_succ _)) h, dunfold cond₅ at hc₅, dunfold cond₆ at hc₆, have k_succ_pos_real : 0 < (k : ℝ) + 1 := nat.cast_add_one_pos k, have hΛ : 1 / (l n) ≤ Λ := by { have h'₂ : 0 < l n := l_pos, have := hc₆ n h_le₁, refine (one_div_le l_pos Λ_pos_real).mpr this, }, have h₁ : dist (T $ x n) (x n) ≤ Λ * (dist (x n) (x $ n + 1) + 2 * M * (1 - β n)) := by { have p₁ := l_3_2_v n, have p₂ : dist (x n) (T $ x n) ≤ (1 / l n) * (dist (x n) (x (n + 1)) + 2 * M * (1 - β n)) := by { apply helper, exact p₁, }, rw dist_comm at p₂, have p₃ : (1 / l n) * (dist (x n) (x (n + 1)) + 2 * M * (1 - β n)) ≤ ↑Λ * (dist (x n) (x (n + 1)) + 2 * M * (1 - β n)) := mul_mono_nonneg (add_nonneg dist_nonneg (by nlinarith [M_pos, @β_pos n, @hβ1 n])) hΛ, refine le_trans p₂ p₃, }, have h₂ : dist (x n) (x $ n + 1) ≤ 1 / (2 * Λ * (k + 1)) := by { specialize Θar (2 * Λ * (k + 1) - 1) n h_le₂, dsimp only at Θar, rw [real.dist_eq, sub_zero, abs_eq_self.mpr dist_nonneg] at Θar, rw dist_comm at Θar, have h_2ΛK_pos : 0 < 2 * Λ * (k + 1) := by nlinarith, have : 2 * Λ * (k + 1) - 1 + 1 = 2 * Λ * (k + 1) := nat.succ_pred_eq_of_pos h_2ΛK_pos, rw this at Θar, simp only [nat.cast_bit0, nat.cast_add, nat.cast_one, nat.cast_mul] at Θar, exact Θar, }, have h₃ : 2 * M * (1 - β n) ≤ 1 / (2 * Λ * (k + 1)) := by { specialize hc₅ ((4 * K * Λ * (k + 1) - 1)) n h_le₃, rw [real.dist_eq, abs_of_nonpos β_sub_one_neg, neg_sub] at hc₅, have h_4KK_pos : 0 < 4 * K * Λ * (k + 1) := by repeat { apply mul_pos }; try { nlinarith [K_pos] }, have : 4 * K * Λ * (k + 1) - 1 + 1 = 4 * K * Λ * (k + 1) := nat.succ_pred_eq_of_pos h_4KK_pos, rw this at hc₅, clear this, have := mul_sides_left _ _ (2 * M) _ _ hc₅, -- this is awful all_goals { sorry }, }, calc dist (T $ x n) (x n) ≤ Λ * (dist (x n) (x $ n + 1) + 2 * M * (1 - β n)) : h₁ ... ≤ Λ * ((1 / (2 * Λ * (k + 1))) + 2 * M * (1 - β n)) : (mul_le_mul_left Λ_pos_real).mpr (add_le_add_right h₂ _) ... = Λ * (1 / (2 * Λ * (k + 1))) + Λ * 2 * M * (1 - β n) : by ring ... = Λ / (2 * Λ * (k + 1)) + Λ * (2 * M * (1 - β n)) : by ring ... = Λ / (Λ * 2 * (k + 1)) + Λ * (2 * M * (1 - β n)) : by rw [mul_comm 2 (Λ : ℝ)] ... = 1 / (2 * (k + 1)) + Λ * (2 * M * (1 - β n)) : by { have : (Λ : ℝ) / ((Λ : ℝ) * 2 * (↑k + 1)) = 1 / (2 * (k + 1)) := by { rw [mul_assoc (Λ : ℝ) 2 (k + 1)], exact div_mul_right _ (ne_of_gt Λ_pos_real), }, rw this, } ... ≤ 1 / (2 * (k + 1)) + Λ * (1 / (2 * Λ * (k + 1))) : add_le_add_left ((mul_le_mul_left Λ_pos_real).mpr h₃) _ ... = 1 / (2 * (k + 1)) + Λ * (1 / (Λ * (2 * (k + 1)))) : by rw [mul_comm 2 (Λ : ℝ), mul_assoc (Λ : ℝ) 2 (k + 1)] ... = 1 / (2 * (k + 1)) + Λ / (Λ * (2 * (k + 1))) : by ring ... = 1 / (2 * (k + 1)) + 1 / (2 * (k + 1)) : by rw [div_mul_right _ (ne_of_gt Λ_pos_real)] ... = 1 / (↑k + 1) : add_div_two_self _ (ne_of_gt k_succ_pos_real), end include hψ theorem main₁ (hc₂ : cond₂) (hc₃ : cond₃) (hc₄ : cond₄) : is_rate_of_asymptotic_regularity Ω x := begin have xu := xu_quantitative a c s L χ σ₂ ψ @a_pos @a_lt_one @c_pos @s_pos L_pos @xu_ineq_s_a_c @s_le_L (l_5_3 hc₃ hc₄) (σ₂_rate_conv_P hc₂) hψ, dsimp only [is_rate_of_asymptotic_regularity], have : s = λ (i : ℕ), dist (x (i + 1)) (x i) := by refl, rw ←this, clear this, have : Ω = xu_rate χ σ₂ ψ L := by { ext, simp [Ω, xu_rate, L], ring, }, rw this, exact xu, end theorem main₂ (hc₂ : cond₂) (hc₃ : cond₃) (hc₄ : cond₄) (hc₅ : cond₅) (hc₆ : cond₆) : is_rate_of_asymptotic_regularity_with_respect_to Φ x T := begin have : Φ = Γ Ω := by { ext, simp [Φ, Γ, Ω], }, rw this, exact l_5_5 hc₅ hc₆ Ω (main₁ hc₂ hc₃ hc₄), end end #check finset.sum_add_distrib open_locale big_operators #check finset.sum_hom example (a b : ℕ → ℝ) (c : ℝ) (n : ℕ) : ∑ i in finset.range n, c * a i = c * (∑ i in finset.range n, a i) := begin exact (finset.range n).sum_hom (has_mul.mul c), end #check div_le_one example (a : ℝ) (h : 0 < a) : 0 < (1 / a) := by { exact one_div_pos.mpr h, } example (k : ℕ) : (0 : ℝ) < (k.succ) := by { have : (0 : ℕ) < k.succ := nat.succ_pos k, exact nat.cast_pos.mpr (nat.succ_pos k), } example (a b : ℝ) (h : a ≤ b) (h₁ : 0 < a) (h₂ : 0 < b) : (a / b ≤ 1) := by { exact (div_le_one h₂).mpr h, } /- Try this: exact gt_of_ge_of_gt h₂ h₁ -/ example (a b : ℝ) (h : 1 / a ≤ b) (h₁ : 0 < a) (h₂ : 0 < b) : 1 / b ≤ a := by { exact (one_div_le h₁ h₂).mp h, } example (a b c : ℝ) (h : b ≤ c) (h₁ : 0 < a) : a * b ≤ a * c := by { exact (mul_le_mul_left h₁).mpr h, } example (a b c : ℝ) (h : a ≤ b) : a + c ≤ b + c := by { exact add_le_add_right h c, } example (a b : ℝ) (h₁: 0 < a) (h₂ : 0 < b) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := by { exact mul_inv_rev' a b, } example (a : ℝ) (h : 0 < a) : a * a⁻¹ = 1 := by { } example (a b : ℝ) (h₁ : 0 ≠ a) (h₂ : 0 ≠ b) : a / (a * b) = 1 / b := by { exact div_mul_right b (ne.symm h₁), -- ring_nf, -- rw [mul_inv_rev', mul_assoc, inv_mul_cancel (ne_of_gt h₁), mul_one], } example (a : ℝ) : a + a = 2 * a := by { ring, } example (a : ℝ) (h : a ≠ 0) : 1 / (2 * a) + 1 / (2 * a) = 1 / a := calc 1 / (2 * a) + 1 / (2 * a) = (2 / (2 * a)) : by ring ... = (1 / a) : by rw [div_mul_right a two_ne_zero] example (a b c : ℝ) (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a * b ≤ c → b ≤ a⁻¹ * c := by { have : a * b ≤ c → a⁻¹ * (a * b) ≤ a⁻¹ * c := (mul_le_mul_left (inv_pos.mpr ha)).mpr, rw [←mul_assoc, inv_mul_cancel (ne_of_gt ha), one_mul] at this, exact this, } example (a b c : ℝ) (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : b ≤ c → a * b ≤ a * c := by { exact (mul_le_mul_left ha).mpr, } example (a b c : ℝ) (h' : b ≤ c) (h : 0 ≤ a) : b * a ≤ c * a := by { exact mul_mono_nonneg h h', } #check (mul_le_mul_left _).mpr example (a b : ℝ) : - (a - b) = b -a := neg_sub a b example (a : ℝ) (h : a ≤ 0) : abs a = -a := abs_of_nonpos h example (s : finset ℕ) (x : ℕ) (h : x ∈ s) : x ≤ s.sup id := by { have := @finset.le_sup _ _ _ _ id _ h, exact this, } example (a : ℕ) : a ≤ a + 1 := nat.le_succ a #check finset.prod_nonneg #check finset.sum_nonneg example (a b c d : ℝ) (h₁ : 0 ≠ a) (h₂ : 0 ≠ c) : (a * b) / (a * c) = b / c := by { exact mul_div_mul_left b c (ne.symm h₁), }
bb17823f259d2ea6150258c766fc8977b23e5bb2
83c8119e3298c0bfc53fc195c41a6afb63d01513
/library/init/function.lean
81d9fe80ce53ff10b4952b2f54fe1d97d619bea3
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
5,622
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Haitao Zhang General operations on functions. -/ prelude import init.data.prod init.funext init.logic universes u₁ u₂ u₃ u₄ namespace function variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁} @[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ := λ x, f (g x) @[inline, reducible] def dcomp {β : α → Sort u₂} {φ : Π {x : α}, β x → Sort u₃} (f : Π {x : α} (y : β x), φ y) (g : Π x, β x) : Π x, φ (g x) := λ x, f (g x) infixr ` ∘ ` := function.comp infixr ` ∘' `:80 := function.dcomp @[reducible] def comp_right (f : β → β → β) (g : α → β) : β → α → β := λ b a, f b (g a) @[reducible] def comp_left (f : β → β → β) (g : α → β) : α → β → β := λ a b, f (g a) b @[reducible] def on_fun (f : β → β → φ) (g : α → β) : α → α → φ := λ x y, f (g x) (g y) @[reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ) : α → β → ζ := λ x y, op (f x y) (g x y) @[reducible] def const (β : Sort u₂) (a : α) : β → α := λ x, a @[reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y := λ y x, f x y @[reducible] def app {β : α → Sort u₂} (f : Π x, β x) (x : α) : β x := f x infixl ` on `:2 := on_fun notation f ` -[` op `]- ` g := combine f op g lemma left_id (f : α → β) : id ∘ f = f := rfl lemma right_id (f : α → β) : f ∘ id = f := rfl @[simp] lemma comp_app (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ (g ∘ h) := rfl @[simp] lemma comp.left_id (f : α → β) : id ∘ f = f := rfl @[simp] lemma comp.right_id (f : α → β) : f ∘ id = f := rfl lemma comp_const_right (f : β → φ) (b : β) : f ∘ (const α b) = const α (f b) := rfl @[reducible] def injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂ lemma injective_comp {g : β → φ} {f : α → β} (hg : injective g) (hf : injective f) : injective (g ∘ f) := assume a₁ a₂, assume h, hf (hg h) @[reducible] def surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b lemma surjective_comp {g : β → φ} {f : α → β} (hg : surjective g) (hf : surjective f) : surjective (g ∘ f) := λ (c : φ), exists.elim (hg c) (λ b hb, exists.elim (hf b) (λ a ha, exists.intro a (show g (f a) = c, from (eq.trans (congr_arg g ha) hb)))) def bijective (f : α → β) := injective f ∧ surjective f lemma bijective_comp {g : β → φ} {f : α → β} : bijective g → bijective f → bijective (g ∘ f) | ⟨h_ginj, h_gsurj⟩ ⟨h_finj, h_fsurj⟩ := ⟨injective_comp h_ginj h_finj, surjective_comp h_gsurj h_fsurj⟩ /-- `left_inverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/ def left_inverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x def has_left_inverse (f : α → β) : Prop := ∃ finv : β → α, left_inverse finv f /-- `right_inverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/ def right_inverse (g : β → α) (f : α → β) : Prop := left_inverse f g def has_right_inverse (f : α → β) : Prop := ∃ finv : β → α, right_inverse finv f lemma injective_of_left_inverse {g : β → α} {f : α → β} : left_inverse g f → injective f := assume h, assume a b, assume faeqfb, have h₁ : a = g (f a), from eq.symm (h a), have h₂ : g (f b) = b, from h b, have h₃ : g (f a) = g (f b), from congr_arg g faeqfb, eq.trans h₁ (eq.trans h₃ h₂) lemma injective_of_has_left_inverse {f : α → β} : has_left_inverse f → injective f := assume h, exists.elim h (λ finv inv, injective_of_left_inverse inv) lemma right_inverse_of_injective_of_left_inverse {f : α → β} {g : β → α} (injf : injective f) (lfg : left_inverse f g) : right_inverse f g := assume x, have h : f (g (f x)) = f x, from lfg (f x), injf h lemma surjective_of_has_right_inverse {f : α → β} : has_right_inverse f → surjective f | ⟨finv, inv⟩ b := ⟨finv b, inv b⟩ lemma left_inverse_of_surjective_of_right_inverse {f : α → β} {g : β → α} (surjf : surjective f) (rfg : right_inverse f g) : left_inverse f g := assume y, exists.elim (surjf y) (λ x hx, calc f (g y) = f (g (f x)) : hx ▸ rfl ... = f x : eq.symm (rfg x) ▸ rfl ... = y : hx) lemma injective_id : injective (@id α) := assume a₁ a₂ h, h lemma surjective_id : surjective (@id α) := assume a, ⟨a, rfl⟩ lemma bijective_id : bijective (@id α) := ⟨injective_id, surjective_id⟩ end function namespace function variables {α : Type u₁} {β : Type u₂} {φ : Type u₃} @[inline] def curry : (α × β → φ) → α → β → φ := λ f a b, f (a, b) @[inline] def uncurry : (α → β → φ) → α × β → φ := λ f a, f a.1 a.2 @[simp] lemma curry_uncurry (f : α → β → φ) : curry (uncurry f) = f := rfl @[simp] lemma uncurry_curry (f : α × β → φ) : uncurry (curry f) = f := funext (λ ⟨a, b⟩, rfl) def id_of_left_inverse {g : β → α} {f : α → β} : left_inverse g f → g ∘ f = id := assume h, funext h def id_of_right_inverse {g : β → α} {f : α → β} : right_inverse g f → f ∘ g = id := assume h, funext h end function
fc78dad6a879ffede029edc0abe900c524add68e
618003631150032a5676f229d13a079ac875ff77
/src/set_theory/cardinal.lean
001e2abdb2f32ce7b9449a071fe9f48bc5aad21e
[ "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
45,166
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nonzero cardinal.{u} := { zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_add_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_inj {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(-s : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : α → Prop) (e : α ≃ β) : mk {a : α // p a} = mk {b : β // p (e.symm b)} := quotient.sound ⟨equiv.subtype_equiv_of_subtype' e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
150f8a27f78ee0ff052eec35b461ca5dcaa4b2f7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/metric_space/closeds_auto.lean
b6d5fe61027e171a727afa74cbeedbfbc082ba70
[]
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
7,244
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.metric_space.hausdorff_distance import Mathlib.analysis.specific_limits import Mathlib.PostPort universes u namespace Mathlib /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ namespace emetric /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ protected instance closeds.emetric_space {α : Type u} [emetric_space α] : emetric_space (topological_space.closeds α) := emetric_space.mk sorry sorry sorry sorry (uniform_space_of_edist (fun (s t : topological_space.closeds α) => Hausdorff_edist (subtype.val s) (subtype.val t)) sorry sorry sorry) /-- The edistance to a closed set depends continuously on the point and the set -/ theorem continuous_inf_edist_Hausdorff_edist {α : Type u} [emetric_space α] : continuous fun (p : α × topological_space.closeds α) => inf_edist (prod.fst p) (subtype.val (prod.snd p)) := sorry /-- Subsets of a given closed subset form a closed set -/ theorem is_closed_subsets_of_is_closed {α : Type u} [emetric_space α] {s : set α} (hs : is_closed s) : is_closed (set_of fun (t : topological_space.closeds α) => subtype.val t ⊆ s) := sorry /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ theorem closeds.edist_eq {α : Type u} [emetric_space α] {s : topological_space.closeds α} {t : topological_space.closeds α} : edist s t = Hausdorff_edist (subtype.val s) (subtype.val t) := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ protected instance closeds.complete_space {α : Type u} [emetric_space α] [complete_space α] : complete_space (topological_space.closeds α) := sorry /-- In a compact space, the type of closed subsets is compact. -/ protected instance closeds.compact_space {α : Type u} [emetric_space α] [compact_space α] : compact_space (topological_space.closeds α) := sorry /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ protected instance nonempty_compacts.emetric_space {α : Type u} [emetric_space α] : emetric_space (topological_space.nonempty_compacts α) := emetric_space.mk sorry sorry sorry sorry (uniform_space_of_edist (fun (s t : topological_space.nonempty_compacts α) => Hausdorff_edist (subtype.val s) (subtype.val t)) sorry sorry sorry) /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ theorem nonempty_compacts.to_closeds.uniform_embedding {α : Type u} [emetric_space α] : uniform_embedding topological_space.nonempty_compacts.to_closeds := isometry.uniform_embedding fun (x y : topological_space.nonempty_compacts α) => rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ theorem nonempty_compacts.is_closed_in_closeds {α : Type u} [emetric_space α] [complete_space α] : is_closed (set.range topological_space.nonempty_compacts.to_closeds) := sorry /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ protected instance nonempty_compacts.complete_space {α : Type u} [emetric_space α] [complete_space α] : complete_space (topological_space.nonempty_compacts α) := iff.mpr (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding) (is_closed.is_complete nonempty_compacts.is_closed_in_closeds) /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ protected instance nonempty_compacts.compact_space {α : Type u} [emetric_space α] [compact_space α] : compact_space (topological_space.nonempty_compacts α) := compact_space.mk (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact set.univ)) (propext (embedding.compact_iff_compact_image (uniform_embedding.embedding nonempty_compacts.to_closeds.uniform_embedding))))) (eq.mpr (id (Eq._oldrec (Eq.refl (is_compact (topological_space.nonempty_compacts.to_closeds '' set.univ))) set.image_univ)) (is_closed.compact nonempty_compacts.is_closed_in_closeds))) /-- In a second countable space, the type of nonempty compact subsets is second countable -/ protected instance nonempty_compacts.second_countable_topology {α : Type u} [emetric_space α] [topological_space.second_countable_topology α] : topological_space.second_countable_topology (topological_space.nonempty_compacts α) := second_countable_of_separable (topological_space.nonempty_compacts α) namespace metric /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ protected instance Mathlib.metric.nonempty_compacts.metric_space {α : Type u} [metric_space α] : metric_space (topological_space.nonempty_compacts α) := emetric_space.to_metric_space sorry /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ theorem Mathlib.metric.nonempty_compacts.dist_eq {α : Type u} [metric_space α] {x : topological_space.nonempty_compacts α} {y : topological_space.nonempty_compacts α} : dist x y = metric.Hausdorff_dist (subtype.val x) (subtype.val y) := rfl theorem Mathlib.metric.lipschitz_inf_dist_set {α : Type u} [metric_space α] (x : α) : lipschitz_with 1 fun (s : topological_space.nonempty_compacts α) => metric.inf_dist x (subtype.val s) := sorry theorem Mathlib.metric.lipschitz_inf_dist {α : Type u} [metric_space α] : lipschitz_with (bit0 1) fun (p : α × topological_space.nonempty_compacts α) => metric.inf_dist (prod.fst p) (subtype.val (prod.snd p)) := lipschitz_with.uncurry (fun (s : topological_space.nonempty_compacts α) => metric.lipschitz_inf_dist_pt (subtype.val s)) metric.lipschitz_inf_dist_set theorem Mathlib.metric.uniform_continuous_inf_dist_Hausdorff_dist {α : Type u} [metric_space α] : uniform_continuous fun (p : α × topological_space.nonempty_compacts α) => metric.inf_dist (prod.fst p) (subtype.val (prod.snd p)) := lipschitz_with.uniform_continuous metric.lipschitz_inf_dist end Mathlib
c051334d62c93ccdccafe84571285ac6bfc0df3d
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/unfold_crash.lean
1155aee4f19d5c418893ca3ed198f61f39c957ae
[ "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
306
lean
-- open nat tactic example (a b : nat) : a = succ b → a = b + 1 := by do H ← intro `H, try (dunfold_hyp [`nat.succ] H), dunfold_target [`add, `has_add.add, `has_one.one, `nat.add, `one], trace_state, t ← target, expected ← to_expr ```(a = succ b), guard (t = expected), assumption
4af3e6d1076b5e37fa5bae074191e47f7a0bfa84
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/metric_space/pi_Lp.lean
c77fac10786bfd2a3a5f987ab95d9b6deab95700
[ "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
15,364
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.mean_inequalities /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a real parameter `p ∈ [1, ∞)`, that also induce the product topology. We define them in this file. The distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$ We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Pi type, named `pi_Lp p hp α`, where `hp : 1 ≤ p`. This assumption is included in the definition of the type to make sure that it is always available to typeclass inference to construct the instances. We ensure that the topology and uniform structure on `pi_Lp p hp α` are (defeq to) the product topology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ∥f (x)∥^p dμ\right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm), and some functions have infinite `L^p` norm. All these subtleties are not present in the case of finitely many metric spaces (which corresponds to the basis which is a finite space with the counting measure), hence it is worth devoting a file to this specific case which is particularly well behaved. The general case is not yet formalized in mathlib. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`. -/ open real set filter open_locale big_operators uniformity topological_space nnreal ennreal noncomputable theory variables {ι : Type*} /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances, and we provide the assumption `hp` in the definition, to make it available to typeclass resolution when it looks for a distance on `pi_Lp p hp α`. -/ @[nolint unused_arguments] def pi_Lp {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) : Type* := Π (i : ι), α i instance {ι : Type*} (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) [∀ i, inhabited (α i)] : inhabited (pi_Lp p hp α) := ⟨λ i, default (α i)⟩ namespace pi_Lp variables (p : ℝ) (hp : 1 ≤ p) (α : ι → Type*) (β : ι → Type*) /-- Canonical bijection between `pi_Lp p hp α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p hp α ≃ Π (i : ι), α i := equiv.refl _ section /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p hp α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [∀ i, emetric_space (α i)] [∀ i, pseudo_emetric_space (β i)] [fintype ι] /-- Endowing the space `pi_Lp p hp β` with the `L^p` pseudoedistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/ def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p hp β) := have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, { edist := λ f g, (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p), edist_self := λ f, by simp [edist, ennreal.zero_rpow_of_pos pos, ennreal.zero_rpow_of_pos (inv_pos.2 pos)], edist_comm := λ f g, by simp [edist, edist_comm], edist_triangle := λ f g h, calc (∑ (i : ι), edist (f i) (h i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), (edist (f i) (g i) + edist (g i) (h i)) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (le_trans zero_le_one hp) end ... ≤ (∑ (i : ι), edist (f i) (g i) ^ p) ^ (1 / p) + (∑ (i : ι), edist (g i) (h i) ^ p) ^ (1 / p) : ennreal.Lp_add_le _ _ _ hp } /-- Endowing the space `pi_Lp p hp α` with the `L^p` edistance. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary emetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this emetric space and `emetric_space.replace_uniformity`. -/ def emetric_aux : emetric_space (pi_Lp p hp α) := { eq_of_edist_eq_zero := λ f g hfg, begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, letI h := pseudo_emetric_aux p hp α, have h : edist f g = (∑ (i : ι), (edist (f i) (g i)) ^ p) ^ (1/p) := rfl, simp [h, ennreal.rpow_eq_zero_iff, pos, asymm pos, finset.sum_eq_zero_iff_of_nonneg] at hfg, exact funext hfg end, ..pseudo_emetric_aux p hp α } local attribute [instance] pi_Lp.emetric_aux pi_Lp.pseudo_emetric_aux lemma lipschitz_with_equiv : lipschitz_with 1 (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p) ^ (1/p) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ le_of_lt pos), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i) end end lemma antilipschitz_with_equiv : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1/p)) (pi_Lp.equiv p hp β) := begin have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, have nonneg : 0 ≤ 1 / p := one_div_nonneg.2 (le_of_lt pos), have cancel : p * (1/p) = 1 := mul_div_cancel' 1 (ne_of_gt pos), assume x y, simp [edist, -one_div], calc (∑ (i : ι), edist (x i) (y i) ^ p) ^ (1 / p) ≤ (∑ (i : ι), edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) ^ p) ^ (1 / p) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : ℝ≥0)) ^ (1/p) : ℝ≥0) * edist (pi_Lp.equiv p hp β x) (pi_Lp.equiv p hp β y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end end lemma aux_uniformity_eq : 𝓤 (pi_Lp p hp β) = @uniformity _ (Pi.uniform_space _) := begin have A : uniform_embedding (pi_Lp.equiv p hp β) := (antilipschitz_with_equiv p hp β).uniform_embedding_of_injective (pi_Lp.equiv p hp β).injective (lipschitz_with_equiv p hp β).uniform_continuous, have : (λ (x : pi_Lp p hp β × pi_Lp p hp β), ((pi_Lp.equiv p hp β) x.fst, (pi_Lp.equiv p hp β) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end end /-! ### Instances on finite `L^p` products -/ instance uniform_space [∀ i, uniform_space (β i)] : uniform_space (pi_Lp p hp β) := Pi.uniform_space _ variable [fintype ι] /-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the `L^p` pseudoedistance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p hp β) := (pseudo_emetric_aux p hp β).replace_uniformity (aux_uniformity_eq p hp β).symm /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [∀ i, emetric_space (α i)] : emetric_space (pi_Lp p hp α) := (emetric_aux p hp α).replace_uniformity (aux_uniformity_eq p hp α).symm protected lemma edist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_emetric_space (β i)] (x y : pi_Lp p hp β) : edist x y = (∑ (i : ι), (edist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- pseudometric space instance on the product of finitely many psuedometric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p hp β) := begin /- we construct the instance from the pseudo emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [∀ i, metric_space (α i)] : metric_space (pi_Lp p hp α) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, refine emetric_space.to_metric_space_of_dist (λf g, (∑ (i : ι), (dist (f i) (g i)) ^ p) ^ (1/p)) (λ f g, _) (λ f g, _), { simp [pi_Lp.edist, ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, edist_ne_top] }, { have A : ∀ (i : ι), i ∈ (finset.univ : finset ι) → edist (f i) (g i) ^ p < ⊤ := λ i hi, by simp [lt_top_iff_ne_top, edist_ne_top, le_of_lt pos], simp [dist, -one_div, pi_Lp.edist, ← ennreal.to_real_rpow, ennreal.to_real_sum A, dist_edist] } end protected lemma dist {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀ i, pseudo_metric_space (β i)] (x y : pi_Lp p hp β) : dist x y = (∑ (i : ι), (dist (x i) (y i)) ^ p) ^ (1/p) := rfl /-- seminormed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance semi_normed_group [∀i, semi_normed_group (β i)] : semi_normed_group (pi_Lp p hp β) := { norm := λf, (∑ (i : ι), norm (f i) ^ p) ^ (1/p), dist_eq := λ x y, by { simp [pi_Lp.dist, dist_eq_norm, sub_eq_add_neg] }, .. pi.add_comm_group } /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_group [∀i, normed_group (α i)] : normed_group (pi_Lp p hp α) := { ..pi_Lp.semi_normed_group p hp α } lemma norm_eq {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ p) ^ (1/p) := rfl lemma norm_eq_of_nat {p : ℝ} {hp : 1 ≤ p} {β : ι → Type*} [∀i, semi_normed_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p hp β) : ∥f∥ = (∑ (i : ι), ∥f i∥ ^ n) ^ (1/(n : ℝ)) := by simp [norm_eq, h, real.sqrt_eq_rpow, ←real.rpow_nat_cast] variables (𝕜 : Type*) [normed_field 𝕜] /-- The product of finitely many seminormed spaces is a seminormed space, with the `L^p` norm. -/ instance semi_normed_space [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] : semi_normed_space 𝕜 (pi_Lp p hp β) := { norm_smul_le := begin assume c f, have : p * (1 / p) = 1 := mul_div_cancel' 1 (ne_of_gt (lt_of_lt_of_le zero_lt_one hp)), simp only [pi_Lp.norm_eq, norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) end, .. pi.semimodule ι β 𝕜 } /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [∀i, normed_group (α i)] [∀i, normed_space 𝕜 (α i)] : normed_space 𝕜 (pi_Lp p hp α) := { ..pi_Lp.semi_normed_space p hp α 𝕜 } /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 p hp α} [∀i, semi_normed_group (β i)] [∀i, semi_normed_space 𝕜 (β i)] (c : 𝕜) (x y : pi_Lp p hp β) (i : ι) @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl end pi_Lp
1a0a28e169818dff9f8217c8955ad2b2e8875b23
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/finset/basic.lean
20cda225f8b52b0b87b21eb9a5e8b5d1fd2f2835
[ "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
128,767
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import data.multiset.finset_ops import tactic.apply import tactic.monotonicity import tactic.nth_rewrite /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. * `finset.card`: `card s : ℕ` returns the cardinalilty of `s : finset α`. The API for `card`'s interaction with operations on finsets is extensive. TODO: The noncomputable sister `fincard` is about to be added into mathlib. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.diag`: Given `s`, `diag s` is the set of pairs `(a, a)` with `a ∈ s`. See also `finset.off_diag`: Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.bUnion` for finite unions. * `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. TODO: `finset.bInter` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.union`: see "The lattice structure on subsets of finsets" * `finset.inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.prod`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.sigma`: Given finsets of `α` and `β`, defines finsets of the dependent sum type `Σ α, β` * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open multiset subtype nat function variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type*} : has_coe_to_sort (finset α) := ⟨_, λ s, {x // x ∈ s}⟩ instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (s : finset ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α (∈ s) } instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) : can_lift (s → α) (ι → α) := pi_finset_coe.can_lift ι (λ _, α) s instance finset_coe.can_lift (s : finset α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } @[simp, norm_cast] lemma coe_sort_coe (s : finset α) : ((s : set α) : Sort*) = s := rfl /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } /-- Coercion to `set α` as an `order_embedding`. -/ def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩ @[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff theorem not_subset (s t : finset α) : ¬(s ⊆ t) ↔ ∃ x ∈ s, ¬(x ∈ t) := by simp only [←finset.coe_subset, set.not_subset, exists_prop, finset.mem_coe] @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl alias coe_nonempty ↔ _ finset.nonempty.to_set lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero @[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ := λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := by { rw nonempty_iff_ne_empty, exact not_not, } theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem is_empty_elim /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { intros h, subst h, simp, }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, }, end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := begin split, { intro hs, apply or.imp_right _ s.eq_empty_or_nonempty, rintro ⟨t, ht⟩, apply subset.antisymm hs, rwa [singleton_subset_iff, ←mem_singleton.1 (hs ht)] }, rintro (rfl | rfl), { exact empty_subset _ }, exact subset.refl _, end @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {α a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty section universe u /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype end lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s₁ t₁ s₂ t₂ : finset α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∪ s₂ ⊆ t₁ ∪ t₂ := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma exists_mem_subset_of_subset_bUnion_of_directed_on {α ι : Type*} {f : ι → set α} {c : set ι} {a : ι} (hac : a ∈ c) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { intros, use [a, hac], simp }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hic : i ∈ c, hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hjc, hbj⟩ : ∃ j ∈ c, b ∈ f j, by simpa [set.mem_bUnion_iff] using hbtc (t.mem_insert_self b), rcases hc j hjc i hic with ⟨k, hkc, hk, hk'⟩, use [k, hkc], rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ -- TODO: some of these results may have simpler proofs, once there are enough results -- to obtain the `lattice` instance. theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } @[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff {s₁ s₂ s₃ : finset α} : s₁ ∪ s₂ ⊆ s₃ ↔ s₁ ⊆ s₃ ∧ s₂ ⊆ s₃ := (sup_le_iff : s₁ ⊔ s₂ ≤ s₃ ↔ s₁ ≤ s₃ ∧ s₂ ≤ s₃) lemma subset_inter_iff {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ ∩ s₃ ↔ s₁ ⊆ s₂ ∧ s₁ ⊆ s₃ := (le_inf_iff : s₁ ≤ s₂ ⊓ s₃ ↔ s₁ ≤ s₂ ∧ s₁ ≤ s₃) theorem inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := (inf_eq_left : s ⊓ t = s ↔ s ≤ t) theorem inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := (inf_eq_right : t ⊓ s = s ↔ s ≤ t) /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.semilattice_inf_bot } lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := sup_sdiff_of_le h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := sdiff_inf @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := sdiff_inf_self_left @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := sdiff_inf_self_right @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := sdiff_bot @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := sup_sdiff_symm lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma sdiff_ssubset {s t : finset α} (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt (le_iff_subset.2 h) ht.ne_empty lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ lemma monotone_filter_left (p : α → Prop) [decidable_pred p] : monotone (filter p) := λ _ _, filter_subset_filter p lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := multiset.subset_of_le (multiset.monotone_filter_right s.val h) @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ nat.sub_pos_of_lt $ mem_range.1 hx @[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 := ⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne', λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩ @[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] lemma nonempty_range_succ : (range $ n + 1).nonempty := nonempty_range_iff.2 n.succ_ne_zero end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply nat.sub_add_cancel, simpa using j.2 end, right_inv := λ j, nat.add_sub_cancel _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset : option α → finset α | none := ∅ | (some a) := {a} @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = {a} := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l = l' := by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} := by rw [singleton_eq_cons, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq] @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } end finset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := begin rintro s -, cases s with t hl, induction t using quot.ind with l, refine ⟨l, hl, (to_finset_eq hl).symm⟩ end theorem to_finset_surjective : surjective (to_finset : list α → finset α) := by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ } lemma to_finset_eq_iff_perm_erase_dup {l l' : list α} : l.to_finset = l'.to_finset ↔ l.erase_dup ~ l'.erase_dup := by simp [finset.ext_iff, perm_ext (nodup_erase_dup _) (nodup_erase_dup _)] lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_erase_dup.mpr h.erase_dup lemma perm_of_nodup_nodup_to_finset_eq {l l' : list α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l ~ l' := begin rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h end @[simp] lemma to_finset_append {l l' : list α} : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl @[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s := by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ } theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f := mem_map_of_mem f x.prop @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f := calc ↑(s.map f) = f '' s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) : s.map (equiv.cast h).to_embedding == s := by { subst h, simp } theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] /-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := eq_of_veq (map_filter _ _ _) theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := ext $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ lemma _root_.function.injective.mem_finset_image {f : α → β} (hf : function.injective f) {s : finset α} {x : α} : f x ∈ s.image f ↔ x ∈ s := begin refine ⟨λ h, _, finset.mem_image_of_mem f⟩, obtain ⟨y, hy, heq⟩ := mem_image.1 h, exact hf heq ▸ hy, end lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ @[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty := ⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := begin split, { rintros ⟨i, hi⟩, simp only [mem_image, exists_prop, mem_range], exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ }, { rintro h, simp only [mem_image, exists_prop, set.mem_range, mem_range] at *, rcases h with ⟨i, hi, ha⟩, use ⟨i, ha⟩ }, end lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Because `finset.image` requires a `decidable_eq` instances for the target type, we can only construct a `functor finset` when working classically. -/ instance [Π P, decidable P] : functor finset := { map := λ α β f s, s.image f, } instance [Π P, decidable P] : is_lawful_functor finset := { id_map := λ α x, image_id, comp_map := λ α β γ f g s, image_image.symm, } /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, rw mem_map, change (∃ a : {x // p x}, ∃ H, (a : α) = x) ↔ _, split, { rintros ⟨y, hy, hyval⟩, rw [mem_subtype, hyval] at hy, rw mem_filter, use hy, rw ← hyval, use y.property }, { intro hx, rw mem_filter at hx, use ⟨⟨x, hx.2⟩, mem_subtype.2 hx.1, rfl⟩ } end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin classical, split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { refine ⟨∅, set.empty_subset _, _⟩, convert finset.image_empty _ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi], congr end end image end finset theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm namespace finset /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val] theorem card_le_one {s : finset α} : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b := begin rcases s.eq_empty_or_nonempty with rfl|⟨x, hx⟩, { simp }, refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩), { rintro ⟨y, rfl⟩, simp }, { exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ } end theorem card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by { rw card_le_one, tauto } lemma card_le_one_iff_subset_singleton [nonempty α] {s : finset α} : s.card ≤ 1 ↔ ∃ (x : α), s ⊆ {x} := begin split, { assume H, by_cases h : ∃ x, x ∈ s, { rcases h with ⟨x, hx⟩, refine ⟨x, λ y hy, _⟩, rw [card_le_one.1 H y hy x hx, mem_singleton] }, { push_neg at h, inhabit α, exact ⟨default α, λ y hy, (h y hy).elim⟩ } }, { rintros ⟨x, hx⟩, rw ← card_singleton x, exact card_le_of_subset hx } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ theorem one_lt_card {s : finset α} : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b := by { rw ← not_iff_not, push_neg, exact card_le_one } lemma exists_ne_of_one_lt_card {s : finset α} (hs : 1 < s.card) (a : α) : ∃ b : α, b ∈ s ∧ b ≠ a := begin obtain ⟨x, hx, y, hy, hxy⟩ := finset.one_lt_card.mp hs, by_cases ha : y = a, { exact ⟨x, hx, ne_of_ne_of_eq hxy ha⟩ }, { exact ⟨y, hy, ha⟩ }, end lemma one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := by { rw one_lt_card, simp only [exists_prop, exists_and_distrib_left] } @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem x s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] }, end theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := begin by_cases h : a ∈ s, { rw [card_erase_of_mem h], refl }, { rw [erase_eq_of_not_mem h], apply nat.sub_le } end @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) lemma list.card_to_finset [decidable_eq α] (l : list α) : finset.card l.to_finset = l.erase_dup.length := rfl theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : set.inj_on f s) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem inj_on_of_card_image_eq [decidable_eq β] {f : α → β} {s : finset α} (H : card (image f s) = card s) : set.inj_on f s := begin change (s.1.map f).erase_dup.card = s.1.card at H, have : (s.1.map f).erase_dup = s.1.map f, { apply multiset.eq_of_le_of_card_le, { apply multiset.erase_dup_le }, rw H, simp only [multiset.card_map] }, rw multiset.erase_dup_eq_self at this, apply inj_on_of_nodup_map this, end theorem card_image_eq_iff_inj_on [decidable_eq β] {f : α → β} {s : finset α} : (s.image f).card = s.card ↔ set.inj_on f s := ⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩ theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ @[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) : (s.subtype p).card = (s.filter p).card := by simp [finset.subtype] lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] : card (s.filter p) ≤ card s := card_le_of_subset $ filter_subset _ _ theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma filter_card_eq {s : finset α} {p : α → Prop} [decidable_pred p] (h : (s.filter p).card = s.card) (x : α) (hx : x ∈ s) : p x := begin rw [←eq_of_subset_of_card_le (s.filter_subset p) h.ge, mem_filter] at hx, exact hx.2, end lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ image_subset_iff.2 hf end /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra hz, push_neg at hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma le_card_of_inj_on_range {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀ (i<n) (j<n), f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range]) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) : ∀ (s : finset α), p s | s := H s (λ t h, have card t < card s, from card_lt_card h, strong_induction t) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) : strong_induction H s = H s (λ t h, strong_induction H t) := by rw strong_induction /-- Analogue of `strong_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀ t ⊂ s, p t) → p s) → p s := λ s H, strong_induction H s lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) : s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) := by { dunfold strong_induction_on, rw strong_induction } @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of cardinality less than `n`, starting from finsets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : finset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - card t < n - card s, from (nat.sub_lt_sub_left_iff ht).2 (finset.card_lt_card h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : finset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : finset α) : strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) := by rw strong_downward_induction /-- Analogue of `strong_downward_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_downward_induction_on {p : finset α → Sort*} {n : ℕ} : ∀ (s : finset α), (∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) → s.card ≤ n → p s := λ s H, strong_downward_induction H s lemma strong_downward_induction_on_eq {p : finset α → Sort*} (s : finset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) := by { dunfold strong_downward_induction_on, rw strong_downward_induction } lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ nat.le_add_right _ _ lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) : (s ∪ t).card = s.card + t.card := begin rw [← card_union_add_card_inter], convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h end lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card section to_list /-- Produce a list of the elements in the finite set using choice. -/ @[reducible] noncomputable def to_list (s : finset α) : list α := s.1.to_list lemma nodup_to_list (s : finset α) : s.to_list.nodup := by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup } @[simp] lemma mem_to_list {a : α} (s : finset α) : a ∈ s.to_list ↔ a ∈ s := by { rw [to_list, ←multiset.mem_coe, multiset.coe_to_list], exact iff.rfl } @[simp] lemma length_to_list (s : finset α) : s.to_list.length = s.card := by { rw [to_list, ←multiset.coe_card, multiset.coe_to_list], refl } @[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := by simp [to_list] @[simp, norm_cast] lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := by { classical, ext, simp } @[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s := by { ext, simp } lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) : ∃ (l : list α), l.nodup ∧ l.to_finset = s := ⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩ end to_list section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := begin classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] end theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bUnion t = s.bUnion (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bUnion_insert, ih]) theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bUnion t).image f = s.bUnion (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bUnion_insert, image_union, ih]) lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) : (s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) := begin ext, simp only [finset.mem_bUnion, exists_prop], simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc], rw exists_comm, end theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem {s : finset α} (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := begin apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)), exact subset_of_eq singleton_bUnion.symm, end @[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β] {s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h, λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩ lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm] @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := by { rw bUnion_singleton, exact image_id } lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λa, s.filter $ (λc, f c = a)) = s := ext $ λ b, by simpa using h b lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s := bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g) lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } end bUnion /-! ### prod -/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ (s.image prod.fst).product (s.image prod.snd) := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ theorem product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bUnion (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] lemma product_bUnion {β γ : Type*} [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) : (s.product t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) := by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] } @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros; finish, }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, }, end lemma empty_product (t : finset β) : (∅ : finset α).product t = ∅ := rfl lemma product_empty (s : finset α) : s.product (∅ : finset β) = ∅ := eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2) end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma @[simp] theorem sigma_nonempty : (s.sigma t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty] @[simp] theorem sigma_eq_empty : s.sigma t = ∅ ↔ ∀ x ∈ s, t x = ∅ := by simp only [← not_nonempty_iff_eq_empty, sigma_nonempty, not_exists] @[mono] theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bUnion [decidable_eq (Σ a, σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bUnion (λa, (t a).map $ embedding.sigma_mk a) := by { ext ⟨x, y⟩, simp [and.left_comm] } end sigma /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], } end disjoint section self_prod variables (s : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, finish, }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end end self_prod /-- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, { have : (A \ B).nonempty, { rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ], rw mem_sdiff at ha, exact ha.1 }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintros t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } } end /-- We can shrink A to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ /-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/ def fin_range (k : ℕ) : finset (fin k) := ⟨list.fin_range k, list.nodup_fin_range k⟩ @[simp] lemma fin_range_card {k : ℕ} : (fin_range k).card = k := by simp [fin_range] @[simp] lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k := list.mem_fin_range m @[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ := set.eq_univ_of_forall mem_fin_range /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp 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 theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp } @[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl @[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr := by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] } end equiv namespace multiset variable [decidable_eq α] theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card := congr_arg card $ multiset.erase_dup_eq_self.mpr h lemma disjoint_to_finset {m1 m2 : multiset α} : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := multiset.to_finset_card_of_nodup h lemma disjoint_to_finset_iff_disjoint {l l' : list α} : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' := multiset.disjoint_to_finset end list
e38fd4a5d165b4722798e4b26951718ae540fb25
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/duplicate.lean
8aec14aa72b7a247a2521147155dba7b5d406824
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,345
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky, Chris Hughes -/ import data.fin.basic import data.list.nodup /-! # List duplicates ## Main definitions * `list.duplicate x l : Prop` is an inductive property that holds when `x` is a duplicate in `l` ## Implementation details In this file, `x ∈+ l` notation is shorthand for `list.duplicate x l`. -/ variable {α : Type*} namespace list /-- Property that an element `x : α` of `l : list α` can be found in the list more than once. -/ inductive duplicate (x : α) : list α → Prop | cons_mem {l : list α} : x ∈ l → duplicate (x :: l) | cons_duplicate {y : α} {l : list α} : duplicate l → duplicate (y :: l) local infix ` ∈+ `:50 := list.duplicate variables {l : list α} {x : α} lemma mem.duplicate_cons_self (h : x ∈ l) : x ∈+ x :: l := duplicate.cons_mem h lemma duplicate.duplicate_cons (h : x ∈+ l) (y : α) : x ∈+ y :: l := duplicate.cons_duplicate h lemma duplicate.mem (h : x ∈+ l) : x ∈ l := begin induction h with l' h y l' h hm, { exact mem_cons_self _ _ }, { exact mem_cons_of_mem _ hm } end lemma duplicate.mem_cons_self (h : x ∈+ x :: l) : x ∈ l := begin cases h with _ h _ _ h, { exact h }, { exact h.mem } end @[simp] lemma duplicate_cons_self_iff : x ∈+ x :: l ↔ x ∈ l := ⟨duplicate.mem_cons_self, mem.duplicate_cons_self⟩ lemma duplicate.ne_nil (h : x ∈+ l) : l ≠ [] := λ H, (mem_nil_iff x).mp (H ▸ h.mem) @[simp] lemma not_duplicate_nil (x : α) : ¬ x ∈+ [] := λ H, H.ne_nil rfl lemma duplicate.ne_singleton (h : x ∈+ l) (y : α) : l ≠ [y] := begin induction h with l' h z l' h hm, { simp [ne_nil_of_mem h] }, { simp [ne_nil_of_mem h.mem] } end @[simp] lemma not_duplicate_singleton (x y : α) : ¬ x ∈+ [y] := λ H, H.ne_singleton _ rfl lemma duplicate.elim_nil (h : x ∈+ []) : false := not_duplicate_nil x h lemma duplicate.elim_singleton {y : α} (h : x ∈+ [y]) : false := not_duplicate_singleton x y h lemma duplicate_cons_iff {y : α} : x ∈+ y :: l ↔ (y = x ∧ x ∈ l) ∨ x ∈+ l := begin refine ⟨λ h, _, λ h, _⟩, { cases h with _ hm _ _ hm, { exact or.inl ⟨rfl, hm⟩ }, { exact or.inr hm } }, { rcases h with ⟨rfl|h⟩|h, { simpa }, { exact h.cons_duplicate } } end lemma duplicate.of_duplicate_cons {y : α} (h : x ∈+ y :: l) (hx : x ≠ y) : x ∈+ l := by simpa [duplicate_cons_iff, hx.symm] using h lemma duplicate_cons_iff_of_ne {y : α} (hne : x ≠ y) : x ∈+ y :: l ↔ x ∈+ l := by simp [duplicate_cons_iff, hne.symm] lemma duplicate.mono_sublist {l' : list α} (hx : x ∈+ l) (h : l <+ l') : x ∈+ l' := begin induction h with l₁ l₂ y h IH l₁ l₂ y h IH, { exact hx }, { exact (IH hx).duplicate_cons _ }, { rw duplicate_cons_iff at hx ⊢, rcases hx with ⟨rfl, hx⟩|hx, { simp [h.subset hx] }, { simp [IH hx] } } end /-- The contrapositive of `list.nodup_iff_sublist`. -/ lemma duplicate_iff_sublist : x ∈+ l ↔ [x, x] <+ l := begin induction l with y l IH, { simp }, { by_cases hx : x = y, { simp [hx, cons_sublist_cons_iff, singleton_sublist] }, { rw [duplicate_cons_iff_of_ne hx, IH], refine ⟨sublist_cons_of_sublist y, λ h, _⟩, cases h, { assumption }, { contradiction } } } end lemma nodup_iff_forall_not_duplicate : nodup l ↔ ∀ (x : α), ¬ x ∈+ l := by simp_rw [nodup_iff_sublist, duplicate_iff_sublist] lemma exists_duplicate_iff_not_nodup : (∃ (x : α), x ∈+ l) ↔ ¬ nodup l := by simp [nodup_iff_forall_not_duplicate] lemma duplicate.not_nodup (h : x ∈+ l) : ¬ nodup l := λ H, nodup_iff_forall_not_duplicate.mp H _ h lemma duplicate_iff_two_le_count [decidable_eq α] : (x ∈+ l) ↔ 2 ≤ count x l := by simp [duplicate_iff_sublist, le_count_iff_repeat_sublist] instance decidable_duplicate [decidable_eq α] (x : α) : ∀ (l : list α), decidable (x ∈+ l) | [] := is_false (not_duplicate_nil x) | (y :: l) := match decidable_duplicate l with | is_true h := is_true (h.duplicate_cons y) | is_false h := if hx : y = x ∧ x ∈ l then is_true (hx.left.symm ▸ hx.right.duplicate_cons_self) else is_false (by simpa [duplicate_cons_iff, h] using hx) end end list
9441877b1e56a1b708cfd08751547e59b8456861
fe208a542cea7b2d6d7ff79f94d535f6d11d814a
/src/Dedekind_cuts/jean_lo.lean
3f04d363d317464cb912acc713f9010c77528bb4
[]
no_license
ImperialCollegeLondon/M1F_room_342_questions
c4b98b14113fe900a7f388762269305faff73e63
63de9a6ab9c27a433039dd5530bc9b10b1d227f7
refs/heads/master
1,585,807,312,561
1,545,232,972,000
1,545,232,972,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,792
lean
import data.rat data.set.basic order.bounds structure dedekind_real := (carrier: set ℚ) (nonemp: ∃ a, a ∈ carrier) (nonrat: ∃ a, a ∉ carrier) (down: ∀ p ∈ carrier, ∀ q, q < p → q ∈ carrier) (init: ∀ p ∈ carrier, ∀ q ∉ carrier, p < q) notation `ℝ` := dedekind_real instance: has_coe ℝ (set ℚ) := ⟨λ r, r.carrier⟩ namespace dedekind_real theorem eq_of_carrier_eq: ∀ {α β: dedekind_real}, α.carrier = β.carrier → α = β | ⟨a, _, _, _, _⟩ ⟨b, _, _, _, _⟩ rfl := rfl theorem carrier_inj {α β: dedekind_real}: α.carrier = β.carrier ↔ α = β := ⟨eq_of_carrier_eq, λ h, congr_arg carrier h⟩ protected def le (α β: ℝ): Prop := (α: set ℚ) ⊆ β instance: has_le ℝ := ⟨dedekind_real.le⟩ end dedekind_real open dedekind_real -- a lemma about inequalities and set membership. theorem Q_1a (α: ℝ) (r s: ℚ): r ∉ (α: set ℚ) → r < s → s ∉ (α: set ℚ) := λ hna hlt hsa, hna (α.down s hsa r hlt) -- linear order on the Dedekind reals. -- -- this is a definition rather than a theorem so that it can be used -- as data for type class inference. def Q_1b: linear_order ℝ := { le := dedekind_real.le, le_total := λ α β, classical.or_iff_not_imp_left.2 (λ h b hb, exists.elim (set.not_subset.1 h) (λ a ⟨ha, hnb⟩, or.elim (le_or_gt a b) (λ hle, false.elim (not_le_of_gt (β.init b hb a hnb) hle)) (λ hgt, α.down a ha b hgt))), le_antisymm := λ α β h1 h2, eq_of_carrier_eq (set.subset.antisymm h1 h2), le_trans := λ α β γ h1 h2 c ha, h2 (h1 ha), le_refl := λ a c h, h } instance: linear_order ℝ := Q_1b -- the Dedekind reals have the least upper bound property: -- the lub of a set of Dedekind reals is the union of all its elements. theorem Q_1c (S: set ℝ): (∃ σ: ℝ, σ ∈ S) → (∃ τ: ℝ, ∀ σ ∈ S, τ ≥ σ) → (∃ γ: ℝ, is_lub S γ) := λ ⟨σ, hσ⟩ ⟨τ, hτ⟩, ⟨ -- the union is itself a Dedekind real: { carrier := { a: ℚ | ∃ α ∈ S, a ∈ (α: set ℚ) }, nonemp := exists.elim σ.nonemp $ λ a haσ, ⟨a, ⟨σ, ⟨hσ, haσ⟩⟩⟩, nonrat := exists.elim τ.nonrat $ λ t htτ, ⟨t, (λ ⟨α, ⟨hα, htα⟩⟩, htτ $ (hτ α hα) htα)⟩, down := λ p ⟨α, ⟨hαS, hpα⟩⟩ q hqp, ⟨α, ⟨hαS, α.down p hpα q hqp⟩⟩, init := λ p ⟨α, ⟨hαS, hpα⟩⟩ q hqu, lt_of_not_ge $ λ hpq, hqu ⟨α, ⟨hαS, or.elim (eq_or_lt_of_le hpq) (λ heq, heq.symm ▸ hpα) (λ hle, α.down p hpα q hle)⟩⟩, }, -- & it satisfies the conditions for it to be a least upper bound. ⟨ λ α hαS a haα, ⟨α, ⟨hαS, haα⟩⟩, λ γ hγ g ⟨α, ⟨hαS, hgα⟩⟩, hγ α hαS hgα ⟩ ⟩
58cbc474a499fc39ca1461813ab6c48134101259
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/noncomputable_example.lean
de4542d7ef3c984f0453b36c3d598f4bd2940205
[ "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
396
lean
universe u open classical psum variables (A : Type u) (h : (A → false) → false) -- both noncomputable example... noncomputable example : A := match type_decidable A with | (inl ha) := ha | (inr hna) := false.rec _ (h hna) end -- ... and noncomputable theory should work noncomputable theory example : A := match type_decidable A with | (inl ha) := ha | (inr hna) := false.rec _ (h hna) end
3aef0c0a96e1f91d3934b884d20499e958da044c
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/finset/n_ary.lean
3a0db131eab7b99e1bcdca12111b69be2216e544
[ "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
20,035
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.prod import data.set.finite /-! # N-ary images of finsets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `finset.image₂`, the binary image of finsets. This is the finset version of `set.image2`. This is mostly useful to define pointwise operations. ## Notes This file is very similar to `data.set.n_ary`, `order.filter.n_ary` and `data.option.n_ary`. Please keep them in sync. We do not define `finset.image₃` as its only purpose would be to prove properties of `finset.image₂` and `set.image2` already fulfills this task. -/ open function set variables {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*} namespace finset variables [decidable_eq α'] [decidable_eq β'] [decidable_eq γ] [decidable_eq γ'] [decidable_eq δ] [decidable_eq δ'] [decidable_eq ε] [decidable_eq ε'] {f f' : α → β → γ} {g g' : α → β → γ → δ} {s s' : finset α} {t t' : finset β} {u u' : finset γ} {a a' : α} {b b' : β} {c : γ} /-- The image of a binary function `f : α → β → γ` as a function `finset α → finset β → finset γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image₂ (f : α → β → γ) (s : finset α) (t : finset β) : finset γ := (s ×ˢ t).image $ uncurry f @[simp] lemma mem_image₂ : c ∈ image₂ f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := by simp [image₂, and_assoc] @[simp, norm_cast] lemma coe_image₂ (f : α → β → γ) (s : finset α) (t : finset β) : (image₂ f s t : set γ) = set.image2 f s t := set.ext $ λ _, mem_image₂ lemma card_image₂_le (f : α → β → γ) (s : finset α) (t : finset β) : (image₂ f s t).card ≤ s.card * t.card := card_image_le.trans_eq $ card_product _ _ lemma card_image₂_iff : (image₂ f s t).card = s.card * t.card ↔ (s ×ˢ t : set (α × β)).inj_on (λ x, f x.1 x.2) := by { rw [←card_product, ←coe_product], exact card_image_iff } lemma card_image₂ (hf : injective2 f) (s : finset α) (t : finset β) : (image₂ f s t).card = s.card * t.card := (card_image_of_injective _ hf.uncurry).trans $ card_product _ _ lemma mem_image₂_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image₂ f s t := mem_image₂.2 ⟨a, b, ha, hb, rfl⟩ lemma mem_image₂_iff (hf : injective2 f) : f a b ∈ image₂ f s t ↔ a ∈ s ∧ b ∈ t := by rw [←mem_coe, coe_image₂, mem_image2_iff hf, mem_coe, mem_coe] lemma image₂_subset (hs : s ⊆ s') (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s' t' := by { rw [←coe_subset, coe_image₂, coe_image₂], exact image2_subset hs ht } lemma image₂_subset_left (ht : t ⊆ t') : image₂ f s t ⊆ image₂ f s t' := image₂_subset subset.rfl ht lemma image₂_subset_right (hs : s ⊆ s') : image₂ f s t ⊆ image₂ f s' t := image₂_subset hs subset.rfl lemma image_subset_image₂_left (hb : b ∈ t) : s.image (λ a, f a b) ⊆ image₂ f s t := image_subset_iff.2 $ λ a ha, mem_image₂_of_mem ha hb lemma image_subset_image₂_right (ha : a ∈ s) : t.image (λ b, f a b) ⊆ image₂ f s t := image_subset_iff.2 $ λ b, mem_image₂_of_mem ha lemma forall_image₂_iff {p : γ → Prop} : (∀ z ∈ image₂ f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := by simp_rw [←mem_coe, coe_image₂, forall_image2_iff] @[simp] lemma image₂_subset_iff : image₂ f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image₂_iff lemma image₂_subset_iff_left : image₂ f s t ⊆ u ↔ ∀ a ∈ s, t.image (λ b, f a b) ⊆ u := by simp_rw [image₂_subset_iff, image_subset_iff] lemma image₂_subset_iff_right : image₂ f s t ⊆ u ↔ ∀ b ∈ t, s.image (λ a, f a b) ⊆ u := by simp_rw [image₂_subset_iff, image_subset_iff, @forall₂_swap α] @[simp] lemma image₂_nonempty_iff : (image₂ f s t).nonempty ↔ s.nonempty ∧ t.nonempty := by { rw [←coe_nonempty, coe_image₂], exact image2_nonempty_iff } lemma nonempty.image₂ (hs : s.nonempty) (ht : t.nonempty) : (image₂ f s t).nonempty := image₂_nonempty_iff.2 ⟨hs, ht⟩ lemma nonempty.of_image₂_left (h : (image₂ f s t).nonempty) : s.nonempty := (image₂_nonempty_iff.1 h).1 lemma nonempty.of_image₂_right (h : (image₂ f s t).nonempty) : t.nonempty := (image₂_nonempty_iff.1 h).2 @[simp] lemma image₂_empty_left : image₂ f ∅ t = ∅ := coe_injective $ by simp @[simp] lemma image₂_empty_right : image₂ f s ∅ = ∅ := coe_injective $ by simp @[simp] lemma image₂_eq_empty_iff : image₂ f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [←not_nonempty_iff_eq_empty, image₂_nonempty_iff, not_and_distrib] @[simp] lemma image₂_singleton_left : image₂ f {a} t = t.image (λ b, f a b) := ext $ λ x, by simp @[simp] lemma image₂_singleton_right : image₂ f s {b} = s.image (λ a, f a b) := ext $ λ x, by simp lemma image₂_singleton_left' : image₂ f {a} t = t.image (f a) := image₂_singleton_left lemma image₂_singleton : image₂ f {a} {b} = {f a b} := by simp lemma image₂_union_left [decidable_eq α] : image₂ f (s ∪ s') t = image₂ f s t ∪ image₂ f s' t := coe_injective $ by { push_cast, exact image2_union_left } lemma image₂_union_right [decidable_eq β] : image₂ f s (t ∪ t') = image₂ f s t ∪ image₂ f s t' := coe_injective $ by { push_cast, exact image2_union_right } @[simp] lemma image₂_insert_left [decidable_eq α] : image₂ f (insert a s) t = t.image (λ b, f a b) ∪ image₂ f s t := coe_injective $ by { push_cast, exact image2_insert_left } @[simp] lemma image₂_insert_right [decidable_eq β] : image₂ f s (insert b t) = s.image (λ a, f a b) ∪ image₂ f s t := coe_injective $ by { push_cast, exact image2_insert_right } lemma image₂_inter_left [decidable_eq α] (hf : injective2 f) : image₂ f (s ∩ s') t = image₂ f s t ∩ image₂ f s' t := coe_injective $ by { push_cast, exact image2_inter_left hf } lemma image₂_inter_right [decidable_eq β] (hf : injective2 f) : image₂ f s (t ∩ t') = image₂ f s t ∩ image₂ f s t' := coe_injective $ by { push_cast, exact image2_inter_right hf } lemma image₂_inter_subset_left [decidable_eq α] : image₂ f (s ∩ s') t ⊆ image₂ f s t ∩ image₂ f s' t := coe_subset.1 $ by { push_cast, exact image2_inter_subset_left } lemma image₂_inter_subset_right [decidable_eq β] : image₂ f s (t ∩ t') ⊆ image₂ f s t ∩ image₂ f s t' := coe_subset.1 $ by { push_cast, exact image2_inter_subset_right } lemma image₂_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image₂ f s t = image₂ f' s t := coe_injective $ by { push_cast, exact image2_congr h } /-- A common special case of `image₂_congr` -/ lemma image₂_congr' (h : ∀ a b, f a b = f' a b) : image₂ f s t = image₂ f' s t := image₂_congr $ λ a _ b _, h a b lemma subset_image₂ {s : set α} {t : set β} (hu : ↑u ⊆ image2 f s t) : ∃ (s' : finset α) (t' : finset β), ↑s' ⊆ s ∧ ↑t' ⊆ t ∧ u ⊆ image₂ f s' t' := begin apply finset.induction_on' u, { exact ⟨∅, ∅, set.empty_subset _, set.empty_subset _, empty_subset _⟩ }, rintro a u ha _ _ ⟨s', t', hs, hs', h⟩, obtain ⟨x, y, hx, hy, ha⟩ := hu ha, haveI := classical.dec_eq α, haveI := classical.dec_eq β, refine ⟨insert x s', insert y t', _⟩, simp_rw [coe_insert, set.insert_subset], exact ⟨⟨hx, hs⟩, ⟨hy, hs'⟩, insert_subset.2 ⟨mem_image₂.2 ⟨x, y, mem_insert_self _ _, mem_insert_self _ _, ha⟩, h.trans $ image₂_subset (subset_insert _ _) $ subset_insert _ _⟩⟩, end variables (s t) lemma card_image₂_singleton_left (hf : injective (f a)) : (image₂ f {a} t).card = t.card := by rw [image₂_singleton_left, card_image_of_injective _ hf] lemma card_image₂_singleton_right (hf : injective (λ a, f a b)) : (image₂ f s {b}).card = s.card := by rw [image₂_singleton_right, card_image_of_injective _ hf] lemma image₂_singleton_inter [decidable_eq β] (t₁ t₂ : finset β) (hf : injective (f a)) : image₂ f {a} (t₁ ∩ t₂) = image₂ f {a} t₁ ∩ image₂ f {a} t₂ := by simp_rw [image₂_singleton_left, image_inter _ _ hf] lemma image₂_inter_singleton [decidable_eq α] (s₁ s₂ : finset α) (hf : injective (λ a, f a b)) : image₂ f (s₁ ∩ s₂) {b} = image₂ f s₁ {b} ∩ image₂ f s₂ {b} := by simp_rw [image₂_singleton_right, image_inter _ _ hf] lemma card_le_card_image₂_left {s : finset α} (hs : s.nonempty) (hf : ∀ a, injective (f a)) : t.card ≤ (image₂ f s t).card := begin obtain ⟨a, ha⟩ := hs, rw ←card_image₂_singleton_left _ (hf a), exact card_le_of_subset (image₂_subset_right $ singleton_subset_iff.2 ha), end lemma card_le_card_image₂_right {t : finset β} (ht : t.nonempty) (hf : ∀ b, injective (λ a, f a b)) : s.card ≤ (image₂ f s t).card := begin obtain ⟨b, hb⟩ := ht, rw ←card_image₂_singleton_right _ (hf b), exact card_le_of_subset (image₂_subset_left $ singleton_subset_iff.2 hb), end variables {s t} lemma bUnion_image_left : s.bUnion (λ a, t.image $ f a) = image₂ f s t := coe_injective $ by { push_cast, exact set.Union_image_left _ } lemma bUnion_image_right : t.bUnion (λ b, s.image $ λ a, f a b) = image₂ f s t := coe_injective $ by { push_cast, exact set.Union_image_right _ } /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `finset.image₂` of those operations. The proof pattern is `image₂_lemma operation_lemma`. For example, `image₂_comm mul_comm` proves that `image₂ (*) f g = image₂ (*) g f` in a `comm_semigroup`. -/ lemma image_image₂ (f : α → β → γ) (g : γ → δ) : (image₂ f s t).image g = image₂ (λ a b, g (f a b)) s t := coe_injective $ by { push_cast, exact image_image2 _ _ } lemma image₂_image_left (f : γ → β → δ) (g : α → γ) : image₂ f (s.image g) t = image₂ (λ a b, f (g a) b) s t := coe_injective $ by { push_cast, exact image2_image_left _ _ } lemma image₂_image_right (f : α → γ → δ) (g : β → γ) : image₂ f s (t.image g) = image₂ (λ a b, f a (g b)) s t := coe_injective $ by { push_cast, exact image2_image_right _ _ } @[simp] lemma image₂_mk_eq_product [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : image₂ prod.mk s t = s ×ˢ t := by ext; simp [prod.ext_iff] @[simp] lemma image₂_curry (f : α × β → γ) (s : finset α) (t : finset β) : image₂ (curry f) s t = (s ×ˢ t).image f := by { classical, rw [←image₂_mk_eq_product, image_image₂, curry] } @[simp] lemma image_uncurry_product (f : α → β → γ) (s : finset α) (t : finset β) : (s ×ˢ t).image (uncurry f) = image₂ f s t := by rw [←image₂_curry, curry_uncurry] lemma image₂_swap (f : α → β → γ) (s : finset α) (t : finset β) : image₂ f s t = image₂ (λ a b, f b a) t s := coe_injective $ by { push_cast, exact image2_swap _ _ _ } @[simp] lemma image₂_left [decidable_eq α] (h : t.nonempty) : image₂ (λ x y, x) s t = s := coe_injective $ by { push_cast, exact image2_left h } @[simp] lemma image₂_right [decidable_eq β] (h : s.nonempty) : image₂ (λ x y, y) s t = t := coe_injective $ by { push_cast, exact image2_right h } lemma image₂_assoc {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image₂ f (image₂ g s t) u = image₂ f' s (image₂ g' t u) := coe_injective $ by { push_cast, exact image2_assoc h_assoc } lemma image₂_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image₂ f s t = image₂ g t s := (image₂_swap _ _ _).trans $ by simp_rw h_comm lemma image₂_left_comm {γ : Type*} {u : finset γ} {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image₂ f s (image₂ g t u) = image₂ g' t (image₂ f' s u) := coe_injective $ by { push_cast, exact image2_left_comm h_left_comm } lemma image₂_right_comm {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image₂ f (image₂ g s t) u = image₂ g' (image₂ f' s u) t := coe_injective $ by { push_cast, exact image2_right_comm h_right_comm } lemma image₂_image₂_image₂_comm {γ δ : Type*} {u : finset γ} {v : finset δ} [decidable_eq ζ] [decidable_eq ζ'] [decidable_eq ν] {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ} {f' : ε' → ζ' → ν} {g' : α → γ → ε'} {h' : β → δ → ζ'} (h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) : image₂ f (image₂ g s t) (image₂ h u v) = image₂ f' (image₂ g' s u) (image₂ h' t v) := coe_injective $ by { push_cast, exact image2_image2_image2_comm h_comm } lemma image_image₂_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image₂ f s t).image g = image₂ f' (s.image g₁) (t.image g₂) := coe_injective $ by { push_cast, exact image_image2_distrib h_distrib } /-- Symmetric statement to `finset.image₂_image_left_comm`. -/ lemma image_image₂_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image₂ f s t).image g = image₂ f' (s.image g') t := coe_injective $ by { push_cast, exact image_image2_distrib_left h_distrib } /-- Symmetric statement to `finset.image_image₂_right_comm`. -/ lemma image_image₂_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image₂ f s t).image g = image₂ f' s (t.image g') := coe_injective $ by { push_cast, exact image_image2_distrib_right h_distrib } /-- Symmetric statement to `finset.image_image₂_distrib_left`. -/ lemma image₂_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image₂ f (s.image g) t = (image₂ f' s t).image g' := (image_image₂_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric statement to `finset.image_image₂_distrib_right`. -/ lemma image_image₂_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image₂ f s (t.image g) = (image₂ f' s t).image g' := (image_image₂_distrib_right $ λ a b, (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ lemma image₂_distrib_subset_left {γ : Type*} {u : finset γ} {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image₂ f s (image₂ g t u) ⊆ image₂ g' (image₂ f₁ s t) (image₂ f₂ s u) := coe_subset.1 $ by { push_cast, exact set.image2_distrib_subset_left h_distrib } /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ lemma image₂_distrib_subset_right {γ : Type*} {u : finset γ} {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image₂ f (image₂ g s t) u ⊆ image₂ g' (image₂ f₁ s u) (image₂ f₂ t u) := coe_subset.1 $ by { push_cast, exact set.image2_distrib_subset_right h_distrib } lemma image_image₂_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image₂ f s t).image g = image₂ f' (t.image g₁) (s.image g₂) := by { rw image₂_swap f, exact image_image₂_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric statement to `finset.image₂_image_left_anticomm`. -/ lemma image_image₂_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image₂ f s t).image g = image₂ f' (t.image g') s := coe_injective $ by { push_cast, exact image_image2_antidistrib_left h_antidistrib } /-- Symmetric statement to `finset.image_image₂_right_anticomm`. -/ lemma image_image₂_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image₂ f s t).image g = image₂ f' t (s.image g') := coe_injective $ by { push_cast, exact image_image2_antidistrib_right h_antidistrib } /-- Symmetric statement to `finset.image_image₂_antidistrib_left`. -/ lemma image₂_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image₂ f (s.image g) t = (image₂ f' t s).image g' := (image_image₂_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric statement to `finset.image_image₂_antidistrib_right`. -/ lemma image_image₂_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image₂ f s (t.image g) = (image₂ f' t s).image g' := (image_image₂_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm /-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for `finset.image₂ f`. -/ lemma image₂_left_identity {f : α → γ → γ} {a : α} (h : ∀ b, f a b = b) (t : finset γ) : image₂ f {a} t = t := coe_injective $ by rw [coe_image₂, coe_singleton, set.image2_left_identity h] /-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for `finset.image₂ f`. -/ lemma image₂_right_identity {f : γ → β → γ} {b : β} (h : ∀ a, f a b = a) (s : finset γ) : image₂ f s {b} = s := by rw [image₂_singleton_right, funext h, image_id'] variables [decidable_eq α] [decidable_eq β] lemma image₂_inter_union_subset_union : image₂ f (s ∩ s') (t ∪ t') ⊆ image₂ f s t ∪ image₂ f s' t' := coe_subset.1 $ by { push_cast, exact set.image2_inter_union_subset_union } lemma image₂_union_inter_subset_union : image₂ f (s ∪ s') (t ∩ t') ⊆ image₂ f s t ∪ image₂ f s' t' := coe_subset.1 $ by { push_cast, exact set.image2_union_inter_subset_union } lemma image₂_inter_union_subset {f : α → α → β} {s t : finset α} (hf : ∀ a b, f a b = f b a) : image₂ f (s ∩ t) (s ∪ t) ⊆ image₂ f s t := coe_subset.1 $ by { push_cast, exact image2_inter_union_subset hf } lemma image₂_union_inter_subset {f : α → α → β} {s t : finset α} (hf : ∀ a b, f a b = f b a) : image₂ f (s ∪ t) (s ∩ t) ⊆ image₂ f s t := coe_subset.1 $ by { push_cast, exact image2_union_inter_subset hf } end finset namespace set variables [decidable_eq γ] {s : set α} {t : set β} @[simp] lemma to_finset_image2 (f : α → β → γ) (s : set α) (t : set β) [fintype s] [fintype t] [fintype (image2 f s t)] : (image2 f s t).to_finset = finset.image₂ f s.to_finset t.to_finset := finset.coe_injective $ by simp lemma finite.to_finset_image2 (f : α → β → γ) (hs : s.finite) (ht : t.finite) (hf := hs.image2 f ht) : hf.to_finset = finset.image₂ f hs.to_finset ht.to_finset := finset.coe_injective $ by simp end set
d9cee38a14320c28d08bf26085de8ce672378a19
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Data/Json/FromToJson.lean
34dc91118be777a5d243acc9e4f60f68fde999ad
[ "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
5,325
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic import Lean.Data.Json.Printer namespace Lean universe u class FromJson (α : Type u) where fromJson? : Json → Except String α export FromJson (fromJson?) class ToJson (α : Type u) where toJson : α → Json export ToJson (toJson) instance : FromJson Json := ⟨Except.ok⟩ instance : ToJson Json := ⟨id⟩ instance : FromJson JsonNumber := ⟨Json.getNum?⟩ instance : ToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance : FromJson Bool := ⟨Json.getBool?⟩ instance : ToJson Bool := ⟨fun b => b⟩ instance : FromJson Nat := ⟨Json.getNat?⟩ instance : ToJson Nat := ⟨fun n => n⟩ instance : FromJson Int := ⟨Json.getInt?⟩ instance : ToJson Int := ⟨fun n => Json.num n⟩ instance : FromJson String := ⟨Json.getStr?⟩ instance : ToJson String := ⟨fun s => s⟩ instance : FromJson System.FilePath := ⟨fun j => System.FilePath.mk <$> Json.getStr? j⟩ instance : ToJson System.FilePath := ⟨fun p => p.toString⟩ instance [FromJson α] : FromJson (Array α) where fromJson? | Json.arr a => a.mapM fromJson? | j => throw s!"expected JSON array, got '{j}'" instance [ToJson α] : ToJson (Array α) := ⟨fun a => Json.arr (a.map toJson)⟩ instance [FromJson α] : FromJson (List α) where fromJson? j := (fromJson? j (α := Array α)).map Array.toList instance [ToJson α] : ToJson (List α) where toJson xs := toJson xs.toArray instance [FromJson α] : FromJson (Option α) where fromJson? | Json.null => Except.ok none | j => some <$> fromJson? j instance [ToJson α] : ToJson (Option α) := ⟨fun | none => Json.null | some a => toJson a⟩ instance [FromJson α] [FromJson β] : FromJson (α × β) where fromJson? | Json.arr #[ja, jb] => do let a ← fromJson? ja let b ← fromJson? jb return (a, b) | j => throw s!"expected pair, got '{j}'" instance [ToJson α] [ToJson β] : ToJson (α × β) where toJson := fun (a, b) => Json.arr #[toJson a, toJson b] instance : FromJson Name where fromJson? j := do let s ← j.getStr? if s == "[anonymous]" then return Name.anonymous else let some n := Syntax.decodeNameLit ("`" ++ s) | throw s!"expected a `Name`, got '{j}'" return n instance : ToJson Name where toJson n := toString n /-- Note that `USize`s and `UInt64`s are stored as strings because JavaScript cannot represent 64-bit numbers. -/ def bignumFromJson? (j : Json) : Except String Nat := do let s ← j.getStr? let some v := Syntax.decodeNatLitVal? s -- TODO maybe this should be in Std | throw s!"expected a string-encoded number, got '{j}'" return v def bignumToJson (n : Nat) : Json := toString n instance : FromJson USize where fromJson? j := do let n ← bignumFromJson? j if n ≥ USize.size then throw "value '{j}' is too large for `USize`" return USize.ofNat n instance : ToJson USize where toJson v := bignumToJson (USize.toNat v) instance : FromJson UInt64 where fromJson? j := do let n ← bignumFromJson? j if n ≥ UInt64.size then throw "value '{j}' is too large for `UInt64`" return UInt64.ofNat n instance : ToJson UInt64 where toJson v := bignumToJson (UInt64.toNat v) namespace Json instance : FromJson Structured := ⟨fun | arr a => return Structured.arr a | obj o => return Structured.obj o | j => throw s!"expected structured object, got '{j}'"⟩ instance : ToJson Structured := ⟨fun | Structured.arr a => arr a | Structured.obj o => obj o⟩ def toStructured? [ToJson α] (v : α) : Except String Structured := fromJson? (toJson v) def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α := fromJson? <| j.getObjValD k def opt [ToJson α] (k : String) : Option α → List (String × Json) | none => [] | some o => [⟨k, toJson o⟩] /-- Parses a JSON-encoded `structure` or `inductive` constructor. Used mostly by `deriving FromJson`. -/ def parseTagged (json : Json) (tag : String) (nFields : Nat) (fieldNames? : Option (Array Name)) : Except String (Array Json) := if nFields == 0 then match getStr? json with | Except.ok s => if s == tag then Except.ok #[] else throw s!"incorrect tag: {s} ≟ {tag}" | Except.error err => Except.error err else match getObjVal? json tag with | Except.ok payload => match fieldNames? with | some fieldNames => do let mut fields := #[] for fieldName in fieldNames do fields := fields.push (←getObjVal? payload fieldName.getString!) Except.ok fields | none => if nFields == 1 then Except.ok #[payload] else match getArr? payload with | Except.ok fields => if fields.size == nFields then Except.ok fields else Except.error s!"incorrect number of fields: {fields.size} ≟ {nFields}" | Except.error err => Except.error err | Except.error err => Except.error err end Json end Lean
9e6075248104a7dc2dca4cc643ad99d57808652e
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/basic.lean
55d0359b83892fcb239f9b9741421717f52bd520
[ "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
55,957
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import data.support /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open.inter /-- A set is closed if its complement is open -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ } lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open.inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open.inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open.sdiff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed.union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma is_open.inter_frontier_eq_empty_of_disjoint {s t : set α} (ht : is_open t) (hd : disjoint s t) : t ∩ frontier s = ∅ := begin rw [inter_comm, ← subset_compl_iff_disjoint], exact subset.trans frontier_subset_closure (closure_minimal (λ _, disjoint_left.1 hd) (is_closed_compl_iff.2 ht)) end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, split, { rintros ⟨s_in, s_op⟩, exact ⟨mem_of_mem_nhds s_in, s_op⟩ }, { rintros ⟨a_in, s_op⟩, exact ⟨is_open.mem_nhds s_op a_in, s_op⟩ }, end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZ' using this, refine ⟨⋃ x ∈ s, Z x, _, _, bUnion_subset hZ'⟩, { intros x hx, simp only [mem_Union], exact ⟨x, hx, (hZ x hx).1⟩ }, { apply is_open_Union, intros x, by_cases hx : x ∈ s ; simp [hx], exact (hZ x hx).2 } end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure_sets.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_sets_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.nonempty_inter_iff_exists_right] theorem mem_closure_iff_nhds_basis' {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_eq, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := begin rintro a ⟨hs, ht⟩, have : s ∈ 𝓝 a := is_open.mem_nhds h hs, rw mem_closure_iff_nhds_ne_bot at ht ⊢, rwa [← inf_principal, ← inf_assoc, inf_eq_left.2 (le_principal_iff.2 this)], end lemma closure_inter_open' {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using closure_inter_open h /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := is_closed_closure.mem_of_tendsto hf $ h.mono (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite.point_finite {f : β → set α} (hf : locally_finite f) (x : α) : finite {b | x ∈ f b} := let ⟨t, hxt, ht⟩ := hf x in ht.subset $ λ b hb, ⟨x, hb, mem_of_mem_nhds hxt⟩ lemma locally_finite_of_fintype [fintype β] (f : β → set α) : locally_finite f := assume x, ⟨univ, univ_mem_sets, finite.of_fintype _⟩ lemma locally_finite.subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma locally_finite.comp_injective {ι} {f : β → set α} {g : ι → β} (hf : locally_finite f) (hg : function.injective g) : locally_finite (f ∘ g) := λ x, let ⟨t, htx, htf⟩ := hf x in ⟨t, htx, htf.preimage (hg.inj_on _)⟩ lemma locally_finite.closure {f : β → set α} (hf : locally_finite f) : locally_finite (λ i, closure (f i)) := begin intro x, rcases hf x with ⟨s, hsx, hsf⟩, refine ⟨interior s, interior_mem_nhds.2 hsx, hsf.subset $ λ i hi, _⟩, exact (hi.mono (closure_inter_open' is_open_interior)).of_closure.mono (inter_subset_inter_right _ interior_subset) end lemma locally_finite.is_closed_Union {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_compl_iff.1 $ is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ (f i)ᶜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, (f i)ᶜ ∈ (𝓝 a), by simp only [mem_nhds_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, (h₂ i).is_open_compl, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) : by simp * ... ≤ 𝓟 (⋃i, f i)ᶜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end lemma locally_finite.closure_Union {f : β → set α} (h : locally_finite f) : closure (⋃ i, f i) = ⋃ i, closure (f i) := subset.antisymm (closure_minimal (Union_subset_Union $ λ _, subset_closure) $ h.closure.is_closed_Union $ λ _, is_closed_closure) (Union_subset $ λ i, closure_mono $ subset_Union _ _) end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_eq, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := set.maps_to.closure ht hf ha /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ end dense_range end continuous
54cf9dd7fbc956d23b43dd22d186c3b27e465bfe
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/full_subcategory.lean
418b03f2e5a565bd150ad8c94376eadbf2989a27
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
1,076
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .functor open categories.functor namespace categories definition {u v w} FullSubcategory ( C : Category.{u v} ) ( Z : C.Obj → Sort w ) : Category.{(max u w) v} := { Obj := Σ X : C.Obj, plift (Z X), Hom := λ X Y, C.Hom X.1 Y.1, identity := by tidy, compose := λ _ _ _ f g, C.compose f g, left_identity := ♯, right_identity := ♯, associativity := ♯ } definition {u1 v1 u2 v2 wc wd} Functor_restricts_to_FullSubcategory { C : Category.{u1 v1} } { D : Category.{u2 v2} } ( F : Functor C D ) ( ZC : C.Obj → Sort wc ) ( ZD : D.Obj → Sort wd ) ( w : ∀ { X : C.Obj } (z : ZC X), ZD (F.onObjects X) ) : Functor (FullSubcategory C ZC) (FullSubcategory D ZD) := { onObjects := λ X, ⟨ F.onObjects X.1, ⟨ w X.2.down ⟩ ⟩, onMorphisms := λ _ _ f, F.onMorphisms f, identities := ♯, functoriality := ♯ } end categories
e97269131f3c7622bb8d06aab37a5ae272a03e6d
df561f413cfe0a88b1056655515399c546ff32a5
/5-advanced-proposition-world/l9.lean
9822b1dc9207fa8c1b87660e631b7ac0e1c8505a
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
149
lean
lemma contra (P Q : Prop) : (P ∧ ¬ P) → Q := begin intro h, cases h with p notp, rw not_iff_imp_false at notp, exfalso, apply notp, exact p, end
ea6ae52e36c3633b2aaab942c842f385836c103f
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Deriving/Util.lean
3c4ef885aa1df3c458406af174f9d16b05f56395
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,768
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Elab.Term namespace Lean.Elab.Deriving open Meta def implicitBinderF := Parser.Term.implicitBinder def instBinderF := Parser.Term.instBinder def explicitBinderF := Parser.Term.explicitBinder def mkInductArgNames (indVal : InductiveVal) : TermElabM (Array Name) := do forallTelescopeReducing indVal.type fun xs _ => do let mut argNames := #[] for x in xs do let localDecl ← getLocalDecl x.fvarId! let paramName ← mkFreshUserName localDecl.userName.eraseMacroScopes argNames := argNames.push paramName pure argNames def mkInductiveApp (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := let f := mkIdent indVal.name let args := argNames.map mkIdent `(@$f $args*) def mkImplicitBinders (argNames : Array Name) : TermElabM (Array Syntax) := argNames.mapM fun argName => `(implicitBinderF| { $(mkIdent argName) }) def mkInstImplicitBinders (className : Name) (indVal : InductiveVal) (argNames : Array Name) : TermElabM (Array Syntax) := forallBoundedTelescope indVal.type indVal.numParams fun xs _ => do let mut binders := #[] for i in [:xs.size] do try let x := xs[i] let c ← mkAppM className #[x] if (← isTypeCorrect c) then let argName := argNames[i] let binder ← `(instBinderF| [ $(mkIdent className):ident $(mkIdent argName):ident ]) binders := binders.push binder catch _ => pure () return binders structure Context where typeInfos : Array InductiveVal auxFunNames : Array Name usePartial : Bool def mkContext (fnPrefix : String) (typeName : Name) : TermElabM Context := do let indVal ← getConstInfoInduct typeName let mut typeInfos := #[] for typeName in indVal.all do typeInfos ← typeInfos.push (← getConstInfoInduct typeName) let mut auxFunNames := #[] for typeName in indVal.all do match typeName.eraseMacroScopes with | Name.str _ t _ => auxFunNames := auxFunNames.push (← mkFreshUserName <| Name.mkSimple <| fnPrefix ++ t) | _ => auxFunNames := auxFunNames.push (← mkFreshUserName `instFn) trace[Elab.Deriving.beq]! "{auxFunNames}" let usePartial := indVal.isNested || typeInfos.size > 1 return { typeInfos := typeInfos auxFunNames := auxFunNames usePartial := usePartial } def mkLocalInstanceLetDecls (ctx : Context) (className : Name) (argNames : Array Name) : TermElabM (Array Syntax) := do let mut letDecls := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] let auxFunName := ctx.auxFunNames[i] let currArgNames ← mkInductArgNames indVal let numParams := indVal.numParams let currIndices := currArgNames[numParams:] let binders ← mkImplicitBinders currIndices let argNamesNew := argNames[:numParams] ++ currIndices let indType ← mkInductiveApp indVal argNamesNew let type ← `($(mkIdent className) $indType) let val ← `(⟨$(mkIdent auxFunName)⟩) let instName ← mkFreshUserName `localinst let letDecl ← `(Parser.Term.letDecl| $(mkIdent instName):ident $binders:implicitBinder* : $type := $val) letDecls := letDecls.push letDecl return letDecls def mkLet (letDecls : Array Syntax) (body : Syntax) : TermElabM Syntax := letDecls.foldrM (init := body) fun letDecl body => `(let $letDecl:letDecl; $body) def mkInstanceCmds (ctx : Context) (className : Name) (typeNames : Array Name) (useAnonCtor := true) : TermElabM (Array Syntax) := do let mut instances := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] if typeNames.contains indVal.name then let auxFunName := ctx.auxFunNames[i] let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let binders := binders ++ (← mkInstImplicitBinders className indVal argNames) let indType ← mkInductiveApp indVal argNames let type ← `($(mkIdent className) $indType) let val ← if useAnonCtor then `(⟨$(mkIdent auxFunName)⟩) else pure <| mkIdent auxFunName let instCmd ← `(instance $binders:implicitBinder* : $type := $val) trace[Meta.debug]! "\n{instCmd}" instances := instances.push instCmd return instances def mkDiscr (varName : Name) : TermElabM Syntax := `(Parser.Term.matchDiscr| $(mkIdent varName):term) structure Header where binders : Array Syntax argNames : Array Name targetNames : Array Name def mkHeader (ctx : Context) (className : Name) (arity : Nat) (indVal : InductiveVal) : TermElabM Header := do let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let targetType ← mkInductiveApp indVal argNames let mut targetNames := #[] for i in [:arity] do targetNames := targetNames.push (← mkFreshUserName `x) let binders := binders ++ (← mkInstImplicitBinders className indVal argNames) let binders := binders ++ (← targetNames.mapM fun targetName => `(explicitBinderF| ($(mkIdent targetName) : $targetType))) return { binders := binders argNames := argNames targetNames := targetNames } def mkDiscrs (header : Header) (indVal : InductiveVal) : TermElabM (Array Syntax) := do let mut discrs := #[] -- add indices for argName in header.argNames[indVal.numParams:] do discrs := discrs.push (← mkDiscr argName) return discrs ++ (← header.targetNames.mapM mkDiscr) end Lean.Elab.Deriving
2b74801163179ae9c1dec7dd66f3bd1e123efc19
d796eac6dc113f68ec6fc0579c13e8eae2bdef6c
/Resources/Code/Category+Theory-Github-Topic/monoidal-categories-reboot/src/monoidal_categories_reboot/braided_monoidal_category.lean
9f4a444873f8ee53e0a13115dee754f0b540ce1f
[ "Apache-2.0" ]
permissive
paddlelaw/functional-discipline-content-cats
5a7e13e8adedd96b94f66b0b3cbf1847bc86d7f6
d93b7aa849b343c384cec40c73ee84a9300004e8
refs/heads/master
1,675,541,859,508
1,607,251,766,000
1,607,251,766,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,017
lean
import category_theory.category import category_theory.functor import category_theory.products import category_theory.natural_isomorphism import .monoidal_category open category_theory open tactic universes v u open category_theory.category open category_theory.functor open category_theory.prod open category_theory.functor.category.nat_trans open category_theory.nat_iso namespace category_theory.monoidal class braided_monoidal_category (C : Sort u) extends monoidal_category.{v} C := -- braiding natural iso: (braiding : Π X Y : C, X ⊗ Y ≅ Y ⊗ X) (braiding_naturality' : ∀ {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (f ⊗ g) ≫ (braiding Y Y').hom = (braiding X X').hom ≫ (g ⊗ f) . obviously) -- hexagon identities: (hexagon_forward' : Π X Y Z : C, (associator X Y Z).hom ≫ (braiding X (Y ⊗ Z)).hom ≫ (associator Y Z X).hom = ((braiding X Y).hom ⊗ (𝟙 Z)) ≫ (associator Y X Z).hom ≫ (𝟙 Y) ⊗ (braiding X Z).hom . obviously) (hexagon_reverse' : Π X Y Z : C, (associator X Y Z).inv ≫ (braiding (X ⊗ Y) Z).hom ≫ (associator Z X Y).inv = ((𝟙 X) ⊗ (braiding Y Z).hom) ≫ (associator X Z Y).inv ≫ (braiding X Z).hom ⊗ (𝟙 Y) . obviously) restate_axiom braided_monoidal_category.braiding_naturality' attribute [simp,search] braided_monoidal_category.braiding_naturality restate_axiom braided_monoidal_category.hexagon_forward' attribute [simp,search] braided_monoidal_category.hexagon_forward restate_axiom braided_monoidal_category.hexagon_reverse' attribute [simp,search] braided_monoidal_category.hexagon_reverse section variables (C : Type u) [𝒞 : braided_monoidal_category.{v+1} C] include 𝒞 -- TODO not good names, should just take about `tensor_functor` and `swap ⋙ tensor_functor`. @[reducible] def braided_monoidal_category.braiding_functor : (C × C) ⥤ C := { obj := λ X, X.2 ⊗ X.1, map := λ {X Y : C × C} (f : X ⟶ Y), f.2 ⊗ f.1 } @[reducible] def braided_monoidal_category.non_braiding_functor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } open monoidal_category open braided_monoidal_category @[simp,search] def braiding_of_product (X Y Z : C) : (braiding (X ⊗ Y) Z).hom = (associator X Y Z).hom ≫ ((𝟙 X) ⊗ (braiding Y Z).hom) ≫ (associator X Z Y).inv ≫ ((braiding X Z).hom ⊗ (𝟙 Y)) ≫ (associator Z X Y).hom := begin obviously, end def braided_monoidal_category.braiding_nat_iso : braiding_functor C ≅ non_braiding_functor C := nat_iso.of_components (by intros; simp; apply braiding) (by intros; simp; apply braiding_naturality) end class symmetric_monoidal_category (C : Sort u) extends braided_monoidal_category.{v} C := -- braiding symmetric: (symmetry' : ∀ X Y : C, (braiding X Y).hom ≫ (braiding Y X).hom = 𝟙 (X ⊗ Y) . obviously) restate_axiom symmetric_monoidal_category.symmetry' attribute [simp,search] symmetric_monoidal_category.symmetry end category_theory.monoidal
c8d1dc97c06e7bcb572671f507783162298ce32a
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/elide.lean
14e2eb2f31b722d091229c81caee4523cffdbe08
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,175
lean
import logic.basic tactic.basic namespace tactic namespace elide meta def replace : ℕ → expr → tactic expr | 0 e := do t ← infer_type e, expr.sort u ← infer_type t, return $ (expr.const ``hidden [u]).app t e | (i+1) (expr.app f x) := do f' ← replace (i+1) f, x' ← replace i x, return (f' x') | (i+1) (expr.lam n b d e) := do d' ← replace i d, var ← mk_local' n b d, e' ← replace i (expr.instantiate_var e var), return (expr.lam n b d' (expr.abstract_local e' var.local_uniq_name)) | (i+1) (expr.pi n b d e) := do d' ← replace i d, var ← mk_local' n b d, e' ← replace i (expr.instantiate_var e var), return (expr.pi n b d' (expr.abstract_local e' var.local_uniq_name)) | (i+1) el@(expr.elet n t d e) := do t' ← replace i t, d' ← replace i d, var ← mk_local_def n d, e' ← replace i (expr.instantiate_var e var) | replace el 0, return (expr.elet n t' d' (expr.abstract_local e' var.local_uniq_name)) | (i+1) e := return e meta def unelide (e : expr) : expr := expr.replace e $ λ e n, match e with | (expr.app (expr.app (expr.const n _) _) e') := if n = ``hidden then some e' else none | (expr.app (expr.lam _ _ _ (expr.var 0)) e') := some e' | _ := none end end elide namespace interactive open interactive.types interactive /-- The `elide n (at ...)` tactic hides all subterms of the target goal or hypotheses beyond depth `n` by replacing them with `hidden`, which is a variant on the identity function. (Tactics should still mostly be able to see through the abbreviation, but if you want to unhide the term you can use `unelide`.) -/ meta def elide (n : ℕ) (loc : parse location) : tactic unit := loc.apply (λ h, infer_type h >>= tactic.elide.replace n >>= tactic.change_core h ∘ some) (target >>= tactic.elide.replace n >>= tactic.change) /-- The `unelide (at ...)` tactic removes all `hidden` subterms in the target types (usually added by `elide`). -/ meta def unelide (loc : parse location) : tactic unit := loc.apply (λ h, infer_type h >>= tactic.change_core h ∘ some ∘ elide.unelide) (target >>= tactic.change ∘ elide.unelide) end interactive end tactic
cc0b648f85fb1034896a66a08812c2a63febd597
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier11.lean
bf8907258244440dda202b8ecda9f86bc41396ad
[ "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,957
lean
-- Conditional congruence import logic.connectives logic.quantifiers -- TODO(dhs): add this to the library lemma not_false_true [simp] : (¬ false) ↔ true := sorry namespace if_congr constants {A : Type} {b c : Prop} (dec_b : decidable b) (dec_c : decidable c) {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) attribute dec_b [instance] attribute dec_c [instance] attribute h_c [simp] attribute h_t [simp] attribute h_e [simp] attribute if_congr [congr] #simplify eq env 0 (ite b x y) end if_congr namespace if_ctx_simp_congr constants {A : Type} {b c : Prop} (dec_b : decidable b) {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) attribute dec_b [instance] attribute h_c [simp] attribute h_t [simp] attribute h_e [simp] attribute if_ctx_simp_congr [congr] #simplify eq env 0 (ite b x y) end if_ctx_simp_congr namespace if_ctx_congr_prop constants {b c x y u v : Prop} (dec_b : decidable b) (dec_c : decidable c) (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) attribute dec_b [instance] attribute dec_c [instance] attribute h_c [simp] attribute h_t [simp] attribute h_e [simp] attribute if_ctx_congr_prop [congr] #simplify iff env 0 (ite b x y) end if_ctx_congr_prop namespace if_ctx_simp_congr_prop constants (b c x y u v : Prop) (dec_b : decidable b) (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬ c → (y ↔ v)) attribute dec_b [instance] attribute h_c [simp] attribute h_t [simp] attribute h_e [simp] attribute if_ctx_simp_congr_prop [congr] #simplify iff env 0 (ite b x y) end if_ctx_simp_congr_prop namespace if_simp_congr_prop constants (b c x y u v : Prop) (dec_b : decidable b) (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) attribute dec_b [instance] attribute h_c [simp] attribute h_t [simp] attribute h_e [simp] attribute if_simp_congr_prop [congr] #simplify iff env 0 (ite b x y) end if_simp_congr_prop
3b871f29ccc61bea9722a92c328b78833da0f5ae
7a468d7c7c0949ab8b191bb62ff6d4d2af9f3917
/test/inconsistent_context.lean
e1da3c5b3921db4d9193b154eb37770bcd9a05d9
[ "Apache-2.0" ]
permissive
seanpm2001/LeanProver_SMT2_Interface
c15b2fba021c406d965655b182eef54a14121b82
7ff0ce248b68ea4db2a2d4966a97b5786da05ed7
refs/heads/master
1,688,599,220,366
1,547,825,187,000
1,547,825,187,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
130
lean
import smt2 import .test_tactics lemma P_and_not_P_false (P : Prop) (p : P) (np : not P) : false := begin intros, z3 end
c1a116f977f51fd169eb74a8c1d8c65c3215d044
6f510b1ed724f95a55b7d26a8dcd13e1264123dd
/src/page01.lean
fdb80378e32a92a8e7a8d7bd9bd99ca745a3ff94
[]
no_license
jcommelin/oberharmersbach2019
adaf2e54ba4eff7c178c933978055ff4d6b0593b
d2cdf780a10baa8502a9b0cae01c7efa318649a6
refs/heads/master
1,587,558,516,731
1,550,558,213,000
1,550,558,213,000
170,372,753
0
0
null
null
null
null
UTF-8
Lean
false
false
241
lean
import data.real.basic /- Type theory -/ #check "hello, world!" #check 3 #check ℤ #check 3 = 4 #check false #check ℤ = "hi" #check real.sqrt --- --- --- --- --- --- --- --- --- --- --- --- --- --- #eval 1 + 1 #eval real.sqrt 2
8864e5c9f1c69cecef106edba3a954f944b85a80
05b503addd423dd68145d68b8cde5cd595d74365
/src/tactic/lint/default.lean
54231d2e1c3e17ff9bc30f6dfa42354b35a35fcf
[ "Apache-2.0" ]
permissive
aestriplex/mathlib
77513ff2b176d74a3bec114f33b519069788811d
e2fa8b2b1b732d7c25119229e3cdfba8370cb00f
refs/heads/master
1,621,969,960,692
1,586,279,279,000
1,586,279,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,754
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.frontend tactic.lint.simp tactic.lint.type_classes tactic.lint.misc open tactic add_tactic_doc { name := "linting commands", category := doc_category.cmd, decl_names := [`lint_cmd, `lint_mathlib_cmd, `lint_all_cmd, `list_linters], tags := ["linting"], description := "User commands to spot common mistakes in the code * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) The following linters are run by default: 1. `unused_arguments` checks for unused arguments in declarations. 2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma. 3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration. 4. `ge_or_gt` checks whether ≥/> is used in the declaration. 5. `instance_priority` checks that instances that always apply have priority below default. 6. `doc_blame` checks for missing doc strings on definitions and constants. 7. `has_inhabited_instance` checks whether every type has an associated `inhabited` instance. 8. `impossible_instance` checks for instances that can never fire. 9. `incorrect_type_class_argument` checks for arguments in [square brackets] that are not classes. 10. `dangerous_instance` checks for instances that generate type-class problems with metavariables. 11. `fails_quickly` tests that type-class inference ends (relatively) quickly when applied to variables. 12. `has_coe_variable` tests that there are no instances of type `has_coe α t` for a variable `α`. 13. `inhabited_nonempty` checks for `inhabited` instance arguments that should be changed to `nonempty`. 14. `simp_nf` checks that the left-hand side of simp lemmas is in simp-normal form. 15. `simp_var_head` checks that there are no variables as head symbol of left-hand sides of simp lemmas. 16. `simp_comm` checks that no commutativity lemmas (such as `add_comm`) are marked simp. Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. This is not run by default. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output of passing checks. A silent lint will fail if any test fails. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks." } /-- The default linters used in mathlib CI. -/ meta def mathlib_linters : list name := by do ls ← get_checks tt [] ff, let ls := ls.map (λ ⟨n, _⟩, `linter ++ n), exact (reflect ls)
8db00c94099022999148dac6b225896dfe401551
f3a5af2927397cf346ec0e24312bfff077f00425
/src/mynat/definition.lean
4615797071776cdbabb38c8fe88df4f444b94e84
[ "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
846
lean
import tactic.structure_helper import tactic.nat_num_game /- mynat/definition.lean -- definition of mynat. Supplies: constants zero : mynat and one : mynat function S : mynat → mynat notation 0 for zero and 1 for one. The below code will be *invisible to the player* -/ -- definition of "the natural numbers" @[derive decidable_eq] inductive mynat | zero : mynat | succ (n : mynat) : mynat namespace mynat instance : has_zero mynat := ⟨mynat.zero⟩ @[leakage] theorem mynat_zero_eq_zero : mynat.zero = 0 := rfl def one : mynat := succ 0 instance : has_one mynat := ⟨mynat.one⟩ theorem one_eq_succ_zero : 1 = succ 0 := rfl lemma zero_ne_succ (m : mynat) : (0 : mynat) ≠ succ m := λ h, by cases h lemma succ_inj {m n : mynat} (h : succ m = succ n) : m = n := by cases h; refl end mynat attribute [symm] ne.symm
a6aa1f9ee4d7f03dd14bdfa3cef52e8d352ae5c3
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/normal_mono.lean
80ddba688e31b4bc3359a1825ab48a113243f063
[ "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
8,866
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.regular_mono import category_theory.limits.shapes.kernels import category_theory.limits.preserves.basic /-! # Definitions and basic properties of normal monomorphisms and epimorphisms. A normal monomorphism is a morphism that is the kernel of some other morphism. We give the construction `normal_mono → regular_mono` (`category_theory.normal_mono.regular_mono`) as well as the dual construction for normal epimorphisms. We show equivalences reflect normal monomorphisms (`category_theory.equivalence_reflects_normal_mono`), and that the pullback of a normal monomorphism is normal (`category_theory.normal_of_is_pullback_snd_of_normal`). -/ noncomputable theory namespace category_theory open category_theory.limits universes v₁ u₁ u₂ variables {C : Type u₁} [category.{v₁} C] variables {X Y : C} section variables [has_zero_morphisms C] /-- A normal monomorphism is a morphism which is the kernel of some morphism. -/ class normal_mono (f : X ⟶ Y) := (Z : C) (g : Y ⟶ Z) (w : f ≫ g = 0) (is_limit : is_limit (kernel_fork.of_ι f w)) section local attribute [instance] fully_faithful_reflects_limits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal mono, then `f` is a normal mono. -/ def equivalence_reflects_normal_mono {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_mono (F.map f)) : normal_mono f := { Z := F.obj_preimage hf.Z, g := full.preimage (hf.g ≫ (F.obj_obj_preimage_iso hf.Z).inv), w := faithful.map_injective F $ by simp [reassoc_of hf.w], is_limit := reflects_limit.reflects $ is_limit.of_cone_equiv (cones.postcompose_equivalence (comp_nat_iso F : _)) $ is_limit.of_iso_limit (by exact is_limit.of_iso_limit (is_kernel.of_comp_iso _ _ (F.obj_obj_preimage_iso hf.Z) (by simp) hf.is_limit) (of_ι_congr (category.comp_id _).symm)) (iso_of_ι _).symm } end /-- Every normal monomorphism is a regular monomorphism. -/ @[priority 100] instance normal_mono.regular_mono (f : X ⟶ Y) [I : normal_mono f] : regular_mono f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal mono, then any map `k : W ⟶ Y` such that `k ≫ normal_mono.g = 0` induces a morphism `l : W ⟶ X` such that `l ≫ f = k`. -/ def normal_mono.lift' {W : C} (f : X ⟶ Y) [normal_mono f] (k : W ⟶ Y) (h : k ≫ normal_mono.g = 0) : {l : W ⟶ X // l ≫ f = k} := kernel_fork.is_limit.lift' normal_mono.is_limit _ h /-- The second leg of a pullback cone is a normal monomorphism if the right component is too. See also `pullback.snd_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_fst_of_normal` for the flipped version. -/ def normal_of_is_pullback_snd_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_mono h] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono g := { Z := hn.Z, g := k ≫ hn.g, w := by rw [← reassoc_of comm, hn.w, has_zero_morphisms.comp_zero], is_limit := begin letI gr := regular_of_is_pullback_snd_of_regular comm t, have q := (has_zero_morphisms.comp_zero k hn.Z).symm, convert gr.is_limit, dunfold kernel_fork.of_ι fork.of_ι, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pullback cone is a normal monomorphism if the left component is too. See also `pullback.fst_of_mono` for the basic monomorphism version, and `normal_of_is_pullback_snd_of_normal` for the flipped version. -/ def normal_of_is_pullback_fst_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_mono k] (comm : f ≫ h = g ≫ k) (t : is_limit (pullback_cone.mk _ _ comm)) : normal_mono f := normal_of_is_pullback_snd_of_normal comm.symm (pullback_cone.flip_is_limit t) end section variables [has_zero_morphisms C] /-- A normal epimorphism is a morphism which is the cokernel of some morphism. -/ class normal_epi (f : X ⟶ Y) := (W : C) (g : W ⟶ X) (w : g ≫ f = 0) (is_colimit : is_colimit (cokernel_cofork.of_π f w)) section local attribute [instance] fully_faithful_reflects_colimits local attribute [instance] equivalence.ess_surj_of_equivalence /-- If `F` is an equivalence and `F.map f` is a normal epi, then `f` is a normal epi. -/ def equivalence_reflects_normal_epi {D : Type u₂} [category.{v₁} D] [has_zero_morphisms D] (F : C ⥤ D) [is_equivalence F] {X Y : C} {f : X ⟶ Y} (hf : normal_epi (F.map f)) : normal_epi f := { W := F.obj_preimage hf.W, g := full.preimage ((F.obj_obj_preimage_iso hf.W).hom ≫ hf.g), w := faithful.map_injective F $ by simp [hf.w], is_colimit := reflects_colimit.reflects $ is_colimit.of_cocone_equiv (cocones.precompose_equivalence (comp_nat_iso F).symm) $ is_colimit.of_iso_colimit (by exact is_colimit.of_iso_colimit (is_cokernel.of_iso_comp _ _ (F.obj_obj_preimage_iso hf.W).symm (by simp) hf.is_colimit) (of_π_congr (category.id_comp _).symm)) (iso_of_π _).symm } end /-- Every normal epimorphism is a regular epimorphism. -/ @[priority 100] instance normal_epi.regular_epi (f : X ⟶ Y) [I : normal_epi f] : regular_epi f := { left := I.g, right := 0, w := (by simpa using I.w), ..I } /-- If `f` is a normal epi, then every morphism `k : X ⟶ W` satisfying `normal_epi.g ≫ k = 0` induces `l : Y ⟶ W` such that `f ≫ l = k`. -/ def normal_epi.desc' {W : C} (f : X ⟶ Y) [normal_epi f] (k : X ⟶ W) (h : normal_epi.g ≫ k = 0) : {l : Y ⟶ W // f ≫ l = k} := cokernel_cofork.is_colimit.desc' (normal_epi.is_colimit) _ h /-- The second leg of a pushout cocone is a normal epimorphism if the right component is too. See also `pushout.snd_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_fst_of_normal` for the flipped version. -/ def normal_of_is_pushout_snd_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [gn : normal_epi g] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi h := { W := gn.W, g := gn.g ≫ f, w := by rw [category.assoc, comm, reassoc_of gn.w, zero_comp], is_colimit := begin letI hn := regular_of_is_pushout_snd_of_regular comm t, have q := (@zero_comp _ _ _ gn.W _ _ f).symm, convert hn.is_colimit, dunfold cokernel_cofork.of_π cofork.of_π, congr, exact q, exact q, exact q, apply proof_irrel_heq, end } /-- The first leg of a pushout cocone is a normal epimorphism if the left component is too. See also `pushout.fst_of_epi` for the basic epimorphism version, and `normal_of_is_pushout_snd_of_normal` for the flipped version. -/ def normal_of_is_pushout_fst_of_normal {P Q R S : C} {f : P ⟶ Q} {g : P ⟶ R} {h : Q ⟶ S} {k : R ⟶ S} [hn : normal_epi f] (comm : f ≫ h = g ≫ k) (t : is_colimit (pushout_cocone.mk _ _ comm)) : normal_epi k := normal_of_is_pushout_snd_of_normal comm.symm (pushout_cocone.flip_is_colimit t) end open opposite variables [has_zero_morphisms C] /-- A normal mono becomes a normal epi in the opposite category. -/ def normal_epi_of_normal_mono_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) (m : normal_mono f.unop) : normal_epi f := { W := op m.Z, g := m.g.op, w := congr_arg quiver.hom.op m.w, is_colimit := is_colimit.of_π _ _ (λ Z' g' w', (kernel_fork.is_limit.lift' m.is_limit g'.unop (congr_arg quiver.hom.unop w')).1.op) (λ Z' g' w', congr_arg quiver.hom.op (kernel_fork.is_limit.lift' m.is_limit g'.unop (congr_arg quiver.hom.unop w')).2) begin rintros Z' g' w' m' rfl, apply quiver.hom.unop_inj, apply m.is_limit.uniq (kernel_fork.of_ι (m'.unop ≫ f.unop) _) m'.unop, rintro (⟨⟩|⟨⟩); simp, end, } /-- A normal epi becomes a normal mono in the opposite category. -/ def normal_mono_of_normal_epi_unop {X Y : Cᵒᵖ} (f : X ⟶ Y) (m : normal_epi f.unop) : normal_mono f := { Z := op m.W, g := m.g.op, w := congr_arg quiver.hom.op m.w, is_limit := is_limit.of_ι _ _ (λ Z' g' w', (cokernel_cofork.is_colimit.desc' m.is_colimit g'.unop (congr_arg quiver.hom.unop w')).1.op) (λ Z' g' w', congr_arg quiver.hom.op (cokernel_cofork.is_colimit.desc' m.is_colimit g'.unop (congr_arg quiver.hom.unop w')).2) begin rintros Z' g' w' m' rfl, apply quiver.hom.unop_inj, apply m.is_colimit.uniq (cokernel_cofork.of_π (f.unop ≫ m'.unop) _) m'.unop, rintro (⟨⟩|⟨⟩); simp, end, } end category_theory
5f580f349e321d59e500fc59071e6f53e00ea42d
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/root.lean
a28906a1fc14547c4c75abd0b8c3f11943845f9e
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
249
lean
import standard using num variable foo : Prop namespace N1 variable foo : Prop check N1.foo check _root_.foo namespace N2 variable foo : Prop check N1.foo check N1.N2.foo print raw foo print raw _root_.foo end end
ac0b6b5d8ed0569a080b13bec88b37513ab050e2
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed/group/quotient.lean
a8f5f4110438c65ee373ac10cdeccf9071785883
[ "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
21,911
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Riccardo Brasca -/ import analysis.normed.group.hom /-! # Quotients of seminormed groups For any `semi_normed_group M` and any `S : add_subgroup M`, we provide a `semi_normed_group` the group quotient `M ⧸ S`. If `S` is closed, we provide `normed_group (M ⧸ S)` (regardless of whether `M` itself is separated). The two main properties of these structures are the underlying topology is the quotient topology and the projection is a normed group homomorphism which is norm non-increasing (better, it has operator norm exactly one unless `S` is dense in `M`). The corresponding universal property is that every normed group hom defined on `M` which vanishes on `S` descends to a normed group hom defined on `M ⧸ S`. This file also introduces a predicate `is_quotient` characterizing normed group homs that are isomorphic to the canonical projection onto a normed group quotient. ## Main definitions We use `M` and `N` to denote seminormed groups and `S : add_subgroup M`. All the following definitions are in the `add_subgroup` namespace. Hence we can access `add_subgroup.normed_mk S` as `S.normed_mk`. * `semi_normed_group_quotient` : The seminormed group structure on the quotient by an additive subgroup. This is an instance so there is no need to explictly use it. * `normed_group_quotient` : The normed group structure on the quotient by a closed additive subgroup. This is an instance so there is no need to explictly use it. * `normed_mk S` : the normed group hom from `M` to `M ⧸ S`. * `lift S f hf`: implements the universal property of `M ⧸ S`. Here `(f : normed_group_hom M N)`, `(hf : ∀ s ∈ S, f s = 0)` and `lift S f hf : normed_group_hom (M ⧸ S) N`. * `is_quotient`: given `f : normed_group_hom M N`, `is_quotient f` means `N` is isomorphic to a quotient of `M` by a subgroup, with projection `f`. Technically it asserts `f` is surjective and the norm of `f x` is the infimum of the norms of `x + m` for `m` in `f.ker`. ## Main results * `norm_normed_mk` : the operator norm of the projection is `1` if the subspace is not dense. * `is_quotient.norm_lift`: Provided `f : normed_hom M N` satisfies `is_quotient f`, for every `n : N` and positive `ε`, there exists `m` such that `f m = n ∧ ∥m∥ < ∥n∥ + ε`. ## Implementation details For any `semi_normed_group M` and any `S : add_subgroup M` we define a norm on `M ⧸ S` by `∥x∥ = Inf (norm '' {m | mk' S m = x})`. This formula is really an implementation detail, it shouldn't be needed outside of this file setting up the theory. Since `M ⧸ S` is automatically a topological space (as any quotient of a topological space), one needs to be careful while defining the `semi_normed_group` instance to avoid having two different topologies on this quotient. This is not purely a technological issue. Mathematically there is something to prove. The main point is proved in the auxiliary lemma `quotient_nhd_basis` that has no use beyond this verification and states that zero in the quotient admits as basis of neighborhoods in the quotient topology the sets `{x | ∥x∥ < ε}` for positive `ε`. Once this mathematical point it settled, we have two topologies that are propositionaly equal. This is not good enough for the type class system. As usual we ensure *definitional* equality using forgetful inheritance, see Note [forgetful inheritance]. A (semi)-normed group structure includes a uniform space structure which includes a topological space structure, together with propositional fields asserting compatibility conditions. The usual way to define a `semi_normed_group` is to let Lean build a uniform space structure using the provided norm, and then trivially build a proof that the norm and uniform structure are compatible. Here the uniform structure is provided using `topological_add_group.to_uniform_space` which uses the topological structure and the group structure to build the uniform structure. This uniform structure induces the correct topological structure by construction, but the fact that it is compatible with the norm is not obvious; this is where the mathematical content explained in the previous paragraph kicks in. -/ noncomputable theory open quotient_add_group metric set open_locale topological_space nnreal variables {M N : Type*} [semi_normed_group M] [semi_normed_group N] /-- The definition of the norm on the quotient by an additive subgroup. -/ noncomputable instance norm_on_quotient (S : add_subgroup M) : has_norm (M ⧸ S) := { norm := λ x, Inf (norm '' {m | mk' S m = x}) } lemma image_norm_nonempty {S : add_subgroup M} : ∀ x : M ⧸ S, (norm '' {m | mk' S m = x}).nonempty := begin rintro ⟨m⟩, rw set.nonempty_image_iff, use m, change mk' S m = _, refl end lemma bdd_below_image_norm (s : set M) : bdd_below (norm '' s) := begin use 0, rintro _ ⟨x, hx, rfl⟩, apply norm_nonneg end /-- The norm on the quotient satisfies `∥-x∥ = ∥x∥`. -/ lemma quotient_norm_neg {S : add_subgroup M} (x : M ⧸ S) : ∥-x∥ = ∥x∥ := begin suffices : norm '' {m | mk' S m = x} = norm '' {m | mk' S m = -x}, by simp only [this, norm], ext r, split, { rintros ⟨m, rfl : mk' S m = x, rfl⟩, rw ← norm_neg, exact ⟨-m, by simp only [(mk' S).map_neg, set.mem_set_of_eq], rfl⟩ }, { rintros ⟨m, hm : mk' S m = -x, rfl⟩, exact ⟨-m, by simpa [eq_comm] using eq_neg_iff_eq_neg.mp ((mk'_apply _ _).symm.trans hm)⟩ } end lemma quotient_norm_sub_rev {S : add_subgroup M} (x y : M ⧸ S) : ∥x - y∥ = ∥y - x∥ := by rw [show x - y = -(y - x), by abel, quotient_norm_neg] /-- The norm of the projection is smaller or equal to the norm of the original element. -/ lemma quotient_norm_mk_le (S : add_subgroup M) (m : M) : ∥mk' S m∥ ≤ ∥m∥ := begin apply cInf_le, use 0, { rintros _ ⟨n, h, rfl⟩, apply norm_nonneg }, { apply set.mem_image_of_mem, rw set.mem_set_of_eq } end /-- The norm of the projection is smaller or equal to the norm of the original element. -/ lemma quotient_norm_mk_le' (S : add_subgroup M) (m : M) : ∥(m : M ⧸ S)∥ ≤ ∥m∥ := quotient_norm_mk_le S m /-- The norm of the image under the natural morphism to the quotient. -/ lemma quotient_norm_mk_eq (S : add_subgroup M) (m : M) : ∥mk' S m∥ = Inf ((λ x, ∥m + x∥) '' S) := begin change Inf _ = _, congr' 1, ext r, simp_rw [coe_mk', eq_iff_sub_mem], split, { rintros ⟨y, h, rfl⟩, use [y - m, h], simp }, { rintros ⟨y, h, rfl⟩, use m + y, simpa using h }, end /-- The quotient norm is nonnegative. -/ lemma quotient_norm_nonneg (S : add_subgroup M) : ∀ x : M ⧸ S, 0 ≤ ∥x∥ := begin rintros ⟨m⟩, change 0 ≤ ∥mk' S m∥, apply le_cInf (image_norm_nonempty _), rintros _ ⟨n, h, rfl⟩, apply norm_nonneg end /-- The quotient norm is nonnegative. -/ lemma norm_mk_nonneg (S : add_subgroup M) (m : M) : 0 ≤ ∥mk' S m∥ := quotient_norm_nonneg S _ /-- The norm of the image of `m : M` in the quotient by `S` is zero if and only if `m` belongs to the closure of `S`. -/ lemma quotient_norm_eq_zero_iff (S : add_subgroup M) (m : M) : ∥mk' S m∥ = 0 ↔ m ∈ closure (S : set M) := begin have : 0 ≤ ∥mk' S m∥ := norm_mk_nonneg S m, rw [← this.le_iff_eq, quotient_norm_mk_eq, real.Inf_le_iff], simp_rw [zero_add], { calc (∀ ε > (0 : ℝ), ∃ r ∈ (λ x, ∥m + x∥) '' (S : set M), r < ε) ↔ (∀ ε > 0, (∃ x ∈ S, ∥m + x∥ < ε)) : by simp [set.bex_image_iff] ... ↔ ∀ ε > 0, (∃ x ∈ S, ∥m + -x∥ < ε) : _ ... ↔ ∀ ε > 0, (∃ x ∈ S, x ∈ metric.ball m ε) : by simp [dist_eq_norm, ← sub_eq_add_neg, norm_sub_rev] ... ↔ m ∈ closure ↑S : by simp [metric.mem_closure_iff, dist_comm], refine forall₂_congr (λ ε ε_pos, _), rw [← S.exists_neg_mem_iff_exists_mem], simp }, { use 0, rintro _ ⟨x, x_in, rfl⟩, apply norm_nonneg }, rw set.nonempty_image_iff, use [0, S.zero_mem] end /-- For any `x : M ⧸ S` and any `0 < ε`, there is `m : M` such that `mk' S m = x` and `∥m∥ < ∥x∥ + ε`. -/ lemma norm_mk_lt {S : add_subgroup M} (x : M ⧸ S) {ε : ℝ} (hε : 0 < ε) : ∃ (m : M), mk' S m = x ∧ ∥m∥ < ∥x∥ + ε := begin obtain ⟨_, ⟨m : M, H : mk' S m = x, rfl⟩, hnorm : ∥m∥ < ∥x∥ + ε⟩ := real.lt_Inf_add_pos (image_norm_nonempty x) hε, subst H, exact ⟨m, rfl, hnorm⟩, end /-- For any `m : M` and any `0 < ε`, there is `s ∈ S` such that `∥m + s∥ < ∥mk' S m∥ + ε`. -/ lemma norm_mk_lt' (S : add_subgroup M) (m : M) {ε : ℝ} (hε : 0 < ε) : ∃ s ∈ S, ∥m + s∥ < ∥mk' S m∥ + ε := begin obtain ⟨n : M, hn : mk' S n = mk' S m, hn' : ∥n∥ < ∥mk' S m∥ + ε⟩ := norm_mk_lt (quotient_add_group.mk' S m) hε, erw [eq_comm, quotient_add_group.eq] at hn, use [- m + n, hn], rwa [add_neg_cancel_left] end /-- The quotient norm satisfies the triangle inequality. -/ lemma quotient_norm_add_le (S : add_subgroup M) (x y : M ⧸ S) : ∥x + y∥ ≤ ∥x∥ + ∥y∥ := begin refine le_of_forall_pos_le_add (λ ε hε, _), replace hε := half_pos hε, obtain ⟨m, rfl, hm : ∥m∥ < ∥mk' S m∥ + ε / 2⟩ := norm_mk_lt x hε, obtain ⟨n, rfl, hn : ∥n∥ < ∥mk' S n∥ + ε / 2⟩ := norm_mk_lt y hε, calc ∥mk' S m + mk' S n∥ = ∥mk' S (m + n)∥ : by rw (mk' S).map_add ... ≤ ∥m + n∥ : quotient_norm_mk_le S (m + n) ... ≤ ∥m∥ + ∥n∥ : norm_add_le _ _ ... ≤ ∥mk' S m∥ + ∥mk' S n∥ + ε : by linarith end /-- The quotient norm of `0` is `0`. -/ lemma norm_mk_zero (S : add_subgroup M) : ∥(0 : M ⧸ S)∥ = 0 := begin erw quotient_norm_eq_zero_iff, exact subset_closure S.zero_mem end /-- If `(m : M)` has norm equal to `0` in `M ⧸ S` for a closed subgroup `S` of `M`, then `m ∈ S`. -/ lemma norm_zero_eq_zero (S : add_subgroup M) (hS : is_closed (S : set M)) (m : M) (h : ∥mk' S m∥ = 0) : m ∈ S := by rwa [quotient_norm_eq_zero_iff, hS.closure_eq] at h lemma quotient_nhd_basis (S : add_subgroup M) : (𝓝 (0 : M ⧸ S)).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {x | ∥x∥ < ε}) := ⟨begin intros U, split, { intros U_in, rw ← (mk' S).map_zero at U_in, have := preimage_nhds_coinduced U_in, rcases metric.mem_nhds_iff.mp this with ⟨ε, ε_pos, H⟩, use [ε/2, half_pos ε_pos], intros x x_in, dsimp at x_in, rcases norm_mk_lt x (half_pos ε_pos) with ⟨y, rfl, ry⟩, apply H, rw ball_zero_eq, dsimp, linarith }, { rintros ⟨ε, ε_pos, h⟩, have : (mk' S) '' (ball (0 : M) ε) ⊆ {x | ∥x∥ < ε}, { rintros - ⟨x, x_in, rfl⟩, rw mem_ball_zero_iff at x_in, exact lt_of_le_of_lt (quotient_norm_mk_le S x) x_in }, apply filter.mem_of_superset _ (set.subset.trans this h), clear h U this, apply is_open.mem_nhds, { change is_open ((mk' S) ⁻¹' _), erw quotient_add_group.preimage_image_coe, apply is_open_Union, rintros ⟨s, s_in⟩, exact (continuous_add_right s).is_open_preimage _ is_open_ball }, { exact ⟨(0 : M), mem_ball_self ε_pos, (mk' S).map_zero⟩ } }, end⟩ /-- The seminormed group structure on the quotient by an additive subgroup. -/ noncomputable instance add_subgroup.semi_normed_group_quotient (S : add_subgroup M) : semi_normed_group (M ⧸ S) := { dist := λ x y, ∥x - y∥, dist_self := λ x, by simp only [norm_mk_zero, sub_self], dist_comm := quotient_norm_sub_rev, dist_triangle := λ x y z, begin unfold dist, have : x - z = (x - y) + (y - z) := by abel, rw this, exact quotient_norm_add_le S (x - y) (y - z) end, dist_eq := λ x y, rfl, to_uniform_space := topological_add_group.to_uniform_space (M ⧸ S), uniformity_dist := begin rw uniformity_eq_comap_nhds_zero', have := (quotient_nhd_basis S).comap (λ (p : (M ⧸ S) × M ⧸ S), p.2 - p.1), apply this.eq_of_same_basis, have : ∀ ε : ℝ, (λ (p : (M ⧸ S) × M ⧸ S), p.snd - p.fst) ⁻¹' {x | ∥x∥ < ε} = {p : (M ⧸ S) × M ⧸ S | ∥p.fst - p.snd∥ < ε}, { intro ε, ext x, dsimp, rw quotient_norm_sub_rev }, rw funext this, refine filter.has_basis_binfi_principal _ set.nonempty_Ioi, rintros ε (ε_pos : 0 < ε) η (η_pos : 0 < η), refine ⟨min ε η, lt_min ε_pos η_pos, _, _⟩, { suffices : ∀ (a b : M ⧸ S), ∥a - b∥ < ε → ∥a - b∥ < η → ∥a - b∥ < ε, by simpa, exact λ a b h h', h }, { simp } end } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) : (quotient.topological_space : topological_space $ M ⧸ S) = S.semi_normed_group_quotient.to_uniform_space.to_topological_space := rfl /-- The quotient in the category of normed groups. -/ noncomputable instance add_subgroup.normed_group_quotient (S : add_subgroup M) [hS : is_closed (S : set M)] : normed_group (M ⧸ S) := { eq_of_dist_eq_zero := begin rintros ⟨m⟩ ⟨m'⟩ (h : ∥mk' S m - mk' S m'∥ = 0), erw [← (mk' S).map_sub, quotient_norm_eq_zero_iff, hS.closure_eq, ← quotient_add_group.eq_iff_sub_mem] at h, exact h end, .. add_subgroup.semi_normed_group_quotient S } -- This is a sanity check left here on purpose to ensure that potential refactors won't destroy -- this important property. example (S : add_subgroup M) [is_closed (S : set M)] : S.semi_normed_group_quotient = normed_group.to_semi_normed_group := rfl namespace add_subgroup open normed_group_hom /-- The morphism from a seminormed group to the quotient by a subgroup. -/ noncomputable def normed_mk (S : add_subgroup M) : normed_group_hom M (M ⧸ S) := { bound' := ⟨1, λ m, by simpa [one_mul] using quotient_norm_mk_le _ m⟩, .. quotient_add_group.mk' S } /-- `S.normed_mk` agrees with `quotient_add_group.mk' S`. -/ @[simp] lemma normed_mk.apply (S : add_subgroup M) (m : M) : normed_mk S m = quotient_add_group.mk' S m := rfl /-- `S.normed_mk` is surjective. -/ lemma surjective_normed_mk (S : add_subgroup M) : function.surjective (normed_mk S) := surjective_quot_mk _ /-- The kernel of `S.normed_mk` is `S`. -/ lemma ker_normed_mk (S : add_subgroup M) : S.normed_mk.ker = S := quotient_add_group.ker_mk _ /-- The operator norm of the projection is at most `1`. -/ lemma norm_normed_mk_le (S : add_subgroup M) : ∥S.normed_mk∥ ≤ 1 := normed_group_hom.op_norm_le_bound _ zero_le_one (λ m, by simp [quotient_norm_mk_le']) /-- The operator norm of the projection is `1` if the subspace is not dense. -/ lemma norm_normed_mk (S : add_subgroup M) (h : (S.topological_closure : set M) ≠ univ) : ∥S.normed_mk∥ = 1 := begin obtain ⟨x, hx⟩ := set.nonempty_compl.2 h, let y := S.normed_mk x, have hy : ∥y∥ ≠ 0, { intro h0, exact set.not_mem_of_mem_compl hx ((quotient_norm_eq_zero_iff S x).1 h0) }, refine le_antisymm (norm_normed_mk_le S) (le_of_forall_pos_le_add (λ ε hε, _)), suffices : 1 ≤ ∥S.normed_mk∥ + min ε ((1 : ℝ)/2), { exact le_add_of_le_add_left this (min_le_left ε ((1 : ℝ)/2)) }, have hδ := sub_pos.mpr (lt_of_le_of_lt (min_le_right ε ((1 : ℝ)/2)) one_half_lt_one), have hδpos : 0 < min ε ((1 : ℝ)/2) := lt_min hε one_half_pos, have hδnorm := mul_pos (div_pos hδpos hδ) (lt_of_le_of_ne (norm_nonneg y) hy.symm), obtain ⟨m, hm, hlt⟩ := norm_mk_lt y hδnorm, have hrw : ∥y∥ + min ε (1 / 2) / (1 - min ε (1 / 2)) * ∥y∥ = ∥y∥ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring, rw [hrw] at hlt, have hm0 : ∥m∥ ≠ 0, { intro h0, have hnorm := quotient_norm_mk_le S m, rw [h0, hm] at hnorm, replace hnorm := le_antisymm hnorm (norm_nonneg _), simpa [hnorm] using hy }, replace hlt := (div_lt_div_right (lt_of_le_of_ne (norm_nonneg m) hm0.symm)).2 hlt, simp only [hm0, div_self, ne.def, not_false_iff] at hlt, have hrw₁ : ∥y∥ * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) / ∥m∥ = (∥y∥ / ∥m∥) * (1 + min ε (1 / 2) / (1 - min ε (1 / 2))) := by ring, rw [hrw₁] at hlt, replace hlt := (inv_pos_lt_iff_one_lt_mul (lt_trans (div_pos hδpos hδ) (lt_one_add _))).2 hlt, suffices : ∥S.normed_mk∥ ≥ 1 - min ε (1 / 2), { exact sub_le_iff_le_add.mp this }, calc ∥S.normed_mk∥ ≥ ∥(S.normed_mk) m∥ / ∥m∥ : ratio_le_op_norm S.normed_mk m ... = ∥y∥ / ∥m∥ : by rw [normed_mk.apply, hm] ... ≥ (1 + min ε (1 / 2) / (1 - min ε (1 / 2)))⁻¹ : le_of_lt hlt ... = 1 - min ε (1 / 2) : by field_simp [(ne_of_lt hδ).symm] end /-- The operator norm of the projection is `0` if the subspace is dense. -/ lemma norm_trivial_quotient_mk (S : add_subgroup M) (h : (S.topological_closure : set M) = set.univ) : ∥S.normed_mk∥ = 0 := begin refine le_antisymm (op_norm_le_bound _ le_rfl (λ x, _)) (norm_nonneg _), have hker : x ∈ (S.normed_mk).ker.topological_closure, { rw [S.ker_normed_mk], exact set.mem_of_eq_of_mem h trivial }, rw [ker_normed_mk] at hker, simp only [(quotient_norm_eq_zero_iff S x).mpr hker, normed_mk.apply, zero_mul], end end add_subgroup namespace normed_group_hom /-- `is_quotient f`, for `f : M ⟶ N` means that `N` is isomorphic to the quotient of `M` by the kernel of `f`. -/ structure is_quotient (f : normed_group_hom M N) : Prop := (surjective : function.surjective f) (norm : ∀ x, ∥f x∥ = Inf ((λ m, ∥x + m∥) '' f.ker)) /-- Given `f : normed_group_hom M N` such that `f s = 0` for all `s ∈ S`, where, `S : add_subgroup M` is closed, the induced morphism `normed_group_hom (M ⧸ S) N`. -/ noncomputable def lift {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) : normed_group_hom (M ⧸ S) N := { bound' := begin obtain ⟨c : ℝ, hcpos : (0 : ℝ) < c, hc : ∀ x, ∥f x∥ ≤ c * ∥x∥⟩ := f.bound, refine ⟨c, λ mbar, le_of_forall_pos_le_add (λ ε hε, _)⟩, obtain ⟨m : M, rfl : mk' S m = mbar, hmnorm : ∥m∥ < ∥mk' S m∥ + ε/c⟩ := norm_mk_lt mbar (div_pos hε hcpos), calc ∥f m∥ ≤ c * ∥m∥ : hc m ... ≤ c*(∥mk' S m∥ + ε/c) : ((mul_lt_mul_left hcpos).mpr hmnorm).le ... = c * ∥mk' S m∥ + ε : by rw [mul_add, mul_div_cancel' _ hcpos.ne.symm] end, .. quotient_add_group.lift S f.to_add_monoid_hom hf } lemma lift_mk {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (m : M) : lift S f hf (S.normed_mk m) = f m := rfl lemma lift_unique {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (g : normed_group_hom (M ⧸ S) N) : g.comp (S.normed_mk) = f → g = lift S f hf := begin intro h, ext, rcases add_subgroup.surjective_normed_mk _ x with ⟨x,rfl⟩, change (g.comp (S.normed_mk) x) = _, simpa only [h] end /-- `S.normed_mk` satisfies `is_quotient`. -/ lemma is_quotient_quotient (S : add_subgroup M) : is_quotient (S.normed_mk) := ⟨S.surjective_normed_mk, λ m, by simpa [S.ker_normed_mk] using quotient_norm_mk_eq _ m⟩ lemma is_quotient.norm_lift {f : normed_group_hom M N} (hquot : is_quotient f) {ε : ℝ} (hε : 0 < ε) (n : N) : ∃ (m : M), f m = n ∧ ∥m∥ < ∥n∥ + ε := begin obtain ⟨m, rfl⟩ := hquot.surjective n, have nonemp : ((λ m', ∥m + m'∥) '' f.ker).nonempty, { rw set.nonempty_image_iff, exact ⟨0, f.ker.zero_mem⟩ }, rcases real.lt_Inf_add_pos nonemp hε with ⟨_, ⟨⟨x, hx, rfl⟩, H : ∥m + x∥ < Inf ((λ (m' : M), ∥m + m'∥) '' f.ker) + ε⟩⟩, exact ⟨m+x, by rw [f.map_add,(normed_group_hom.mem_ker f x).mp hx, add_zero], by rwa hquot.norm⟩, end lemma is_quotient.norm_le {f : normed_group_hom M N} (hquot : is_quotient f) (m : M) : ∥f m∥ ≤ ∥m∥ := begin rw hquot.norm, apply cInf_le, { use 0, rintros _ ⟨m', hm', rfl⟩, apply norm_nonneg }, { exact ⟨0, f.ker.zero_mem, by simp⟩ } end lemma lift_norm_le {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) {c : ℝ≥0} (fb : ∥f∥ ≤ c) : ∥lift S f hf∥ ≤ c := begin apply op_norm_le_bound _ c.coe_nonneg, intros x, by_cases hc : c = 0, { simp only [hc, nnreal.coe_zero, zero_mul] at fb ⊢, obtain ⟨x, rfl⟩ := surjective_quot_mk _ x, show ∥f x∥ ≤ 0, calc ∥f x∥ ≤ 0 * ∥x∥ : f.le_of_op_norm_le fb x ... = 0 : zero_mul _ }, { replace hc : 0 < c := pos_iff_ne_zero.mpr hc, apply le_of_forall_pos_le_add, intros ε hε, have aux : 0 < (ε / c) := div_pos hε hc, obtain ⟨x, rfl, Hx⟩ : ∃ x', S.normed_mk x' = x ∧ ∥x'∥ < ∥x∥ + (ε / c) := (is_quotient_quotient _).norm_lift aux _, rw lift_mk, calc ∥f x∥ ≤ c * ∥x∥ : f.le_of_op_norm_le fb x ... ≤ c * (∥S.normed_mk x∥ + ε / c) : (mul_le_mul_left _).mpr Hx.le ... = c * _ + ε : _, { exact_mod_cast hc }, { rw [mul_add, mul_div_cancel'], exact_mod_cast hc.ne' } }, end lemma lift_norm_noninc {N : Type*} [semi_normed_group N] (S : add_subgroup M) (f : normed_group_hom M N) (hf : ∀ s ∈ S, f s = 0) (fb : f.norm_noninc) : (lift S f hf).norm_noninc := λ x, begin have fb' : ∥f∥ ≤ (1 : ℝ≥0) := norm_noninc.norm_noninc_iff_norm_le_one.mp fb, simpa using le_of_op_norm_le _ (f.lift_norm_le _ _ fb') _, end end normed_group_hom
77f6078b8f9acb3e27be4f2465e19219319d96dc
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/function/continuous_map_dense.lean
80df4cea7918fdc68cc889be2a64a6bfa16a12b1
[ "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
10,073
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import measure_theory.measure.regular import measure_theory.function.simple_func_dense_lp import topology.urysohns_lemma import measure_theory.function.l1_space /-! # Approximation in Lᵖ by continuous functions This file proves that bounded continuous functions are dense in `Lp E p μ`, for `1 ≤ p < ∞`, if the domain `α` of the functions is a normal topological space and the measure `μ` is weakly regular. The result is presented in several versions: * `measure_theory.Lp.bounded_continuous_function_dense`: The subgroup `measure_theory.Lp.bounded_continuous_function` of `Lp E p μ`, the additive subgroup of `Lp E p μ` consisting of equivalence classes containing a continuous representative, is dense in `Lp E p μ`. * `bounded_continuous_function.to_Lp_dense_range`: For finite-measure `μ`, the continuous linear map `bounded_continuous_function.to_Lp p μ 𝕜` from `α →ᵇ E` to `Lp E p μ` has dense range. * `continuous_map.to_Lp_dense_range`: For compact `α` and finite-measure `μ`, the continuous linear map `continuous_map.to_Lp p μ 𝕜` from `C(α, E)` to `Lp E p μ` has dense range. Note that for `p = ∞` this result is not true: the characteristic function of the set `[0, ∞)` in `ℝ` cannot be continuously approximated in `L∞`. The proof is in three steps. First, since simple functions are dense in `Lp`, it suffices to prove the result for a scalar multiple of a characteristic function of a measurable set `s`. Secondly, since the measure `μ` is weakly regular, the set `s` can be approximated above by an open set and below by a closed set. Finally, since the domain `α` is normal, we use Urysohn's lemma to find a continuous function interpolating between these two sets. ## Related results Are you looking for a result on "directional" approximation (above or below with respect to an order) of functions whose codomain is `ℝ≥0∞` or `ℝ`, by semicontinuous functions? See the Vitali-Carathéodory theorem, in the file `measure_theory.vitali_caratheodory`. -/ open_locale ennreal nnreal topological_space bounded_continuous_function open measure_theory topological_space continuous_map variables {α : Type*} [measurable_space α] [topological_space α] [normal_space α] [borel_space α] variables (E : Type*) [normed_group E] [second_countable_topology_either α E] variables {p : ℝ≥0∞} [_i : fact (1 ≤ p)] (hp : p ≠ ∞) (μ : measure α) include _i hp namespace measure_theory.Lp variables [normed_space ℝ E] /-- A function in `Lp` can be approximated in `Lp` by continuous functions. -/ lemma bounded_continuous_function_dense [μ.weakly_regular] : (bounded_continuous_function E p μ).topological_closure = ⊤ := begin have hp₀ : 0 < p := lt_of_lt_of_le ennreal.zero_lt_one _i.elim, have hp₀' : 0 ≤ 1 / p.to_real := div_nonneg zero_le_one ennreal.to_real_nonneg, have hp₀'' : 0 < p.to_real, { simpa [← ennreal.to_real_lt_to_real ennreal.zero_ne_top hp] using hp₀ }, -- It suffices to prove that scalar multiples of the indicator function of a finite-measure -- measurable set can be approximated by continuous functions suffices : ∀ (c : E) {s : set α} (hs : measurable_set s) (hμs : μ s < ⊤), (Lp.simple_func.indicator_const p hs hμs.ne c : Lp E p μ) ∈ (bounded_continuous_function E p μ).topological_closure, { rw add_subgroup.eq_top_iff', refine Lp.induction hp _ _ _ _, { exact this }, { exact λ f g hf hg hfg', add_subgroup.add_mem _ }, { exact add_subgroup.is_closed_topological_closure _ } }, -- Let `s` be a finite-measure measurable set, let's approximate `c` times its indicator function intros c s hs hsμ, refine mem_closure_iff_frequently.mpr _, rw metric.nhds_basis_closed_ball.frequently_iff, intros ε hε, -- A little bit of pre-emptive work, to find `η : ℝ≥0` which will be a margin small enough for -- our purposes obtain ⟨η, hη_pos, hη_le⟩ : ∃ η, 0 < η ∧ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ) ≤ ε, { have : filter.tendsto (λ x : ℝ≥0, ∥bit0 (∥c∥)∥₊ * (2 * x) ^ (1 / p.to_real)) (𝓝 0) (𝓝 0), { have : filter.tendsto (λ x : ℝ≥0, 2 * x) (𝓝 0) (𝓝 (2 * 0)) := filter.tendsto_id.const_mul 2, convert ((nnreal.continuous_at_rpow_const (or.inr hp₀')).tendsto.comp this).const_mul _, simp [hp₀''.ne'] }, let ε' : ℝ≥0 := ⟨ε, hε.le⟩, have hε' : 0 < ε' := by exact_mod_cast hε, obtain ⟨δ, hδ, hδε'⟩ := nnreal.nhds_zero_basis.eventually_iff.mp (eventually_le_of_tendsto_lt hε' this), obtain ⟨η, hη, hηδ⟩ := exists_between hδ, refine ⟨η, hη, _⟩, exact_mod_cast hδε' hηδ }, have hη_pos' : (0 : ℝ≥0∞) < η := ennreal.coe_pos.2 hη_pos, -- Use the regularity of the measure to `η`-approximate `s` by an open superset and a closed -- subset obtain ⟨u, su, u_open, μu⟩ : ∃ u ⊇ s, is_open u ∧ μ u < μ s + ↑η, { refine s.exists_is_open_lt_of_lt _ _, simpa using ennreal.add_lt_add_left hsμ.ne hη_pos' }, obtain ⟨F, Fs, F_closed, μF⟩ : ∃ F ⊆ s, is_closed F ∧ μ s < μ F + ↑η := hs.exists_is_closed_lt_add hsμ.ne hη_pos'.ne', have : disjoint uᶜ F := (Fs.trans su).disjoint_compl_left, have h_μ_sdiff : μ (u \ F) ≤ 2 * η, { have hFμ : μ F < ⊤ := (measure_mono Fs).trans_lt hsμ, refine ennreal.le_of_add_le_add_left hFμ.ne _, have : μ u < μ F + ↑η + ↑η, from μu.trans (ennreal.add_lt_add_right ennreal.coe_ne_top μF), convert this.le using 1, { rw [add_comm, ← measure_union, set.diff_union_of_subset (Fs.trans su)], exacts [disjoint_sdiff_self_left, F_closed.measurable_set] }, have : (2:ℝ≥0∞) * η = η + η := by simpa using add_mul (1:ℝ≥0∞) 1 η, rw this, abel }, -- Apply Urysohn's lemma to get a continuous approximation to the characteristic function of -- the set `s` obtain ⟨g, hgu, hgF, hg_range⟩ := exists_continuous_zero_one_of_closed u_open.is_closed_compl F_closed this, -- Multiply this by `c` to get a continuous approximation to the function `f`; the key point is -- that this is pointwise bounded by the indicator of the set `u \ F` have g_norm : ∀ x, ∥g x∥ = g x := λ x, by rw [real.norm_eq_abs, abs_of_nonneg (hg_range x).1], have gc_bd : ∀ x, ∥g x • c - s.indicator (λ x, c) x∥ ≤ ∥(u \ F).indicator (λ x, bit0 ∥c∥) x∥, { intros x, by_cases hu : x ∈ u, { rw ← set.diff_union_of_subset (Fs.trans su) at hu, cases hu with hFu hF, { refine (norm_sub_le _ _).trans _, refine (add_le_add_left (norm_indicator_le_norm_self (λ x, c) x) _).trans _, have h₀ : g x * ∥c∥ + ∥c∥ ≤ 2 * ∥c∥, { nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] }, have h₁ : (2:ℝ) * ∥c∥ = bit0 (∥c∥) := by simpa using add_mul (1:ℝ) 1 (∥c∥), simp [hFu, norm_smul, h₀, ← h₁, g_norm x] }, { simp [hgF hF, Fs hF] } }, { have : x ∉ s := λ h, hu (su h), simp [hgu hu, this] } }, -- The rest is basically just `ennreal`-arithmetic have gc_snorm : snorm ((λ x, g x • c) - s.indicator (λ x, c)) p μ ≤ (↑(∥bit0 (∥c∥)∥₊ * (2 * η) ^ (1 / p.to_real)) : ℝ≥0∞), { refine (snorm_mono_ae (filter.eventually_of_forall gc_bd)).trans _, rw snorm_indicator_const (u_open.sdiff F_closed).measurable_set hp₀.ne' hp, push_cast [← ennreal.coe_rpow_of_nonneg _ hp₀'], exact ennreal.mul_left_mono (ennreal.monotone_rpow_of_nonneg hp₀' h_μ_sdiff) }, have gc_cont : continuous (λ x, g x • c) := g.continuous.smul continuous_const, have gc_mem_ℒp : mem_ℒp (λ x, g x • c) p μ, { have : mem_ℒp ((λ x, g x • c) - s.indicator (λ x, c)) p μ := ⟨gc_cont.ae_strongly_measurable.sub (strongly_measurable_const.indicator hs) .ae_strongly_measurable, gc_snorm.trans_lt ennreal.coe_lt_top⟩, simpa using this.add (mem_ℒp_indicator_const p hs c (or.inr hsμ.ne)) }, refine ⟨gc_mem_ℒp.to_Lp _, _, _⟩, { rw mem_closed_ball_iff_norm, refine le_trans _ hη_le, rw [simple_func.coe_indicator_const, indicator_const_Lp, ← mem_ℒp.to_Lp_sub, Lp.norm_to_Lp], exact ennreal.to_real_le_coe_of_le_coe gc_snorm }, { rw [set_like.mem_coe, mem_bounded_continuous_function_iff], refine ⟨bounded_continuous_function.of_normed_group _ gc_cont (∥c∥) _, rfl⟩, intros x, have h₀ : g x * ∥c∥ ≤ ∥c∥, { nlinarith [(hg_range x).1, (hg_range x).2, norm_nonneg c] }, simp [norm_smul, g_norm x, h₀] }, end end measure_theory.Lp variables (𝕜 : Type*) [normed_field 𝕜] [normed_algebra ℝ 𝕜] [normed_space 𝕜 E] namespace bounded_continuous_function lemma to_Lp_dense_range [μ.weakly_regular] [is_finite_measure μ] : dense_range ⇑(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] Lp E p μ) := begin haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E, rw dense_range_iff_closure_range, suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤, { exact congr_arg coe this }, simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp], end end bounded_continuous_function namespace continuous_map lemma to_Lp_dense_range [compact_space α] [μ.weakly_regular] [is_finite_measure μ] : dense_range ⇑(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] Lp E p μ) := begin haveI : normed_space ℝ E := restrict_scalars.normed_space ℝ 𝕜 E, rw dense_range_iff_closure_range, suffices : (to_Lp p μ 𝕜 : _ →L[𝕜] Lp E p μ).range.to_add_subgroup.topological_closure = ⊤, { exact congr_arg coe this }, simp [range_to_Lp p μ, measure_theory.Lp.bounded_continuous_function_dense E hp] end end continuous_map
f1c34f3c3aa0f11ed12ea5925a97ae3a5b95e401
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/real/nnreal.lean
0474c82c98b21d092a36ca2bf328eeee79362f45
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
24,483
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin Nonnegative real numbers. -/ import data.real.basic order.lattice algebra.field noncomputable theory open_locale classical /-- Nonnegative real numbers. -/ def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ instance : can_lift ℝ nnreal := { coe := coe, cond := λ r, r ≥ 0, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r := max_eq_left hr lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r := le_max_left r 0 lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2 @[elim_cast, simp, nolint simp_nf] -- takes a crazy amount of time simplify lhs theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩ instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩ instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩ instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩ instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩ instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩ instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩ instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩ instance : has_bot ℝ≥0 := ⟨0⟩ instance : inhabited ℝ≥0 := ⟨0⟩ @[simp] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl @[simp] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl @[simp, move_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl @[simp, move_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl @[simp, move_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, move_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl @[simp] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _) @[simp, elim_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := @nnreal.eq_iff r 0 @[elim_cast] lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by simp instance : comm_semiring ℝ≥0 := begin refine { zero := 0, add := (+), one := 1, mul := (*), ..}; { intros; apply nnreal.eq; simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib, add_comm_monoid.zero, add_comm, add_left_comm] } end instance : is_semiring_hom (coe : ℝ≥0 → ℝ) := by refine_struct {..}; intros; refl @[move_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := is_monoid_hom.map_pow coe r n @[move_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := eq.symm $ l.sum_hom coe @[move_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := eq.symm $ l.prod_hom coe @[move_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := eq.symm $ s.sum_hom coe @[move_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := eq.symm $ s.prod_hom coe @[move_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.sum f) = s.sum (λa, (f a : ℝ)) := eq.symm $ s.sum_hom coe @[move_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(s.prod f) = s.prod (λa, (f a : ℝ)) := eq.symm $ s.prod_hom coe @[move_cast] lemma smul_coe (r : ℝ≥0) (n : ℕ) : ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) := is_add_monoid_hom.map_smul coe r n @[simp, squash_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := is_semiring_hom.map_nat_cast coe n instance : decidable_linear_order ℝ≥0 := decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance) @[elim_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[elim_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[elim_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl @[elim_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext.symm protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma of_real_mono : monotone nnreal.of_real := λ x y h, max_le_max h (le_refl 0) @[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r := nnreal.eq $ max_eq_left r.2 /-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ protected def gi : galois_insertion nnreal.of_real coe := galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono le_coe_of_real (λ _, of_real_coe) instance : order_bot ℝ≥0 := { bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order } instance : canonically_ordered_monoid ℝ≥0 := { add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c, lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c, le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩, iff.intro (assume h : a ≤ b, ⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩, nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩) (assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc), ..nnreal.comm_semiring, ..nnreal.order_bot, ..nnreal.decidable_linear_order } instance : distrib_lattice ℝ≥0 := by apply_instance instance : semilattice_inf_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : semilattice_sup_bot ℝ≥0 := { .. nnreal.order_bot, .. nnreal.distrib_lattice } instance : linear_ordered_semiring ℝ≥0 := { add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h), add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h), le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c, mul_le_mul_of_nonneg_left := assume a b c, @mul_le_mul_of_nonneg_left ℝ _ a b c, mul_le_mul_of_nonneg_right := assume a b c, @mul_le_mul_of_nonneg_right ℝ _ a b c, mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c, mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c, zero_lt_one := @zero_lt_one ℝ _, .. nnreal.decidable_linear_order, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : canonically_ordered_comm_semiring ℝ≥0 := { zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h, mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp, .. nnreal.linear_ordered_semiring, .. nnreal.canonically_ordered_monoid, .. nnreal.comm_semiring } instance : densely_ordered ℝ≥0 := ⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in ⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩ instance : no_top_order ℝ≥0 := ⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩ lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ instance : has_Sup ℝ≥0 := ⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Sup_empty] }, rcases h with ⟨⟨b, hb⟩, hbs⟩, by_cases h' : bdd_above s, { exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb }, { rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] } end⟩⟩ instance : has_Inf ℝ≥0 := ⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s), begin cases s.eq_empty_or_nonempty with h h, { simp [h, set.image_empty, real.Inf_empty] }, exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2) end⟩⟩ lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl instance : conditionally_complete_linear_order_bot ℝ≥0 := { Sup := Sup, Inf := Inf, le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha), cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has), le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb, cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl, decidable_le := begin assume x y, apply classical.dec end, .. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order, .. nnreal.order_bot } instance : archimedean nnreal := ⟨ assume x y pos_y, let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in ⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩ lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end lemma lt_iff_exists_rat_btwn (a b : nnreal) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := begin cases le_total b c with h h, { simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] }, { simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] }, end lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : r * s.sup f = s.sup (λa, r * f a) := begin refine s.induction_on _ _, { simp [bot_eq_zero] }, { assume a s has ih, simp [has, ih, mul_sup], } end section of_real @[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2 @[simp] lemma of_real_zero : nnreal.of_real 0 = 0 := by simp [nnreal.of_real]; refl @[simp] lemma of_real_one : nnreal.of_real 1 = 1 := by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r := by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 := by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r)) lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 := of_real_eq_zero.2 @[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) : nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp] @[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} : nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p := by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl] lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans (and_iff_left h) lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : nnreal.of_real r < nnreal.of_real p ↔ r < p := of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p := nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg] lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) := (of_real_add hr hp).symm lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p := nnreal.of_real_mono h lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp] lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha] lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] }, { rw [of_real_eq_zero.2 h], split, intro, have := not_lt_of_le (zero_le r), contradiction, intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction } end end of_real section mul lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, have := max_eq_left (mul_nonneg hp hq), simpa [nnreal.of_real, hp, hq, max_eq_left] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] } end @[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := by { simp only [ne.def, ← nnreal.eq_iff], simp [h₁, h₂] } end mul section sub lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 := nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h @[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r @[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r := by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe] lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r := of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r := assume hr hp, begin cases le_total r p, { rwa [sub_eq_zero h] }, { rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp } end @[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p := match le_total p r with | or.inl h := by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add] | or.inr h := have r ≤ p + q, from le_add_right h, by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm] end @[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r := sub_le_iff_le_add.2 $ le_add_right $ le_refl r lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p := nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _) lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p := by rw [add_comm, add_sub_cancel] @[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a := nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel] lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r := by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h, sub_sub_cancel, nnreal.of_real_coe] lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q := begin split, { assume H, have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) := nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))), rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H }, { assume H, have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H), rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] } end end sub section inv lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl @[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero @[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 := by rw [← nnreal.eq_iff, nnreal.coe_inv, nnreal.coe_zero, inv_eq_zero, ← nnreal.coe_zero, nnreal.eq_iff] @[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r := by simp [zero_lt_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := mul_pos hr (inv_pos.2 hp) @[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one @[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one] protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _ protected lemma inv_pow' {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n := nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm } @[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 := nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h @[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 := by rw [mul_comm, inv_mul_cancel h] @[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 := mul_inv_cancel h @[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r := by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one] @[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r := by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one] @[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p := by rw [mul_comm, div_mul_cancel h] @[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq inv_inv' @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm] lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa [div_def] using half_lt_self zero_ne_one.symm lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c := begin rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul], exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc) end lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n := by rw [div_def, mul_pow, ← nnreal.inv_pow', ← div_def] @[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c := by rw [div_def, div_def, mul_assoc] @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a := by rw [div_def, one_mul] @[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b := by { rw [div_def, div_def], ac_refl } @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ := one_mul a⁻¹ lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a := by { rw ← nnreal.eq_iff, simp [one_div_div] } lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) := by rw [div_def, div_def, one_mul] @[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b := by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] } @[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) := by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] } @[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff], simp only [nnreal.coe_div, nnreal.coe_mul], exact div_eq_div_iff (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero @[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb end inv section pow theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 := begin rw ← nnreal.eq_iff, rw [← nnreal.eq_iff, coe_pow] at h, exact pow_eq_zero h end @[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h end pow end nnreal
8d942ebf72f91eab96cfc8b734b53a82131bd5ea
a7dd8b83f933e72c40845fd168dde330f050b1c9
/src/category_theory/instances/Top/default.lean
59d1ec93de610dc9ec46a3e3a59dac3e2e969dad
[ "Apache-2.0" ]
permissive
NeilStrickland/mathlib
10420e92ee5cb7aba1163c9a01dea2f04652ed67
3efbd6f6dff0fb9b0946849b43b39948560a1ffe
refs/heads/master
1,589,043,046,346
1,558,938,706,000
1,558,938,706,000
181,285,984
0
0
Apache-2.0
1,568,941,848,000
1,555,233,833,000
Lean
UTF-8
Lean
false
false
397
lean
-- Copyright (c) 2019 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.instances.Top.basic import category_theory.instances.Top.limits import category_theory.instances.Top.epi_mono import category_theory.instances.Top.open_nhds import category_theory.instances.Top.presheaf_of_functions
c3c68c525e511275bb36a00ffae56959fdb8ada8
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/data/nat/parity.lean
5c2f98aecdaeb597b915ccd0e5ba08cdfb67ce5b
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
2,714
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The `even` predicate on the natural numbers. -/ import .modeq namespace nat @[simp] theorem mod_two_ne_one {n : nat} : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero {n : nat} : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] def even (n : nat) : Prop := 2 ∣ n theorem even_iff {n : nat} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ instance : decidable_pred even := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm run_cmd mk_simp_attr `parity_simps @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : nat) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : nat} : even (m + n) ↔ (even m ↔ even n) := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end @[simp] theorem not_even_bit1 (n : nat) : ¬ even (bit1 n) := by simp [bit1] with parity_simps @[parity_simps] theorem even_sub {m n : nat} (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] }, by_cases h : even n; simp [h] end @[parity_simps] theorem even_succ {n : nat} : even (succ n) ↔ ¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul {m n : nat} : even (m * n) ↔ even m ∨ even n := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_pow {m n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, pow_succ, even_mul], tauto } -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : nat) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat
650ff347abd0ba53d1db3b462282a6889848f3ba
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/src/over.lean
401dd205093f494573e5cff01cb878e4de3923f3
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
3,680
lean
import category_theory.comma import category_theory.adjunction.basic import category_theory.limits.shapes import category_theory.epi_mono import category_theory.limits.over import cartesian_closed import pullbacks import comma import to_mathlib /-! # Properties of the over category. We can interpret the forgetful functor `forget : over B ⥤ C` as dependent sum, (written `Σ_B`) and when C has binary products, it has a right adjoint `B*` given by `A ↦ (π₁ : B × A → B)`, denoted `star` in Lean. Furthermore, if the original category C has pullbacks and terminal object (i.e. all finite limits), `B*` has a right adjoint iff `B` is exponentiable in `C`. This right adjoint is written `Π_B` and is interpreted as dependent product. Given `f : A ⟶ B` in `C/B`, the iterated slice `(C/B)/f` is isomorphic to `C/A`. -/ namespace category_theory open category limits universes v u variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 section adjunction variable (B : C) variable [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash @[reducible] def star : C ⥤ over B := { obj := λ A, @over.mk _ _ _ (B ⨯ A) limits.prod.fst, map := λ X Y f, over.hom_mk (limits.prod.map (𝟙 _) f) (by simp) } def forget_adj_star : over.forget ⊣ star B := adjunction.mk_of_hom_equiv { hom_equiv := λ g A, { to_fun := λ f, over.hom_mk (prod.lift g.hom f), inv_fun := λ k, k.left ≫ limits.prod.snd, left_inv := by tidy, right_inv := by tidy } } variables [has_terminal.{v} C] [has_pullbacks.{v} C] def Pi_obj [exponentiable B] (f : over B) : C := pullback (post B f.hom) (point_at_hom (𝟙 B)) private def pi_obj.equiv [exponentiable B] (X : C) (Y : over B) : ((star B).obj X ⟶ Y) ≃ (X ⟶ Pi_obj B Y) := { to_fun := λ f, pullback.lift (exp_transpose.to_fun f.left) (terminal.from _) (begin rw ← exp_transpose_natural_right, erw ← exp_transpose_natural_left, tidy end), inv_fun := λ g, begin apply over.hom_mk _ _, apply (exp_transpose.inv_fun (g ≫ pullback.fst)), dsimp, apply function.injective_of_left_inverse exp_transpose.left_inv, rw exp_transpose_natural_right, rw exp_transpose.right_inv, rw assoc, rw pullback.condition, have : g ≫ pullback.snd = terminal.from X, apply subsingleton.elim, rw ← assoc, rw this, erw ← exp_transpose_natural_left, apply function.injective_of_left_inverse exp_transpose.right_inv, rw exp_transpose.left_inv, rw exp_transpose.left_inv, simp end, left_inv := λ f, begin apply over.over_morphism.ext, simp, rw exp_transpose.left_inv end, right_inv := λ g, begin apply pullback.hom_ext, simp, rw exp_transpose.right_inv, apply subsingleton.elim end } private lemma pi_obj.natural_equiv [exponentiable B] (X' X : C) (Y : over B) (f : X' ⟶ X) (g : (star B).obj X ⟶ Y) : (pi_obj.equiv B X' Y).to_fun ((star B).map f ≫ g) = f ≫ (pi_obj.equiv B X Y).to_fun g := begin apply pullback.hom_ext, simp [pi_obj.equiv], rw ← exp_transpose_natural_left, apply subsingleton.elim end def Pi_functor [exponentiable B] : over B ⥤ C := @adjunction.right_adjoint_of_equiv _ _ _ _ (star B) (Pi_obj B) (pi_obj.equiv B) (pi_obj.natural_equiv B) def star_adj_pi_of_exponentiable [exponentiable B] : star B ⊣ Pi_functor B := adjunction.adjunction_of_equiv_right _ _ def star_is_left_adj_of_exponentiable [exponentiable B] : is_left_adjoint (star B) := ⟨Pi_functor B, star_adj_pi_of_exponentiable B⟩ def exponentiable_of_star_is_left_adj (h : is_left_adjoint (star B)) : exponentiable B := ⟨⟨star B ⋙ h.right, adjunction.comp _ _ h.adj (forget_adj_star B)⟩⟩ end adjunction end category_theory
9b9395d9cc59189976458919aed60a5d036ac125
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/finset.lean
8ed3d1baa68317957aa19937761d9494ff94e5cc
[ "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
116,002
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding algebra.order_functions data.multiset data.sigma.basic data.set.lattice tactic.monotonicity tactic.apply open multiset subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (↑s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[elim_cast] lemma coe_nonempty {s : finset α} : (↑s:set α).nonempty ↔ s.nonempty := iff.rfl lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨λ ⟨a, ha⟩, ne_empty_of_mem ha, nonempty_of_ne_empty⟩ theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl /-! ### singleton -/ /-- `finset.singleton a` is the set `{a}` containing `a` and nothing else. This differs from `singleton a` in that it does not require a `decidable_eq` instance for `α`. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = finset.singleton a ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = finset.singleton a) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : singleton a ⊆ s ↔ a ∈ s := set.singleton_subset_iff /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : {a} = ι a := rfl theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ @[simp] theorem insert_singleton_self_eq' {a : α} : insert a (ι a) = ι a := insert_singleton_self_eq _ /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := by ext; simp theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := by ext; simp only [and_or_distrib_left, mem_union, classical.not_and_distrib, mem_sdiff, mem_inter] @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, empty_union] @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := by simp only [sdiff_inter_distrib_right, sdiff_self, union_empty] @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := ext.2 (by simp) @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) theorem sdiff_subset_self {s₁ s₂ : finset α} : s₁ \ s₂ ⊆ s₁ := suffices s₁ \ s₂ ⊆ s₁ \ ∅, by simpa [sdiff_empty] using this, sdiff_subset_sdiff (subset.refl _) (empty_subset _) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := ext.2 $ λ a, by simp only [mem_union, mem_sdiff, or_iff_not_imp_left, imp_and_distrib, and_iff_left id] @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_sdiff_self_eq_union, union_comm] lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := by rw [union_sdiff_self_eq_union, union_sdiff_self_eq_union, union_comm] lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := by rw [subset_iff, ext]; simp @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := by { rw sdiff_eq_empty_iff_subset, exact empty_subset _ } lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem ↑s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem ↑s h end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := by simp [subset_iff, mem_sdiff] {contextual := tt} end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[elim_cast] lemma piecewise_coe [∀j, decidable (j ∈ (↑s : set α))] : (↑s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : function.update f i v = piecewise (singleton i) (λj, v) f := begin ext j, by_cases h : j = i, { rw [h], simp }, { simp [h] } end end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} : s.filter (λ i, i ∈ t) = s ∩ t := ext' $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter {s t : finset α} : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter {s t : finset α} : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else (filter p s) := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff,sdiff_subset_self], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{ x ∈ s | p x }` for `finset.filter s p`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{ x ∈ s | p x }` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{ x ∈ s | p x }` to `finset.filter s p`. If `p` happens to be decidable, the simp-lemma `filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter(eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, insert_empty_eq_singleton, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] /-- Associate to an embedding `f` from `α` to `β` the embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin classical, split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { refine ⟨∅, set.empty_subset _, _⟩, convert finset.image_empty _ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi], congr end end image /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end end lemma card_le_of_inj_on {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from function.injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)⟩, subtype.ext.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card /-! ### bind -/ section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind {a : α} : (singleton a).bind t = t a := begin classical, have : (insert a ∅ : finset α).bind t = t a, from bind_insert.trans (union_empty _), convert this end theorem bind_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bind f ∩ t = s.bind (λ x, f x ∩ t) := begin ext x, simp only [mem_bind, mem_inter], tauto end theorem inter_bind (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bind f = s.bind (λ x, t ∩ f x) := by rw [inter_comm, bind_inter]; simp [inter_comm] theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind /-! ### prod-/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma /-! ### pi -/ section pi variables {δ : α → Type*} [decidable_eq α] /-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`. Note that the elements of `s.pi t` are only partially defined, on `s`. -/ def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ /-- The empty dependent product function, defined on the emptyset. The assumption `a ∈ ∅` is never satisfied. -/ def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h /-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`, equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted `s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a` anyway. -/ def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end lemma pi_subset {s : finset α} (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) : s.pi t₁ ⊆ s.pi t₂ := λ g hg, mem_pi.2 $ λ a ha, h a ha (mem_pi.mp hg a ha) end pi /-! ### powerset -/ section powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] lemma powerset_empty [decidable_eq α] : finset.powerset (∅ : finset α) = {∅} := rfl @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by { apply mt _ h, apply mem_powerset.1 ht } lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := begin ext t, simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff], by_cases h : a ∈ t, { split, { exact λH, or.inr ⟨_, H, insert_erase h⟩ }, { intros H, cases H, { exact subset.trans (erase_subset a t) H }, { rcases H with ⟨u, hu⟩, rw ← hu.2, exact subset.trans (erase_insert_subset a u) hu.1 } } }, { have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t, by simp [ne.symm (ne_insert_of_not_mem _ _ h)], simp [finset.erase_eq_of_not_mem h, this] } end end powerset section powerset_len /-- Given an integer `n` and a finset `s`, then `powerset_len n s` is the finset of subsets of `s` of cardinality `n`.-/ def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation a * b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha section order variables [decidable_linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff end order end fold /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton' {b : β} : (singleton b).sup f = f b := sup_singleton lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (@is_total.total _ (≤) _ x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton' {b : β} : (singleton b).inf f = f b := inf_singleton lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := inf_singleton' lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (@is_total.total _ (≤) _ x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /-! ### max and min of finite sets -/ section max_min variables [decidable_linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem theorem min_singleton {a : α} : finset.min {a} = some a := min_insert @[simp] theorem min_singleton' {a : α} : finset.min (singleton a) = some a := min_singleton theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption lemma exists_min (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := begin cases min_of_nonempty (h.image f) with y hy, rcases mem_image.mp (mem_of_min hy) with ⟨x, hx, rfl⟩, exact ⟨x, hx, λ x' hx', min_le_of_mem (mem_image_of_mem f hx') hy⟩ end /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' H ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' H < s.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le s H i H1, have H6 := le_max' s H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le s H j H2, have H6 := le_max' s H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end max_min /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ end sort section sort_linear_order variables [decidable_linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min' (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le H _ this } end lemma sorted_last_eq_max' (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' H _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact list.nth_le_of_sorted_of_le (s.sort_sorted (≤)) (nat.le_pred_of_lt i_lt) }, end /-- Given a finset `s` of cardinal `k` in a linear order `α`, the map `mono_of_fin s h` is the increasing bijection between `fin k` and `s` as an `α`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ def mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : α := have A : (i : ℕ) < (s.sort (≤)).length, by simpa [h] using i.2, (s.sort (≤)).nth_le i A lemma mono_of_fin_strict_mono (s : finset α) {k : ℕ} (h : s.card = k) : strict_mono (s.mono_of_fin h) := begin assume i j hij, exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij end lemma bij_on_mono_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.bij_on (s.mono_of_fin h) set.univ ↑s := begin have A : ∀ j, j ∈ s ↔ j ∈ (s.sort (≤)) := λ j, by simp, apply set.bij_on.mk, { assume i hi, simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A], exact list.nth_le_mem _ _ _ }, { exact ((mono_of_fin_strict_mono s h).injective).inj_on _ }, { assume x hx, simp only [mem_coe, A] at hx, obtain ⟨i, il, hi⟩ : ∃ (i : ℕ) (h : i < (s.sort (≤)).length), (s.sort (≤)).nth_le i h = x := list.nth_le_of_mem hx, simp [h] at il, exact ⟨⟨i, il⟩, set.mem_univ _, hi⟩ } end /-- The bijection `mono_of_fin s h` sends `0` to the minimum of `s`. -/ lemma mono_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hs : s.nonempty) (hz : 0 < k) : mono_of_fin s h ⟨0, hz⟩ = s.min' hs := begin apply le_antisymm, { have : min' s hs ∈ s := min'_mem s hs, rcases (bij_on_mono_of_fin s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact zero_le a.val }, { have : mono_of_fin s h ⟨0, hz⟩ ∈ s := (bij_on_mono_of_fin s h).maps_to (set.mem_univ _), exact min'_le s hs _ this } end /-- The bijection `mono_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma mono_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hs : s.nonempty) (hz : 0 < k) : mono_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' hs := begin have h'' : k - 1 < k := buffer.lt_aux_2 hz, apply le_antisymm, { have : mono_of_fin s h ⟨k-1, h''⟩ ∈ s := (bij_on_mono_of_fin s h).maps_to (set.mem_univ _), exact le_max' s hs _ this }, { have : max' s hs ∈ s := max'_mem s hs, rcases (bij_on_mono_of_fin s h).surj_on this with ⟨a, _, ha⟩, rw ← ha, apply (mono_of_fin_strict_mono s h).monotone, exact le_pred_of_lt a.2}, end /-- Any increasing bijection between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. For a statement assuming only that `f` maps `univ` to `s`, see `mono_of_fin_unique'`.-/ lemma mono_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hbij : set.bij_on f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin ext i, rcases i with ⟨i, hi⟩, induction i using nat.strong_induction_on with i IH, rcases lt_trichotomy (f ⟨i, hi⟩) (mono_of_fin s h ⟨i, hi⟩) with H|H|H, { have A : f ⟨i, hi⟩ ∈ ↑s := hbij.maps_to (set.mem_univ _), rcases (bij_on_mono_of_fin s h).surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := (mono_of_fin_strict_mono s h).lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j.1 ji (lt_trans ji hi), rw fin.ext_iff }, rw ← this at hj, exact (ne_of_lt (hmono ji) hj).elim }, { exact H }, { have A : mono_of_fin s h ⟨i, hi⟩ ∈ ↑s := (bij_on_mono_of_fin s h).maps_to (set.mem_univ _), rcases hbij.surj_on A with ⟨j, _, hj⟩, rw ← hj at H, have ji : j < ⟨i, hi⟩ := hmono.lt_iff_lt.1 H, have : f j = mono_of_fin s h j, by { convert IH j.1 ji (lt_trans ji hi), rw fin.ext_iff }, rw this at hj, exact (ne_of_lt (mono_of_fin_strict_mono s h ji) hj).elim } end /-- Given a finset `s` of cardinal `k` in a linear order `α`, the equiv `mono_equiv_of_fin s h` is the increasing bijection between `fin k` and `s` as an `s`-valued map. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃ {x // x ∈ s} := (s.bij_on_mono_of_fin h).equiv _ end sort_linear_order /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma pi_disjoint_of_disjoint {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} [decidable_eq (Πa∈s, δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) : disjoint (s.pi t₁) (s.pi t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha) $ congr_fun (congr_fun eq₁₂ a) ha lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } end disjoint instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp 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 theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] end decidable_linear_order /-! ### intervals -/ /- Ico (a closed open interval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty (n : ℕ) : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff theorem subset_iff {m₁ n₁ m₂ n₂ : ℕ} (hmn : m₁ < n₁) : Ico m₁ n₁ ⊆ Ico m₂ n₂ ↔ (m₂ ≤ m₁ ∧ n₁ ≤ n₂) := begin simp only [subset_iff, mem], refine ⟨λ h, ⟨_, _⟩, _⟩, { exact (h ⟨le_refl _, hmn⟩).1 }, { refine le_of_pred_lt (@h (pred n₁) ⟨le_pred_of_lt hmn, pred_lt _⟩).2, exact ne_of_gt (lt_of_le_of_lt (nat.zero_le m₁) hmn) }, { rintros ⟨hm, hn⟩ k ⟨hmk, hkn⟩, exact ⟨le_trans hm hmk, lt_of_lt_of_le hkn hn⟩ } end protected theorem subset {m₁ n₁ m₂ n₂ : ℕ} (hmm : m₂ ≤ m₁) (hnn : n₁ ≤ n₂) : Ico m₁ n₁ ⊆ Ico m₂ n₂ := begin simp only [finset.subset_iff, Ico.mem], assume x hx, exact ⟨le_trans hmm hx.1, lt_of_lt_of_le hx.2 hnn⟩ end lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end lemma disjoint_consecutive (n m l : ℕ) : disjoint (Ico n m) (Ico m l) := le_of_eq $ inter_consecutive n m l @[simp] theorem succ_singleton (n : ℕ) : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem insert_succ_bot {n m : ℕ} (h : n < m) : insert n (Ico (n + 1) m) = Ico n m := by rw [eq_comm, ← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.Ico.not_mem_top lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m := eq_of_veq $ multiset.Ico.filter_lt_of_top_le hml lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ := eq_of_veq $ multiset.Ico.filter_lt_of_le_bot hln lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l := eq_of_veq $ multiset.Ico.filter_lt_of_ge hlm @[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m := eq_of_veq $ multiset.Ico.filter_le_of_le_bot hln lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ := eq_of_veq $ multiset.Ico.filter_le_of_top_le hml lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m := eq_of_veq $ multiset.Ico.filter_le_of_le hnl @[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_le n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico lemma range_eq_Ico (n : ℕ) : finset.range n = finset.Ico 0 n := by { ext i, simp } -- TODO We don't yet attempt to reproduce the entire interface for `Ico` for `Ico_ℤ`. /-- `Ico_ℤ l u` is the set of integers `l ≤ k < u`. -/ def Ico_ℤ (l u : ℤ) : finset ℤ := (finset.range (u - l).to_nat).map { to_fun := λ n, n + l, inj := λ n m h, by simpa using h } @[simp] lemma Ico_ℤ.mem {n m l : ℤ} : l ∈ Ico_ℤ n m ↔ n ≤ l ∧ l < m := begin dsimp [Ico_ℤ], simp only [int.lt_to_nat, exists_prop, mem_range, add_comm, function.embedding.coe_fn_mk, mem_map], split, { rintro ⟨a, ⟨h, rfl⟩⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨h₁, h₂⟩, use (l - n).to_nat, split; simp [h₁, h₂], } end @[simp] lemma Ico_ℤ.card (l u : ℤ) : (Ico_ℤ l u).card = (u - l).to_nat := by simp [Ico_ℤ] end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list section lattice variables {ι : Sort*} [complete_lattice α] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := begin classical, exact le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end end lattice namespace set variables {ι : Sort*} lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset s end set namespace finset namespace nat /-- The antidiagonal of a natural number `n` is the finset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : finset (ℕ × ℕ) := (multiset.nat.antidiagonal n).to_finset /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, multiset.mem_to_finset, multiset.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by simpa using list.to_finset_card_of_nodup (list.nat.nodup_antidiagonal n) /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := by { rw [antidiagonal, multiset.nat.antidiagonal_zero], refl } end nat end finset namespace finset /-! ### bUnion -/ variables [decidable_eq α] @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton theorem supr_union {α} [complete_lattice α] {β} [decidable_eq β] {f : β → α} {s t : finset β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg _ $ funext $ λ x, by { convert supr_or, rw finset.mem_union, rw finset.mem_union, refl, refl } ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq lemma bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union @[simp] lemma bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw insert_eq, simp only [bUnion_union, finset.bUnion_singleton] end end finset
15fd98fbbbbf252a158c86573e534131a93242b1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/function/jacobian.lean
c36c5707b59b6fb4754e0423a7a7ad568c0e3abc
[ "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
68,583
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.covering.besicovitch_vector_space import measure_theory.measure.haar_lebesgue import analysis.normed_space.pointwise import measure_theory.covering.differentiation import measure_theory.constructions.polish /-! # Change of variables in higher-dimensional integrals Let `μ` be a Lebesgue measure on a finite-dimensional real vector space `E`. Let `f : E → E` be a function which is injective and differentiable on a measurable set `s`, with derivative `f'`. Then we prove that `f '' s` is measurable, and its measure is given by the formula `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ` (where `(f' x).det` is almost everywhere measurable, but not Borel-measurable in general). This formula is proved in `lintegral_abs_det_fderiv_eq_add_haar_image`. We deduce the change of variables formula for the Lebesgue and Bochner integrals, in `lintegral_image_eq_lintegral_abs_det_fderiv_mul` and `integral_image_eq_integral_abs_det_fderiv_smul` respectively. ## Main results * `add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero`: if `f` is differentiable on a set `s` with zero measure, then `f '' s` also has zero measure. * `add_haar_image_eq_zero_of_det_fderiv_within_eq_zero`: if `f` is differentiable on a set `s`, and its derivative is never invertible, then `f '' s` has zero measure (a version of Sard's lemma). * `ae_measurable_fderiv_within`: if `f` is differentiable on a measurable set `s`, then `f'` is almost everywhere measurable on `s`. For the next statements, `s` is a measurable set and `f` is differentiable on `s` (with a derivative `f'`) and injective on `s`. * `measurable_image_of_fderiv_within`: the image `f '' s` is measurable. * `measurable_embedding_of_fderiv_within`: the function `s.restrict f` is a measurable embedding. * `lintegral_abs_det_fderiv_eq_add_haar_image`: the image measure is given by `μ (f '' s) = ∫⁻ x in s, |(f' x).det| ∂μ`. * `lintegral_image_eq_lintegral_abs_det_fderiv_mul`: for `g : E → ℝ≥0∞`, one has `∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ`. * `integral_image_eq_integral_abs_det_fderiv_smul`: for `g : E → F`, one has `∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ`. * `integrable_on_image_iff_integrable_on_abs_det_fderiv_smul`: for `g : E → F`, the function `g` is integrable on `f '' s` if and only if `|(f' x).det| • g (f x))` is integrable on `s`. ## Implementation Typical versions of these results in the literature have much stronger assumptions: `s` would typically be open, and the derivative `f' x` would depend continuously on `x` and be invertible everywhere, to have the local inverse theorem at our disposal. The proof strategy under our weaker assumptions is more involved. We follow [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2]. The first remark is that, if `f` is sufficiently well approximated by a linear map `A` on a set `s`, then `f` expands the volume of `s` by at least `A.det - ε` and at most `A.det + ε`, where the closeness condition depends on `A` in a non-explicit way (see `add_haar_image_le_mul_of_det_lt` and `mul_le_add_haar_image_of_lt_det`). This fact holds for balls by a simple inclusion argument, and follows for general sets using the Besicovitch covering theorem to cover the set by balls with measures adding up essentially to `μ s`. When `f` is differentiable on `s`, one may partition `s` into countably many subsets `s ∩ t n` (where `t n` is measurable), on each of which `f` is well approximated by a linear map, so that the above results apply. See `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, which follows from the pointwise differentiability (in a non-completely trivial way, as one should ensure a form of uniformity on the sets of the partition). Combining the above two results would give the conclusion, except for two difficulties: it is not obvious why `f '' s` and `f'` should be measurable, which prevents us from using countable additivity for the measure and the integral. It turns out that `f '' s` is indeed measurable, and that `f'` is almost everywhere measurable, which is enough to recover countable additivity. The measurability of `f '' s` follows from the deep Lusin-Souslin theorem ensuring that, in a Polish space, a continuous injective image of a measurable set is measurable. The key point to check the almost everywhere measurability of `f'` is that, if `f` is approximated up to `δ` by a linear map on a set `s`, then `f'` is within `δ` of `A` on a full measure subset of `s` (namely, its density points). With the above approximation argument, it follows that `f'` is the almost everywhere limit of a sequence of measurable functions (which are constant on the pieces of the good discretization), and is therefore almost everywhere measurable. ## Tags Change of variables in integrals ## References [Fremlin, *Measure Theory* (volume 2)][fremlin_vol2] -/ open measure_theory measure_theory.measure metric filter set finite_dimensional asymptotics topological_space open_locale nnreal ennreal topological_space pointwise variables {E F : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] [normed_add_comm_group F] [normed_space ℝ F] {s : set E} {f : E → E} {f' : E → E →L[ℝ] E} /-! ### Decomposition lemmas We state lemmas ensuring that a differentiable function can be approximated, on countably many measurable pieces, by linear maps (with a prescribed precision depending on the linear map). -/ /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may cover `s` with countably many closed sets `t n` on which `f` is well approximated by linear maps `A n`. -/ lemma exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), (∀ n, is_closed (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin /- Choose countably many linear maps `f' z`. For every such map, if `f` has a derivative at `x` close enough to `f' z`, then `f y - f x` is well approximated by `f' z (y - x)` for `y` close enough to `x`, say on a ball of radius `r` (or even `u n` for some `n`, where `u` is a fixed sequence tending to `0`). Let `M n z` be the points where this happens. Then this set is relatively closed inside `s`, and moreover in every closed ball of radius `u n / 3` inside it the map is well approximated by `f' z`. Using countably many closed balls to split `M n z` into small diameter subsets `K n z p`, one obtains the desired sets `t q` after reindexing. -/ -- exclude the trivial case where `s` is empty rcases eq_empty_or_nonempty s with rfl|hs, { refine ⟨λ n, ∅, λ n, 0, _, _, _, _⟩; simp }, -- we will use countably many linear maps. Select these from all the derivatives since the -- space of linear maps is second-countable obtain ⟨T, T_count, hT⟩ : ∃ T : set s, T.countable ∧ (⋃ x ∈ T, ball (f' (x : E)) (r (f' x))) = ⋃ (x : s), ball (f' x) (r (f' x)) := topological_space.is_open_Union_countable _ (λ x, is_open_ball), -- fix a sequence `u` of positive reals tending to zero. obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), -- `M n z` is the set of points `x` such that `f y - f x` is close to `f' z (y - x)` for `y` -- in the ball of radius `u n` around `x`. let M : ℕ → T → set E := λ n z, {x | x ∈ s ∧ ∀ y ∈ s ∩ ball x (u n), ∥f y - f x - f' z (y - x)∥ ≤ r (f' z) * ∥y - x∥}, -- As `f` is differentiable everywhere on `s`, the sets `M n z` cover `s` by design. have s_subset : ∀ x ∈ s, ∃ (n : ℕ) (z : T), x ∈ M n z, { assume x xs, obtain ⟨z, zT, hz⟩ : ∃ z ∈ T, f' x ∈ ball (f' (z : E)) (r (f' z)), { have : f' x ∈ ⋃ (z ∈ T), ball (f' (z : E)) (r (f' z)), { rw hT, refine mem_Union.2 ⟨⟨x, xs⟩, _⟩, simpa only [mem_ball, subtype.coe_mk, dist_self] using (rpos (f' x)).bot_lt }, rwa mem_Union₂ at this }, obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ), 0 < ε ∧ ∥f' x - f' z∥ + ε ≤ r (f' z), { refine ⟨r (f' z) - ∥f' x - f' z∥, _, le_of_eq (by abel)⟩, simpa only [sub_pos] using mem_ball_iff_norm.mp hz }, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ℝ) (H : 0 < δ), ball x δ ∩ s ⊆ {y | ∥f y - f x - (f' x) (y - x)∥ ≤ ε * ∥y - x∥} := metric.mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), obtain ⟨n, hn⟩ : ∃ n, u n < δ := ((tendsto_order.1 u_lim).2 _ δpos).exists, refine ⟨n, ⟨z, zT⟩, ⟨xs, _⟩⟩, assume y hy, calc ∥f y - f x - (f' z) (y - x)∥ = ∥(f y - f x - (f' x) (y - x)) + (f' x - f' z) (y - x)∥ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel, end ... ≤ ∥f y - f x - (f' x) (y - x)∥ + ∥(f' x - f' z) (y - x)∥ : norm_add_le _ _ ... ≤ ε * ∥y - x∥ + ∥f' x - f' z∥ * ∥y - x∥ : begin refine add_le_add (hδ _) (continuous_linear_map.le_op_norm _ _), rw inter_comm, exact inter_subset_inter_right _ (ball_subset_ball hn.le) hy, end ... ≤ r (f' z) * ∥y - x∥ : begin rw [← add_mul, add_comm], exact mul_le_mul_of_nonneg_right hε (norm_nonneg _), end }, -- the sets `M n z` are relatively closed in `s`, as all the conditions defining it are clearly -- closed have closure_M_subset : ∀ n z, s ∩ closure (M n z) ⊆ M n z, { rintros n z x ⟨xs, hx⟩, refine ⟨xs, λ y hy, _⟩, obtain ⟨a, aM, a_lim⟩ : ∃ (a : ℕ → E), (∀ k, a k ∈ M n z) ∧ tendsto a at_top (𝓝 x) := mem_closure_iff_seq_limit.1 hx, have L1 : tendsto (λ (k : ℕ), ∥f y - f (a k) - (f' z) (y - a k)∥) at_top (𝓝 ∥f y - f x - (f' z) (y - x)∥), { apply tendsto.norm, have L : tendsto (λ k, f (a k)) at_top (𝓝 (f x)), { apply (hf' x xs).continuous_within_at.tendsto.comp, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ a_lim, exact eventually_of_forall (λ k, (aM k).1) }, apply tendsto.sub (tendsto_const_nhds.sub L), exact ((f' z).continuous.tendsto _).comp (tendsto_const_nhds.sub a_lim) }, have L2 : tendsto (λ (k : ℕ), (r (f' z) : ℝ) * ∥y - a k∥) at_top (𝓝 (r (f' z) * ∥y - x∥)) := (tendsto_const_nhds.sub a_lim).norm.const_mul _, have I : ∀ᶠ k in at_top, ∥f y - f (a k) - (f' z) (y - a k)∥ ≤ r (f' z) * ∥y - a k∥, { have L : tendsto (λ k, dist y (a k)) at_top (𝓝 (dist y x)) := tendsto_const_nhds.dist a_lim, filter_upwards [(tendsto_order.1 L).2 _ hy.2], assume k hk, exact (aM k).2 y ⟨hy.1, hk⟩ }, exact le_of_tendsto_of_tendsto L1 L2 I }, -- choose a dense sequence `d p` rcases topological_space.exists_dense_seq E with ⟨d, hd⟩, -- split `M n z` into subsets `K n z p` of small diameters by intersecting with the ball -- `closed_ball (d p) (u n / 3)`. let K : ℕ → T → ℕ → set E := λ n z p, closure (M n z) ∩ closed_ball (d p) (u n / 3), -- on the sets `K n z p`, the map `f` is well approximated by `f' z` by design. have K_approx : ∀ n (z : T) p, approximates_linear_on f (f' z) (s ∩ K n z p) (r (f' z)), { assume n z p x hx y hy, have yM : y ∈ M n z := closure_M_subset _ _ ⟨hy.1, hy.2.1⟩, refine yM.2 _ ⟨hx.1, _⟩, calc dist x y ≤ dist x (d p) + dist y (d p) : dist_triangle_right _ _ _ ... ≤ u n / 3 + u n / 3 : add_le_add hx.2.2 hy.2.2 ... < u n : by linarith [u_pos n] }, -- the sets `K n z p` are also closed, again by design. have K_closed : ∀ n (z : T) p, is_closed (K n z p) := λ n z p, is_closed_closure.inter is_closed_ball, -- reindex the sets `K n z p`, to let them only depend on an integer parameter `q`. obtain ⟨F, hF⟩ : ∃ F : ℕ → ℕ × T × ℕ, function.surjective F, { haveI : encodable T := T_count.to_encodable, haveI : nonempty T, { unfreezingI { rcases eq_empty_or_nonempty T with rfl|hT }, { rcases hs with ⟨x, xs⟩, rcases s_subset x xs with ⟨n, z, hnz⟩, exact false.elim z.2 }, { exact nonempty_coe_sort.2 hT } }, inhabit (ℕ × T × ℕ), exact ⟨_, encodable.surjective_decode_iget _⟩ }, -- these sets `t q = K n z p` will do refine ⟨λ q, K (F q).1 (F q).2.1 (F q).2.2, λ q, f' (F q).2.1, λ n, K_closed _ _ _, λ x xs, _, λ q, K_approx _ _ _, λ h's q, ⟨(F q).2.1, (F q).2.1.1.2, rfl⟩⟩, -- the only fact that needs further checking is that they cover `s`. -- we already know that any point `x ∈ s` belongs to a set `M n z`. obtain ⟨n, z, hnz⟩ : ∃ (n : ℕ) (z : T), x ∈ M n z := s_subset x xs, -- by density, it also belongs to a ball `closed_ball (d p) (u n / 3)`. obtain ⟨p, hp⟩ : ∃ (p : ℕ), x ∈ closed_ball (d p) (u n / 3), { have : set.nonempty (ball x (u n / 3)), { simp only [nonempty_ball], linarith [u_pos n] }, obtain ⟨p, hp⟩ : ∃ (p : ℕ), d p ∈ ball x (u n / 3) := hd.exists_mem_open is_open_ball this, exact ⟨p, (mem_ball'.1 hp).le⟩ }, -- choose `q` for which `t q = K n z p`. obtain ⟨q, hq⟩ : ∃ q, F q = (n, z, p) := hF _, -- then `x` belongs to `t q`. apply mem_Union.2 ⟨q, _⟩, simp only [hq, subset_closure hnz, hp, mem_inter_eq, and_self], end variables [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] /-- Assume that a function `f` has a derivative at every point of a set `s`. Then one may partition `s` into countably many disjoint relatively measurable sets (i.e., intersections of `s` with measurable sets `t n`) on which `f` is well approximated by linear maps `A n`. -/ lemma exists_partition_approximates_linear_on_of_has_fderiv_within_at [second_countable_topology F] (f : E → F) (s : set E) (f' : E → E →L[ℝ] F) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (r : (E →L[ℝ] F) → ℝ≥0) (rpos : ∀ A, r A ≠ 0) : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] F)), pairwise (disjoint on t) ∧ (∀ n, measurable_set (t n)) ∧ (s ⊆ ⋃ n, t n) ∧ (∀ n, approximates_linear_on f (A n) (s ∩ t n) (r (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := begin rcases exists_closed_cover_approximates_linear_on_of_has_fderiv_within_at f s f' hf' r rpos with ⟨t, A, t_closed, st, t_approx, ht⟩, refine ⟨disjointed t, A, disjoint_disjointed _, measurable_set.disjointed (λ n, (t_closed n).measurable_set), _, _, ht⟩, { rw Union_disjointed, exact st }, { assume n, exact (t_approx n).mono_set (inter_subset_inter_right _ (disjointed_subset _ _)) }, end namespace measure_theory /-! ### Local lemmas We check that a function which is well enough approximated by a linear map expands the volume essentially like this linear map, and that its derivative (if it exists) is almost everywhere close to the approximating linear map. -/ /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at most `m` for any `m > det A`. -/ lemma add_haar_image_le_mul_of_det_lt (A : E →L[ℝ] E) {m : ℝ≥0} (hm : ennreal.of_real (|A.det|) < m) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), μ (f '' s) ≤ m * μ s := begin apply nhds_within_le_nhds, let d := ennreal.of_real (|A.det|), -- construct a small neighborhood of `A '' (closed_ball 0 1)` with measure comparable to -- the determinant of `A`. obtain ⟨ε, hε, εpos⟩ : ∃ (ε : ℝ), μ (closed_ball 0 ε + A '' (closed_ball 0 1)) < m * μ (closed_ball 0 1) ∧ 0 < ε, { have HC : is_compact (A '' closed_ball 0 1) := (proper_space.is_compact_closed_ball _ _).image A.continuous, have L0 : tendsto (λ ε, μ (cthickening ε (A '' (closed_ball 0 1)))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply tendsto.mono_left _ nhds_within_le_nhds, exact tendsto_measure_cthickening_of_is_compact HC }, have L1 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (μ (A '' (closed_ball 0 1)))), { apply L0.congr' _, filter_upwards [self_mem_nhds_within] with r hr, rw [←HC.add_closed_ball_zero (le_of_lt hr), add_comm] }, have L2 : tendsto (λ ε, μ (closed_ball 0 ε + A '' (closed_ball 0 1))) (𝓝[>] 0) (𝓝 (d * μ (closed_ball 0 1))), { convert L1, exact (add_haar_image_continuous_linear_map _ _ _).symm }, have I : d * μ (closed_ball 0 1) < m * μ (closed_ball 0 1) := (ennreal.mul_lt_mul_right ((measure_closed_ball_pos μ _ zero_lt_one).ne') measure_closed_ball_lt_top.ne).2 hm, have H : ∀ᶠ (b : ℝ) in 𝓝[>] 0, μ (closed_ball 0 b + A '' closed_ball 0 1) < m * μ (closed_ball 0 1) := (tendsto_order.1 L2).2 _ I, exact (H.and self_mem_nhds_within).exists }, have : Iio (⟨ε, εpos.le⟩ : ℝ≥0) ∈ 𝓝 (0 : ℝ≥0), { apply Iio_mem_nhds, exact εpos }, filter_upwards [this], -- fix a function `f` which is close enough to `A`. assume δ hδ s f hf, -- This function expands the volume of any ball by at most `m` have I : ∀ x r, x ∈ s → 0 ≤ r → μ (f '' (s ∩ closed_ball x r)) ≤ m * μ (closed_ball x r), { assume x r xs r0, have K : f '' (s ∩ closed_ball x r) ⊆ A '' (closed_ball 0 r) + closed_ball (f x) (ε * r), { rintros y ⟨z, ⟨zs, zr⟩, rfl⟩, apply set.mem_add.2 ⟨A (z - x), f z - f x - A (z - x) + f x, _, _, _⟩, { apply mem_image_of_mem, simpa only [dist_eq_norm, mem_closed_ball, mem_closed_ball_zero_iff] using zr }, { rw [mem_closed_ball_iff_norm, add_sub_cancel], calc ∥f z - f x - A (z - x)∥ ≤ δ * ∥z - x∥ : hf _ zs _ xs ... ≤ ε * r : mul_le_mul (le_of_lt hδ) (mem_closed_ball_iff_norm.1 zr) (norm_nonneg _) εpos.le }, { simp only [map_sub, pi.sub_apply], abel } }, have : A '' (closed_ball 0 r) + closed_ball (f x) (ε * r) = {f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε), by rw [smul_add, ← add_assoc, add_comm ({f x}), add_assoc, smul_closed_ball _ _ εpos.le, smul_zero, singleton_add_closed_ball_zero, ← image_smul_set ℝ E E A, smul_closed_ball _ _ zero_le_one, smul_zero, real.norm_eq_abs, abs_of_nonneg r0, mul_one, mul_comm], rw this at K, calc μ (f '' (s ∩ closed_ball x r)) ≤ μ ({f x} + r • (A '' (closed_ball 0 1) + closed_ball 0 ε)) : measure_mono K ... = ennreal.of_real (r ^ finrank ℝ E) * μ (A '' closed_ball 0 1 + closed_ball 0 ε) : by simp only [abs_of_nonneg r0, add_haar_smul, image_add_left, abs_pow, singleton_add, measure_preimage_add] ... ≤ ennreal.of_real (r ^ finrank ℝ E) * (m * μ (closed_ball 0 1)) : by { rw add_comm, exact ennreal.mul_le_mul le_rfl hε.le } ... = m * μ (closed_ball x r) : by { simp only [add_haar_closed_ball' _ _ r0], ring } }, -- covering `s` by closed balls with total measure very close to `μ s`, one deduces that the -- measure of `f '' s` is at most `m * (μ s + a)` for any positive `a`. have J : ∀ᶠ a in 𝓝[>] (0 : ℝ≥0∞), μ (f '' s) ≤ m * (μ s + a), { filter_upwards [self_mem_nhds_within] with a ha, change 0 < a at ha, obtain ⟨t, r, t_count, ts, rpos, st, μt⟩ : ∃ (t : set E) (r : E → ℝ), t.countable ∧ t ⊆ s ∧ (∀ (x : E), x ∈ t → 0 < r x) ∧ (s ⊆ ⋃ (x ∈ t), closed_ball x (r x)) ∧ ∑' (x : ↥t), μ (closed_ball ↑x (r ↑x)) ≤ μ s + a := besicovitch.exists_closed_ball_covering_tsum_measure_le μ ha.ne' (λ x, Ioi 0) s (λ x xs δ δpos, ⟨δ/2, by simp [half_pos δpos, half_lt_self δpos]⟩), haveI : encodable t := t_count.to_encodable, calc μ (f '' s) ≤ μ (⋃ (x : t), f '' (s ∩ closed_ball x (r x))) : begin rw bUnion_eq_Union at st, apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset _ (subset_inter (subset.refl _) st) end ... ≤ ∑' (x : t), μ (f '' (s ∩ closed_ball x (r x))) : measure_Union_le _ ... ≤ ∑' (x : t), m * μ (closed_ball x (r x)) : ennreal.tsum_le_tsum (λ x, I x (r x) (ts x.2) (rpos x x.2).le) ... ≤ m * (μ s + a) : by { rw ennreal.tsum_mul_left, exact ennreal.mul_le_mul le_rfl μt } }, -- taking the limit in `a`, one obtains the conclusion have L : tendsto (λ a, (m : ℝ≥0∞) * (μ s + a)) (𝓝[>] 0) (𝓝 (m * (μ s + 0))), { apply tendsto.mono_left _ nhds_within_le_nhds, apply ennreal.tendsto.const_mul (tendsto_const_nhds.add tendsto_id), simp only [ennreal.coe_ne_top, ne.def, or_true, not_false_iff] }, rw add_zero at L, exact ge_of_tendsto L J, end /-- Let `f` be a function which is sufficiently close (in the Lipschitz sense) to a given linear map `A`. Then it expands the volume of any set by at least `m` for any `m < det A`. -/ lemma mul_le_add_haar_image_of_lt_det (A : E →L[ℝ] E) {m : ℝ≥0} (hm : (m : ℝ≥0∞) < ennreal.of_real (|A.det|)) : ∀ᶠ δ in 𝓝[>] (0 : ℝ≥0), ∀ (s : set E) (f : E → E) (hf : approximates_linear_on f A s δ), (m : ℝ≥0∞) * μ s ≤ μ (f '' s) := begin apply nhds_within_le_nhds, -- The assumption `hm` implies that `A` is invertible. If `f` is close enough to `A`, it is also -- invertible. One can then pass to the inverses, and deduce the estimate from -- `add_haar_image_le_mul_of_det_lt` applied to `f⁻¹` and `A⁻¹`. -- exclude first the trivial case where `m = 0`. rcases eq_or_lt_of_le (zero_le m) with rfl|mpos, { apply eventually_of_forall, simp only [forall_const, zero_mul, implies_true_iff, zero_le, ennreal.coe_zero] }, have hA : A.det ≠ 0, { assume h, simpa only [h, ennreal.not_lt_zero, ennreal.of_real_zero, abs_zero] using hm }, -- let `B` be the continuous linear equiv version of `A`. let B := A.to_continuous_linear_equiv_of_det_ne_zero hA, -- the determinant of `B.symm` is bounded by `m⁻¹` have I : ennreal.of_real (|(B.symm : E →L[ℝ] E).det|) < (m⁻¹ : ℝ≥0), { simp only [ennreal.of_real, abs_inv, real.to_nnreal_inv, continuous_linear_equiv.det_coe_symm, continuous_linear_map.coe_to_continuous_linear_equiv_of_det_ne_zero, ennreal.coe_lt_coe] at ⊢ hm, exact nnreal.inv_lt_inv mpos.ne' hm }, -- therefore, we may apply `add_haar_image_le_mul_of_det_lt` to `B.symm` and `m⁻¹`. obtain ⟨δ₀, δ₀pos, hδ₀⟩ : ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t, { have : ∀ᶠ (δ : ℝ≥0) in 𝓝[>] 0, ∀ (t : set E) (g : E → E), approximates_linear_on g (B.symm : E →L[ℝ] E) t δ → μ (g '' t) ≤ ↑m⁻¹ * μ t := add_haar_image_le_mul_of_det_lt μ B.symm I, rcases (this.and self_mem_nhds_within).exists with ⟨δ₀, h, h'⟩, exact ⟨δ₀, h', h⟩, }, -- record smallness conditions for `δ` that will be needed to apply `hδ₀` below. have L1 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), subsingleton E ∨ δ < ∥(B.symm : E →L[ℝ] E)∥₊⁻¹, { by_cases (subsingleton E), { simp only [h, true_or, eventually_const] }, simp only [h, false_or], apply Iio_mem_nhds, simpa only [h, false_or, nnreal.inv_pos] using B.subsingleton_or_nnnorm_symm_pos }, have L2 : ∀ᶠ δ in 𝓝 (0 : ℝ≥0), ∥(B.symm : E →L[ℝ] E)∥₊ * (∥(B.symm : E →L[ℝ] E)∥₊⁻¹ - δ)⁻¹ * δ < δ₀, { have : tendsto (λ δ, ∥(B.symm : E →L[ℝ] E)∥₊ * (∥(B.symm : E →L[ℝ] E)∥₊⁻¹ - δ)⁻¹ * δ) (𝓝 0) (𝓝 (∥(B.symm : E →L[ℝ] E)∥₊ * (∥(B.symm : E →L[ℝ] E)∥₊⁻¹ - 0)⁻¹ * 0)), { rcases eq_or_ne (∥(B.symm : E →L[ℝ] E)∥₊) 0 with H|H, { simpa only [H, zero_mul] using tendsto_const_nhds }, refine tendsto.mul (tendsto_const_nhds.mul _) tendsto_id, refine (tendsto.sub tendsto_const_nhds tendsto_id).inv₀ _, simpa only [tsub_zero, inv_eq_zero, ne.def] using H }, simp only [mul_zero] at this, exact (tendsto_order.1 this).2 δ₀ δ₀pos }, -- let `δ` be small enough, and `f` approximated by `B` up to `δ`. filter_upwards [L1, L2], assume δ h1δ h2δ s f hf, have hf' : approximates_linear_on f (B : E →L[ℝ] E) s δ, by { convert hf, exact A.coe_to_continuous_linear_equiv_of_det_ne_zero _ }, let F := hf'.to_local_equiv h1δ, -- the condition to be checked can be reformulated in terms of the inverse maps suffices H : μ ((F.symm) '' F.target) ≤ (m⁻¹ : ℝ≥0) * μ F.target, { change (m : ℝ≥0∞) * μ (F.source) ≤ μ (F.target), rwa [← F.symm_image_target_eq_source, mul_comm, ← ennreal.le_div_iff_mul_le, div_eq_mul_inv, mul_comm, ← ennreal.coe_inv (mpos.ne')], { apply or.inl, simpa only [ennreal.coe_eq_zero, ne.def] using mpos.ne'}, { simp only [ennreal.coe_ne_top, true_or, ne.def, not_false_iff] } }, -- as `f⁻¹` is well approximated by `B⁻¹`, the conclusion follows from `hδ₀` -- and our choice of `δ`. exact hδ₀ _ _ ((hf'.to_inv h1δ).mono_num h2δ.le), end /-- If a differentiable function `f` is approximated by a linear map `A` on a set `s`, up to `δ`, then at almost every `x` in `s` one has `∥f' x - A∥ ≤ δ`. -/ lemma _root_.approximates_linear_on.norm_fderiv_sub_le {A : E →L[ℝ] E} {δ : ℝ≥0} (hf : approximates_linear_on f A s δ) (hs : measurable_set s) (f' : E → E →L[ℝ] E) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ∀ᵐ x ∂(μ.restrict s), ∥f' x - A∥₊ ≤ δ := begin /- The conclusion will hold at the Lebesgue density points of `s` (which have full measure). At such a point `x`, for any `z` and any `ε > 0` one has for small `r` that `{x} + r • closed_ball z ε` intersects `s`. At a point `y` in the intersection, `f y - f x` is close both to `f' x (r z)` (by differentiability) and to `A (r z)` (by linear approximation), so these two quantities are close, i.e., `(f' x - A) z` is small. -/ filter_upwards [besicovitch.ae_tendsto_measure_inter_div μ s, ae_restrict_mem hs], -- start from a Lebesgue density point `x`, belonging to `s`. assume x hx xs, -- consider an arbitrary vector `z`. apply continuous_linear_map.op_norm_le_bound _ δ.2 (λ z, _), -- to show that `∥(f' x - A) z∥ ≤ δ ∥z∥`, it suffices to do it up to some error that vanishes -- asymptotically in terms of `ε > 0`. suffices H : ∀ ε, 0 < ε → ∥(f' x - A) z∥ ≤ (δ + ε) * (∥z∥ + ε) + ∥(f' x - A)∥ * ε, { have : tendsto (λ (ε : ℝ), ((δ : ℝ) + ε) * (∥z∥ + ε) + ∥(f' x - A)∥ * ε) (𝓝[>] 0) (𝓝 ((δ + 0) * (∥z∥ + 0) + ∥(f' x - A)∥ * 0)) := tendsto.mono_left (continuous.tendsto (by continuity) 0) nhds_within_le_nhds, simp only [add_zero, mul_zero] at this, apply le_of_tendsto_of_tendsto tendsto_const_nhds this, filter_upwards [self_mem_nhds_within], exact H }, -- fix a positive `ε`. assume ε εpos, -- for small enough `r`, the rescaled ball `r • closed_ball z ε` intersects `s`, as `x` is a -- density point have B₁ : ∀ᶠ r in 𝓝[>] (0 : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty := eventually_nonempty_inter_smul_of_density_one μ s x hx _ measurable_set_closed_ball (measure_closed_ball_pos μ z εpos).ne', obtain ⟨ρ, ρpos, hρ⟩ : ∃ ρ > 0, ball x ρ ∩ s ⊆ {y : E | ∥f y - f x - (f' x) (y - x)∥ ≤ ε * ∥y - x∥} := mem_nhds_within_iff.1 (is_o.def (hf' x xs) εpos), -- for small enough `r`, the rescaled ball `r • closed_ball z ε` is included in the set where -- `f y - f x` is well approximated by `f' x (y - x)`. have B₂ : ∀ᶠ r in 𝓝[>] (0 : ℝ), {x} + r • closed_ball z ε ⊆ ball x ρ := nhds_within_le_nhds (eventually_singleton_add_smul_subset bounded_closed_ball (ball_mem_nhds x ρpos)), -- fix a small positive `r` satisfying the above properties, as well as a corresponding `y`. obtain ⟨r, ⟨y, ⟨ys, hy⟩⟩, rρ, rpos⟩ : ∃ (r : ℝ), (s ∩ ({x} + r • closed_ball z ε)).nonempty ∧ {x} + r • closed_ball z ε ⊆ ball x ρ ∧ 0 < r := (B₁.and (B₂.and self_mem_nhds_within)).exists, -- write `y = x + r a` with `a ∈ closed_ball z ε`. obtain ⟨a, az, ya⟩ : ∃ a, a ∈ closed_ball z ε ∧ y = x + r • a, { simp only [mem_smul_set, image_add_left, mem_preimage, singleton_add] at hy, rcases hy with ⟨a, az, ha⟩, exact ⟨a, az, by simp only [ha, add_neg_cancel_left]⟩ }, have norm_a : ∥a∥ ≤ ∥z∥ + ε := calc ∥a∥ = ∥z + (a - z)∥ : by simp only [add_sub_cancel'_right] ... ≤ ∥z∥ + ∥a - z∥ : norm_add_le _ _ ... ≤ ∥z∥ + ε : add_le_add_left (mem_closed_ball_iff_norm.1 az) _, -- use the approximation properties to control `(f' x - A) a`, and then `(f' x - A) z` as `z` is -- close to `a`. have I : r * ∥(f' x - A) a∥ ≤ r * (δ + ε) * (∥z∥ + ε) := calc r * ∥(f' x - A) a∥ = ∥(f' x - A) (r • a)∥ : by simp only [continuous_linear_map.map_smul, norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le] ... = ∥(f y - f x - A (y - x)) - (f y - f x - (f' x) (y - x))∥ : begin congr' 1, simp only [ya, add_sub_cancel', sub_sub_sub_cancel_left, continuous_linear_map.coe_sub', eq_self_iff_true, sub_left_inj, pi.sub_apply, continuous_linear_map.map_smul, smul_sub], end ... ≤ ∥f y - f x - A (y - x)∥ + ∥f y - f x - (f' x) (y - x)∥ : norm_sub_le _ _ ... ≤ δ * ∥y - x∥ + ε * ∥y - x∥ : add_le_add (hf _ ys _ xs) (hρ ⟨rρ hy, ys⟩) ... = r * (δ + ε) * ∥a∥ : by { simp only [ya, add_sub_cancel', norm_smul, real.norm_eq_abs, abs_of_nonneg rpos.le], ring } ... ≤ r * (δ + ε) * (∥z∥ + ε) : mul_le_mul_of_nonneg_left norm_a (mul_nonneg rpos.le (add_nonneg δ.2 εpos.le)), show ∥(f' x - A) z∥ ≤ (δ + ε) * (∥z∥ + ε) + ∥(f' x - A)∥ * ε, from calc ∥(f' x - A) z∥ = ∥(f' x - A) a + (f' x - A) (z - a)∥ : begin congr' 1, simp only [continuous_linear_map.coe_sub', map_sub, pi.sub_apply], abel end ... ≤ ∥(f' x - A) a∥ + ∥(f' x - A) (z - a)∥ : norm_add_le _ _ ... ≤ (δ + ε) * (∥z∥ + ε) + ∥f' x - A∥ * ∥z - a∥ : begin apply add_le_add, { rw mul_assoc at I, exact (mul_le_mul_left rpos).1 I }, { apply continuous_linear_map.le_op_norm } end ... ≤ (δ + ε) * (∥z∥ + ε) + ∥f' x - A∥ * ε : add_le_add le_rfl (mul_le_mul_of_nonneg_left (mem_closed_ball_iff_norm'.1 az) (norm_nonneg _)), end /-! ### Measure zero of the image, over non-measurable sets If a set has measure `0`, then its image under a differentiable map has measure zero. This doesn't require the set to be measurable. In the same way, if `f` is differentiable on a set `s` with non-invertible derivative everywhere, then `f '' s` has measure `0`, again without measurability assumptions. -/ /-- A differentiable function maps sets of measure zero to sets of measure zero. -/ lemma add_haar_image_eq_zero_of_differentiable_on_of_add_haar_eq_zero (hf : differentiable_on ℝ f s) (hs : μ s = 0) : μ (f '' s) = 0 := begin refine le_antisymm _ (zero_le _), have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + 1 : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal ((|A.det|)) + 1, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, zero_lt_one, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = fderiv_within ℝ f s y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s (fderiv_within ℝ f s) (λ x xs, (hf x xs).has_fderiv_within_at) δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + 1 : ℝ≥0) * 0 : begin refine ennreal.tsum_le_tsum (λ n, ennreal.mul_le_mul le_rfl _), exact le_trans (measure_mono (inter_subset_left _ _)) (le_of_eq hs), end ... = 0 : by simp only [tsum_zero, mul_zero] end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. Here, we give an auxiliary statement towards this result. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (R : ℝ) (hs : s ⊆ closed_ball 0 R) (ε : ℝ≥0) (εpos : 0 < ε) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) ≤ ε * μ (closed_ball 0 R) := begin rcases eq_empty_or_nonempty s with rfl|h's, { simp only [measure_empty, zero_le, image_empty] }, have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ ∀ (t : set E) (hf : approximates_linear_on f A t δ), μ (f '' t) ≤ (real.to_nnreal (|A.det|) + ε : ℝ≥0) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, h'⟩, exact ⟨δ, h', λ t ht, h t f ht⟩ }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (real.to_nnreal (|(A n).det|) + ε : ℝ≥0) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2, exact ht n, end ... = ∑' n, ε * μ (s ∩ t n) : begin congr' with n, rcases Af' h's n with ⟨y, ys, hy⟩, simp only [hy, h'f' y ys, real.to_nnreal_zero, abs_zero, zero_add] end ... ≤ ε * ∑' n, μ (closed_ball 0 R ∩ t n) : begin rw ennreal.tsum_mul_left, refine ennreal.mul_le_mul le_rfl (ennreal.tsum_le_tsum (λ n, measure_mono _)), exact inter_subset_inter_left _ hs, end ... = ε * μ (⋃ n, closed_ball 0 R ∩ t n) : begin rw measure_Union, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) }, { assume n, exact measurable_set_closed_ball.inter (t_meas n) } end ... ≤ ε * μ (closed_ball 0 R) : begin rw ← inter_Union, exact ennreal.mul_le_mul le_rfl (measure_mono (inter_subset_left _ _)), end end /-- A version of Sard lemma in fixed dimension: given a differentiable function from `E` to `E` and a set where the differential is not invertible, then the image of this set has zero measure. -/ lemma add_haar_image_eq_zero_of_det_fderiv_within_eq_zero (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (h'f' : ∀ x ∈ s, (f' x).det = 0) : μ (f '' s) = 0 := begin suffices H : ∀ R, μ (f '' (s ∩ closed_ball 0 R)) = 0, { apply le_antisymm _ (zero_le _), rw ← Union_inter_closed_ball_nat s 0, calc μ (f '' ⋃ (n : ℕ), s ∩ closed_ball 0 n) ≤ ∑' (n : ℕ), μ (f '' (s ∩ closed_ball 0 n)) : by { rw image_Union, exact measure_Union_le _ } ... ≤ 0 : by simp only [H, tsum_zero, nonpos_iff_eq_zero] }, assume R, have A : ∀ (ε : ℝ≥0) (εpos : 0 < ε), μ (f '' (s ∩ closed_ball 0 R)) ≤ ε * μ (closed_ball 0 R) := λ ε εpos, add_haar_image_eq_zero_of_det_fderiv_within_eq_zero_aux μ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) R (inter_subset_right _ _) ε εpos (λ x hx, h'f' x hx.1), have B : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝[>] 0) (𝓝 0), { have : tendsto (λ (ε : ℝ≥0), (ε : ℝ≥0∞) * μ (closed_ball 0 R)) (𝓝 0) (𝓝 (((0 : ℝ≥0) : ℝ≥0∞) * μ (closed_ball 0 R))) := ennreal.tendsto.mul_const (ennreal.tendsto_coe.2 tendsto_id) (or.inr ((measure_closed_ball_lt_top).ne)), simp only [zero_mul, ennreal.coe_zero] at this, exact tendsto.mono_left this nhds_within_le_nhds }, apply le_antisymm _ (zero_le _), apply ge_of_tendsto B, filter_upwards [self_mem_nhds_within], exact A, end /-! ### Weak measurability statements We show that the derivative of a function on a set is almost everywhere measurable, and that the image `f '' s` is measurable if `f` is injective on `s`. The latter statement follows from the Lusin-Souslin theorem. -/ /-- The derivative of a function on a measurable set is almost everywhere measurable on this set with respect to Lebesgue measure. Note that, in general, it is not genuinely measurable there, as `f'` is not unique (but only on a set of measure `0`, as the argument shows). -/ lemma ae_measurable_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable f' (μ.restrict s) := begin /- It suffices to show that `f'` can be uniformly approximated by a measurable function. Fix `ε > 0`. Thanks to `exists_partition_approximates_linear_on_of_has_fderiv_within_at`, one can find a countable measurable partition of `s` into sets `s ∩ t n` on which `f` is well approximated by linear maps `A n`. On almost all of `s ∩ t n`, it follows from `approximates_linear_on.norm_fderiv_sub_le` that `f'` is uniformly approximated by `A n`, which gives the conclusion. -/ -- fix a precision `ε` refine ae_measurable_of_unif_approx (λ ε εpos, _), let δ : ℝ≥0 := ⟨ε, le_of_lt εpos⟩, have δpos : 0 < δ := εpos, -- partition `s` into sets `s ∩ t n` on which `f` is approximated by linear maps `A n`. obtain ⟨t, A, t_disj, t_meas, t_cover, ht, Af'⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) δ) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' (λ A, δ) (λ A, δpos.ne'), -- define a measurable function `g` which coincides with `A n` on `t n`. obtain ⟨g, g_meas, hg⟩ : ∃ g : E → (E →L[ℝ] E), measurable g ∧ ∀ (n : ℕ) (x : E), x ∈ t n → g x = A n := exists_measurable_piecewise_nat t t_meas t_disj (λ n x, A n) (λ n, measurable_const), refine ⟨g, g_meas.ae_measurable, _⟩, -- reduce to checking that `f'` and `g` are close on almost all of `s ∩ t n`, for all `n`. suffices H : ∀ᵐ (x : E) ∂(sum (λ n, μ.restrict (s ∩ t n))), dist (g x) (f' x) ≤ ε, { have : μ.restrict s ≤ sum (λ n, μ.restrict (s ∩ t n)), { have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, conv_lhs { rw this }, exact restrict_Union_le }, exact ae_mono this H }, -- fix such an `n`. refine ae_sum_iff.2 (λ n, _), -- on almost all `s ∩ t n`, `f' x` is close to `A n` thanks to -- `approximates_linear_on.norm_fderiv_sub_le`. have E₁ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), ∥f' x - A n∥₊ ≤ δ := (ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), -- moreover, `g x` is equal to `A n` there. have E₂ : ∀ᵐ (x : E) ∂μ.restrict (s ∩ t n), g x = A n, { suffices H : ∀ᵐ (x : E) ∂μ.restrict (t n), g x = A n, from ae_mono (restrict_mono (inter_subset_right _ _) le_rfl) H, filter_upwards [ae_restrict_mem (t_meas n)], exact hg n }, -- putting these two properties together gives the conclusion. filter_upwards [E₁, E₂] with x hx1 hx2, rw ← nndist_eq_nnnorm at hx1, rw [hx2, dist_comm], exact hx1, end lemma ae_measurable_of_real_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, ennreal.of_real (|(f' x).det|)) (μ.restrict s) := begin apply ennreal.measurable_of_real.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end lemma ae_measurable_to_nnreal_abs_det_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : ae_measurable (λ x, |(f' x).det|.to_nnreal) (μ.restrict s) := begin apply measurable_real_to_nnreal.comp_ae_measurable, refine continuous_abs.measurable.comp_ae_measurable _, refine continuous_linear_map.continuous_det.measurable.comp_ae_measurable _, exact ae_measurable_fderiv_within μ hs hf' end /-- If a function is differentiable and injective on a measurable set, then the image is measurable.-/ lemma measurable_image_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_set (f '' s) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact hs.image_of_continuous_on_inj_on (differentiable_on.continuous_on this) hf, end /-- If a function is differentiable and injective on a measurable set `s`, then its restriction to `s` is a measurable embedding. -/ lemma measurable_embedding_of_fderiv_within (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measurable_embedding (s.restrict f) := begin have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on.measurable_embedding hs hf end /-! ### Proving the estimate for the measure of the image We show the formula `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s)`, in `lintegral_abs_det_fderiv_eq_add_haar_image`. For this, we show both inequalities in both directions, first up to controlled errors and then letting these errors tend to `0`. -/ lemma add_haar_image_le_lintegral_abs_det_fderiv_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) {ε : ℝ≥0} (εpos : 0 < ε) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s := begin /- To bound `μ (f '' s)`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at most `(A n).det + ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ∥B - A∥ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), μ (g '' t) ≤ (ennreal.of_real (|A.det|) + ε) * μ t, { assume A, let m : ℝ≥0 := real.to_nnreal (|A.det|) + ε, have I : ennreal.of_real (|A.det|) < m, by simp only [ennreal.of_real, m, lt_add_iff_pos_right, εpos, ennreal.coe_lt_coe], rcases ((add_haar_image_le_mul_of_det_lt μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, calc ∥B - A∥ ≤ (min δ δ'' : ℝ≥0) : hB ... ≤ δ'' : by simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] ... < δ' : half_lt_self δ'pos }, { assume t g htg, exact h t g (htg.mono_num (min_le_left _ _)) } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), calc μ (f '' s) ≤ μ (⋃ n, f '' (s ∩ t n)) : begin apply measure_mono, rw [← image_Union, ← inter_Union], exact image_subset f (subset_inter subset.rfl t_cover) end ... ≤ ∑' n, μ (f '' (s ∩ t n)) : measure_Union_le _ ... ≤ ∑' n, (ennreal.of_real (|(A n).det|) + ε) * μ (s ∩ t n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply (hδ (A n)).2.2, exact ht n, end ... = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : by simp only [lintegral_const, measurable_set.univ, measure.restrict_apply, univ_inter] ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(A n).det| ≤ |(f' x).det| + ε := calc |(A n).det| = |(f' x).det - ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(f' x).det| + |(f' x).det - (A n).det| : abs_sub _ _ ... ≤ |(f' x).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(A n).det|) + ε ≤ ennreal.of_real (|(f' x).det| + ε) + ε : add_le_add (ennreal.of_real_le_of_real I) le_rfl ... = ennreal.of_real (|(f' x).det|) + 2 * ε : by simp only [ennreal.of_real_add, abs_nonneg, two_mul, add_assoc, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal], end ... = ∫⁻ x in ⋃ n, s ∩ t n, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have M : ∀ (n : ℕ), measurable_set (s ∩ t n) := λ n, hs.inter (t_meas n), rw lintegral_Union M, exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) + 2 * ε ∂μ : begin have : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, rw ← this, end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s : by simp only [lintegral_add_right' _ ae_measurable_const, set_lintegral_const] end lemma add_haar_image_le_lintegral_abs_det_fderiv_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact add_haar_image_le_lintegral_abs_det_fderiv_aux1 μ hs hf' εpos, end lemma add_haar_image_le_lintegral_abs_det_fderiv (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) : μ (f '' s) ≤ ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc μ (f '' s) ≤ ∑' n, μ (f '' (s ∩ u n)) : begin conv_lhs { rw [A, image_Union] }, exact measure_Union_le _, end ... ≤ ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply add_haar_image_le_lintegral_abs_det_fderiv_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_rhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux1 (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) {ε : ℝ≥0} (εpos : 0 < ε) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) + 2 * ε * μ s := begin /- To bound `∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ`, we cover `s` by sets where `f` is well-approximated by linear maps `A n` (and where `f'` is almost everywhere close to `A n`), and then use that `f` expands the measure of such a set by at least `(A n).det - ε`. -/ have : ∀ (A : E →L[ℝ] E), ∃ (δ : ℝ≥0), 0 < δ ∧ (∀ (B : E →L[ℝ] E), ∥B - A∥ ≤ δ → |B.det - A.det| ≤ ε) ∧ ∀ (t : set E) (g : E → E) (hf : approximates_linear_on g A t δ), ennreal.of_real (|A.det|) * μ t ≤ μ (g '' t) + ε * μ t, { assume A, obtain ⟨δ', δ'pos, hδ'⟩ : ∃ (δ' : ℝ) (H : 0 < δ'), ∀ B, dist B A < δ' → dist B.det A.det < ↑ε := continuous_at_iff.1 continuous_linear_map.continuous_det.continuous_at ε εpos, let δ'' : ℝ≥0 := ⟨δ' / 2, (half_pos δ'pos).le⟩, have I'' : ∀ (B : E →L[ℝ] E), ∥B - A∥ ≤ ↑δ'' → |B.det - A.det| ≤ ↑ε, { assume B hB, rw ← real.dist_eq, apply (hδ' B _).le, rw dist_eq_norm, exact hB.trans_lt (half_lt_self δ'pos) }, rcases eq_or_ne A.det 0 with hA|hA, { refine ⟨δ'', half_pos δ'pos, I'', _⟩, simp only [hA, forall_const, zero_mul, ennreal.of_real_zero, implies_true_iff, zero_le, abs_zero] }, let m : ℝ≥0 := real.to_nnreal (|A.det|) - ε, have I : (m : ℝ≥0∞) < ennreal.of_real (|A.det|), { simp only [ennreal.of_real, with_top.coe_sub], apply ennreal.sub_lt_self ennreal.coe_ne_top, { simpa only [abs_nonpos_iff, real.to_nnreal_eq_zero, ennreal.coe_eq_zero, ne.def] using hA }, { simp only [εpos.ne', ennreal.coe_eq_zero, ne.def, not_false_iff] } }, rcases ((mul_le_add_haar_image_of_lt_det μ A I).and self_mem_nhds_within).exists with ⟨δ, h, δpos⟩, refine ⟨min δ δ'', lt_min δpos (half_pos δ'pos), _, _⟩, { assume B hB, apply I'' _ (hB.trans _), simp only [le_refl, nnreal.coe_min, min_le_iff, or_true] }, { assume t g htg, rcases eq_or_ne (μ t) ∞ with ht|ht, { simp only [ht, εpos.ne', with_top.mul_top, ennreal.coe_eq_zero, le_top, ne.def, not_false_iff, ennreal.add_top] }, have := h t g (htg.mono_num (min_le_left _ _)), rwa [with_top.coe_sub, ennreal.sub_mul, tsub_le_iff_right] at this, simp only [ht, implies_true_iff, ne.def, not_false_iff] } }, choose δ hδ using this, obtain ⟨t, A, t_disj, t_meas, t_cover, ht, -⟩ : ∃ (t : ℕ → set E) (A : ℕ → (E →L[ℝ] E)), pairwise (disjoint on t) ∧ (∀ (n : ℕ), measurable_set (t n)) ∧ (s ⊆ ⋃ (n : ℕ), t n) ∧ (∀ (n : ℕ), approximates_linear_on f (A n) (s ∩ t n) (δ (A n))) ∧ (s.nonempty → ∀ n, ∃ y ∈ s, A n = f' y) := exists_partition_approximates_linear_on_of_has_fderiv_within_at f s f' hf' δ (λ A, (hδ A).1.ne'), have s_eq : s = ⋃ n, s ∩ t n, { rw ← inter_Union, exact subset.antisymm (subset_inter subset.rfl t_cover) (inter_subset_left _ _) }, calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw s_eq }, rw lintegral_Union, { exact λ n, hs.inter (t_meas n) }, { exact pairwise_disjoint.mono t_disj (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, ∫⁻ x in s ∩ t n, ennreal.of_real (|(A n).det|) + ε ∂μ : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_mono_ae, filter_upwards [(ht n).norm_fderiv_sub_le μ (hs.inter (t_meas n)) f' (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _))], assume x hx, have I : |(f' x).det| ≤ |(A n).det| + ε := calc |(f' x).det| = |(A n).det + ((f' x).det - (A n).det)| : by { congr' 1, abel } ... ≤ |(A n).det| + |(f' x).det - (A n).det| : abs_add _ _ ... ≤ |(A n).det| + ε : add_le_add le_rfl ((hδ (A n)).2.1 _ hx), calc ennreal.of_real (|(f' x).det|) ≤ ennreal.of_real (|(A n).det| + ε) : ennreal.of_real_le_of_real I ... = ennreal.of_real (|(A n).det|) + ε : by simp only [ennreal.of_real_add, abs_nonneg, nnreal.zero_le_coe, ennreal.of_real_coe_nnreal] end ... = ∑' n, (ennreal.of_real (|(A n).det|) * μ (s ∩ t n) + ε * μ (s ∩ t n)) : by simp only [set_lintegral_const, lintegral_add_right _ measurable_const] ... ≤ ∑' n, ((μ (f '' (s ∩ t n)) + ε * μ (s ∩ t n)) + ε * μ (s ∩ t n)) : begin refine ennreal.tsum_le_tsum (λ n, add_le_add_right _ _), exact (hδ (A n)).2.2 _ _ (ht n), end ... = μ (f '' s) + 2 * ε * μ s : begin conv_rhs { rw s_eq }, rw [image_Union, measure_Union], rotate, { assume i j hij, apply (disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _)), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (t_disj i j hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (t_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, rw measure_Union, rotate, { exact pairwise_disjoint.mono t_disj (λ i, inter_subset_right _ _) }, { exact λ i, hs.inter (t_meas i) }, rw [← ennreal.tsum_mul_left, ← ennreal.tsum_add], congr' 1, ext1 i, rw [mul_assoc, two_mul, add_assoc], end end lemma lintegral_abs_det_fderiv_le_add_haar_image_aux2 (hs : measurable_set s) (h's : μ s ≠ ∞) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We just need to let the error tend to `0` in the previous lemma. -/ have : tendsto (λ (ε : ℝ≥0), μ (f '' s) + 2 * ε * μ s) (𝓝[>] 0) (𝓝 (μ (f '' s) + 2 * (0 : ℝ≥0) * μ s)), { apply tendsto.mono_left _ nhds_within_le_nhds, refine tendsto_const_nhds.add _, refine ennreal.tendsto.mul_const _ (or.inr h's), exact ennreal.tendsto.const_mul (ennreal.tendsto_coe.2 tendsto_id) (or.inr ennreal.coe_ne_top) }, simp only [add_zero, zero_mul, mul_zero, ennreal.coe_zero] at this, apply ge_of_tendsto this, filter_upwards [self_mem_nhds_within], rintros ε (εpos : 0 < ε), exact lintegral_abs_det_fderiv_le_add_haar_image_aux1 μ hs hf' hf εpos end lemma lintegral_abs_det_fderiv_le_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ ≤ μ (f '' s) := begin /- We already know the result for finite-measure sets. We cover `s` by finite-measure sets using `spanning_sets μ`, and apply the previous result to each of these parts. -/ let u := λ n, disjointed (spanning_sets μ) n, have u_meas : ∀ n, measurable_set (u n), { assume n, apply measurable_set.disjointed (λ i, _), exact measurable_spanning_sets μ i }, have A : s = ⋃ n, s ∩ u n, by rw [← inter_Union, Union_disjointed, Union_spanning_sets, inter_univ], calc ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = ∑' n, ∫⁻ x in s ∩ u n, ennreal.of_real (|(f' x).det|) ∂μ : begin conv_lhs { rw A }, rw lintegral_Union, { assume n, exact hs.inter (u_meas n) }, { exact pairwise_disjoint.mono (disjoint_disjointed _) (λ n, inter_subset_right _ _) } end ... ≤ ∑' n, μ (f '' (s ∩ u n)) : begin apply ennreal.tsum_le_tsum (λ n, _), apply lintegral_abs_det_fderiv_le_add_haar_image_aux2 μ (hs.inter (u_meas n)) _ (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)), have : μ (u n) < ∞ := lt_of_le_of_lt (measure_mono (disjointed_subset _ _)) (measure_spanning_sets_lt_top μ n), exact ne_of_lt (lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) this), end ... = μ (f '' s) : begin conv_rhs { rw [A, image_Union] }, rw measure_Union, { assume i j hij, apply disjoint.image _ hf (inter_subset_left _ _) (inter_subset_left _ _), exact disjoint.mono (inter_subset_right _ _) (inter_subset_right _ _) (disjoint_disjointed _ i j hij) }, { assume i, exact measurable_image_of_fderiv_within (hs.inter (u_meas i)) (λ x hx, (hf' x hx.1).mono (inter_subset_left _ _)) (hf.mono (inter_subset_left _ _)) }, end end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the measure of `f '' s` is given by the integral of `|(f' x).det|` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_abs_det_fderiv_eq_add_haar_image (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : ∫⁻ x in s, ennreal.of_real (|(f' x).det|) ∂μ = μ (f '' s) := le_antisymm (lintegral_abs_det_fderiv_le_add_haar_image μ hs hf' hf) (add_haar_image_le_lintegral_abs_det_fderiv μ hs hf') /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version requires that `f` is measurable, as otherwise `measure.map f` is zero per our definitions. For a version without measurability assumption but dealing with the restricted function `s.restrict f`, see `restrict_map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (h'f : measurable f) : measure.map f ((μ.restrict s).with_density (λ x, ennreal.of_real (|(f' x).det|))) = μ.restrict (f '' s) := begin apply measure.ext (λ t ht, _), rw [map_apply h'f ht, with_density_apply _ (h'f ht), measure.restrict_apply ht, restrict_restrict (h'f ht), lintegral_abs_det_fderiv_eq_add_haar_image μ ((h'f ht).inter hs) (λ x hx, (hf' x hx.2).mono (inter_subset_right _ _)) (hf.mono (inter_subset_right _ _)), image_preimage_inter] end /-- Change of variable formula for differentiable functions, set version: if a function `f` is injective and differentiable on a measurable set `s`, then the pushforward of the measure with density `|(f' x).det|` on `s` is the Lebesgue measure on the image set. This version is expressed in terms of the restricted function `s.restrict f`. For a version for the original function, but with a measurability assumption, see `map_with_density_abs_det_fderiv_eq_add_haar`. -/ theorem restrict_map_with_density_abs_det_fderiv_eq_add_haar (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) : measure.map (s.restrict f) (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (f '' s) := begin obtain ⟨u, u_meas, uf⟩ : ∃ u, measurable u ∧ eq_on u f s, { classical, refine ⟨piecewise s f 0, _, piecewise_eq_on _ _ _⟩, refine continuous_on.measurable_piecewise _ continuous_zero.continuous_on hs, have : differentiable_on ℝ f s := λ x hx, (hf' x hx).differentiable_within_at, exact this.continuous_on }, have u' : ∀ x ∈ s, has_fderiv_within_at u (f' x) s x := λ x hx, (hf' x hx).congr (λ y hy, uf hy) (uf hx), set F : s → E := u ∘ coe with hF, have A : measure.map F (comap coe (μ.with_density (λ x, ennreal.of_real (|(f' x).det|)))) = μ.restrict (u '' s), { rw [hF, ← measure.map_map u_meas measurable_subtype_coe, map_comap_subtype_coe hs, restrict_with_density hs], exact map_with_density_abs_det_fderiv_eq_add_haar μ hs u' (hf.congr uf.symm) u_meas }, rw uf.image_eq at A, have : F = s.restrict f, { ext x, exact uf x.2 }, rwa this at A, end /-! ### Change of variable formulas in integrals -/ /- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Lebesgue integral of a function `g : E → ℝ≥0∞` on `f '' s` coincides with the integral of `|(f' x).det| * g ∘ f` on `s`. Note that the measurability of `f '' s` is given by `measurable_image_of_fderiv_within`. -/ theorem lintegral_image_eq_lintegral_abs_det_fderiv_mul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → ℝ≥0∞) : ∫⁻ x in f '' s, g x ∂μ = ∫⁻ x in s, ennreal.of_real (|(f' x).det|) * g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).lintegral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this], rw [← (measurable_embedding.subtype_coe hs).lintegral_map, map_comap_subtype_coe hs, set_lintegral_with_density_eq_set_lintegral_mul_non_measurable₀ _ _ _ hs], { refl }, { simp only [eventually_true, ennreal.of_real_lt_top] }, { exact ae_measurable_of_real_abs_det_fderiv_within μ hs hf' } end /-- Integrability in the change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then a function `g : E → F` is integrable on `f '' s` if and only if `|(f' x).det| • g ∘ f` is integrable on `s`. -/ theorem integrable_on_image_iff_integrable_on_abs_det_fderiv_smul (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : integrable_on g (f '' s) μ ↔ integrable_on (λ x, |(f' x).det| • g (f x)) s μ := begin rw [integrable_on, ← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integrable_map_iff], change (integrable ((g ∘ f) ∘ (coe : s → E)) _) ↔ _, rw [← (measurable_embedding.subtype_coe hs).integrable_map_iff, map_comap_subtype_coe hs], simp only [ennreal.of_real], rw [restrict_with_density hs, integrable_with_density_iff_integrable_coe_smul₀, integrable_on], { congr' 2 with x, rw real.coe_to_nnreal, exact abs_nonneg _ }, { exact ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf' } end /-- Change of variable formula for differentiable functions: if a function `f` is injective and differentiable on a measurable set `s`, then the Bochner integral of a function `g : E → F` on `f '' s` coincides with the integral of `|(f' x).det| • g ∘ f` on `s`. -/ theorem integral_image_eq_integral_abs_det_fderiv_smul [complete_space F] (hs : measurable_set s) (hf' : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hf : inj_on f s) (g : E → F) : ∫ x in f '' s, g x ∂μ = ∫ x in s, |(f' x).det| • g (f x) ∂μ := begin rw [← restrict_map_with_density_abs_det_fderiv_eq_add_haar μ hs hf' hf, (measurable_embedding_of_fderiv_within hs hf' hf).integral_map], have : ∀ (x : s), g (s.restrict f x) = (g ∘ f) x := λ x, rfl, simp only [this, ennreal.of_real], rw [← (measurable_embedding.subtype_coe hs).integral_map, map_comap_subtype_coe hs, set_integral_with_density_eq_set_integral_smul₀ (ae_measurable_to_nnreal_abs_det_fderiv_within μ hs hf') _ hs], congr' with x, conv_rhs { rw ← real.coe_to_nnreal _ (abs_nonneg (f' x).det) }, refl end theorem integral_target_eq_integral_abs_det_fderiv_smul [complete_space F] {f : local_homeomorph E E} (hf' : ∀ x ∈ f.source, has_fderiv_at f (f' x) x) (g : E → F) : ∫ x in f.target, g x ∂μ = ∫ x in f.source, |(f' x).det| • g (f x) ∂μ := begin have : f '' f.source = f.target := local_equiv.image_source_eq_target f.to_local_equiv, rw ← this, apply integral_image_eq_integral_abs_det_fderiv_smul μ f.open_source.measurable_set _ f.inj_on, assume x hx, exact (hf' x hx).has_fderiv_within_at end end measure_theory
4dc916fda473ffc6d4a9c2f713e89041f15304eb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/binary_products.lean
76698c5a4a4829c44fdb315f4002b676a00a27e8
[ "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
41,952
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.terminal import category_theory.discrete_category import category_theory.epi_mono import category_theory.over /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. We include lemmas for simplifying equations involving projections and coprojections, and define braiding and associating isomorphisms, and the product comparison morphism. ## References * [Stacks: Products of pairs](https://stacks.math.columbia.edu/tag/001R) * [Stacks: coproducts of pairs](https://stacks.math.columbia.edu/tag/04AN) -/ noncomputable theory universes v u u₂ open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type | left | right open walking_pair /-- The equivalence swapping left and right. -/ def walking_pair.swap : walking_pair ≃ walking_pair := { to_fun := λ j, walking_pair.rec_on j right left, inv_fun := λ j, walking_pair.rec_on j right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ j, by { cases j; refl, }, } @[simp] lemma walking_pair.swap_apply_left : walking_pair.swap left = right := rfl @[simp] lemma walking_pair.swap_apply_right : walking_pair.swap right = left := rfl @[simp] lemma walking_pair.swap_symm_apply_tt : walking_pair.swap.symm left = right := rfl @[simp] lemma walking_pair.swap_symm_apply_ff : walking_pair.swap.symm right = left := rfl /-- An equivalence from `walking_pair` to `bool`, sometimes useful when reindexing limits. -/ def walking_pair.equiv_bool : walking_pair ≃ bool := { to_fun := λ j, walking_pair.rec_on j tt ff, -- to match equiv.sum_equiv_sigma_bool inv_fun := λ b, bool.rec_on b right left, left_inv := λ j, by { cases j; refl, }, right_inv := λ b, by { cases b; refl, }, } @[simp] lemma walking_pair.equiv_bool_apply_left : walking_pair.equiv_bool left = tt := rfl @[simp] lemma walking_pair.equiv_bool_apply_right : walking_pair.equiv_bool right = ff := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_tt : walking_pair.equiv_bool.symm tt = left := rfl @[simp] lemma walking_pair.equiv_bool_symm_apply_ff : walking_pair.equiv_bool.symm ff = right := rfl variables {C : Type u} /-- The function on the walking pair, sending the two points to `X` and `Y`. -/ def pair_function (X Y : C) : walking_pair → C := λ j, walking_pair.cases_on j X Y @[simp] lemma pair_function_left (X Y : C) : pair_function X Y left = X := rfl @[simp] lemma pair_function_right (X Y : C) : pair_function X Y right = Y := rfl variables [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := discrete.functor (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj ⟨left⟩ = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj ⟨right⟩ = Y := rfl section variables {F G : discrete walking_pair ⥤ C} (f : F.obj ⟨left⟩ ⟶ G.obj ⟨left⟩) (g : F.obj ⟨right⟩ ⟶ G.obj ⟨right⟩) local attribute [tidy] tactic.discrete_cases /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j f g) } @[simp] lemma map_pair_left : (map_pair f g).app ⟨left⟩ = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app ⟨right⟩ = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj ⟨left⟩ ≅ G.obj ⟨left⟩) (g : F.obj ⟨right⟩ ≅ G.obj ⟨right⟩) : F ≅ G := nat_iso.of_components (λ j, discrete.rec_on j (λ j, walking_pair.cases_on j f g)) (by tidy) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ @[simps] def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj ⟨walking_pair.left⟩) (F.obj ⟨walking_pair.right⟩) := map_pair_iso (iso.refl _) (iso.refl _) section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := diagram_iso_pair _ end /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app ⟨walking_pair.left⟩ /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app ⟨walking_pair.right⟩ @[simp] lemma binary_fan.π_app_left {X Y : C} (s : binary_fan X Y) : s.π.app ⟨walking_pair.left⟩ = s.fst := rfl @[simp] lemma binary_fan.π_app_right {X Y : C} (s : binary_fan X Y) : s.π.app ⟨walking_pair.right⟩ = s.snd := rfl /-- A convenient way to show that a binary fan is a limit. -/ def binary_fan.is_limit.mk {X Y : C} (s : binary_fan X Y) (lift : Π {T : C} (f : T ⟶ X) (g : T ⟶ Y), T ⟶ s.X) (hl₁ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ s.fst = f) (hl₂ : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y), lift f g ≫ s.snd = g) (uniq : ∀ {T : C} (f : T ⟶ X) (g : T ⟶ Y) (m : T ⟶ s.X) (h₁ : m ≫ s.fst = f) (h₂ : m ≫ s.snd = g), m = lift f g) : is_limit s := is_limit.mk (λ t, lift (binary_fan.fst t) (binary_fan.snd t)) (by { rintros t (rfl|rfl), { exact hl₁ _ _ }, { exact hl₂ _ _ } }) (λ t m h, uniq _ _ _ (h ⟨walking_pair.left⟩) (h ⟨walking_pair.right⟩)) lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, discrete.rec_on j (λ j, walking_pair.cases_on j h₁ h₂) /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app ⟨walking_pair.left⟩ /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app ⟨walking_pair.right⟩ @[simp] lemma binary_cofan.ι_app_left {X Y : C} (s : binary_cofan X Y) : s.ι.app ⟨walking_pair.left⟩ = s.inl := rfl @[simp] lemma binary_cofan.ι_app_right {X Y : C} (s : binary_cofan X Y) : s.ι.app ⟨walking_pair.right⟩ = s.inr := rfl /-- A convenient way to show that a binary cofan is a colimit. -/ def binary_cofan.is_colimit.mk {X Y : C} (s : binary_cofan X Y) (desc : Π {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.X ⟶ T) (hd₁ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.inl ≫ desc f g = f) (hd₂ : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T), s.inr ≫ desc f g = g) (uniq : ∀ {T : C} (f : X ⟶ T) (g : Y ⟶ T) (m : s.X ⟶ T) (h₁ : s.inl ≫ m = f) (h₂ : s.inr ≫ m = g), m = desc f g) : is_colimit s := is_colimit.mk (λ t, desc (binary_cofan.inl t) (binary_cofan.inr t)) (by { rintros t (rfl|rfl), { exact hd₁ _ _ }, { exact hd₂ _ _ }}) (λ t m h, uniq _ _ _ (h ⟨walking_pair.left⟩) (h ⟨walking_pair.right⟩)) lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, discrete.rec_on j (λ j, walking_pair.cases_on j h₁ h₂) variables {X Y : C} section local attribute [tidy] tactic.discrete_cases /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ @[simps X] def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j π₁ π₂) }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ @[simps X] def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, discrete.rec_on j (λ j, walking_pair.cases_on j ι₁ ι₂) }} end @[simp] lemma binary_fan.mk_fst {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).fst = π₁ := rfl @[simp] lemma binary_fan.mk_snd {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).snd = π₂ := rfl @[simp] lemma binary_cofan.mk_inl {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).inl = ι₁ := rfl @[simp] lemma binary_cofan.mk_inr {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).inr = ι₂ := rfl /-- Every `binary_fan` is isomorphic to an application of `binary_fan.mk`. -/ def iso_binary_fan_mk {X Y : C} (c : binary_fan X Y) : c ≅ binary_fan.mk c.fst c.snd := cones.ext (iso.refl _) (λ j, by discrete_cases; cases j; tidy) /-- Every `binary_fan` is isomorphic to an application of `binary_fan.mk`. -/ def iso_binary_cofan_mk {X Y : C} (c : binary_cofan X Y) : c ≅ binary_cofan.mk c.inl c.inr := cocones.ext (iso.refl _) (λ j, by discrete_cases; cases j; tidy) /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ @[simps] def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ @[simps] def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- An abbreviation for `has_limit (pair X Y)`. -/ abbreviation has_binary_product (X Y : C) := has_limit (pair X Y) /-- An abbreviation for `has_colimit (pair X Y)`. -/ abbreviation has_binary_coproduct (X Y : C) := has_colimit (pair X Y) /-- If we have a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_binary_product X Y] := limit (pair X Y) /-- If we have a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_binary_coproduct X Y] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ X := limit.π (pair X Y) ⟨walking_pair.left⟩ /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_binary_product X Y] : X ⨯ Y ⟶ Y := limit.π (pair X Y) ⟨walking_pair.right⟩ /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_binary_coproduct X Y] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) ⟨walking_pair.left⟩ /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_binary_coproduct X Y] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) ⟨walking_pair.right⟩ /-- The binary fan constructed from the projection maps is a limit. -/ def prod_is_prod (X Y : C) [has_binary_product X Y] : is_limit (binary_fan.mk (prod.fst : X ⨯ Y ⟶ X) prod.snd) := (limit.is_limit _).of_iso_limit (cones.ext (iso.refl _) (by { rintro (_ | _), tidy })) /-- The binary cofan constructed from the coprojection maps is a colimit. -/ def coprod_is_coprod (X Y : C) [has_binary_coproduct X Y] : is_colimit (binary_cofan.mk (coprod.inl : X ⟶ X ⨿ Y) coprod.inr) := (colimit.is_colimit _).of_iso_colimit (cocones.ext (iso.refl _) (by { rintro (_ | _), tidy })) @[ext] lemma prod.hom_ext {W X Y : C} [has_binary_product X Y] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_binary_coproduct X Y] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- diagonal arrow of the binary product in the category `fam I` -/ abbreviation diag (X : C) [has_binary_product X X] : X ⟶ X ⨯ X := prod.lift (𝟙 _) (𝟙 _) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) /-- codiagonal arrow of the binary coproduct -/ abbreviation codiag (X : C) [has_binary_coproduct X X] : X ⨿ X ⟶ X := coprod.desc (𝟙 _) (𝟙 _) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.inl_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.inr_desc {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ instance prod.mono_lift_of_mono_left {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_binary_product X Y] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_binary_coproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ def prod.map {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim_map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ def coprod.map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim_map (map_pair f g) section prod_lemmas -- Making the reassoc version of this a simp lemma seems to be more harmful than helpful. @[reassoc, simp] lemma prod.comp_lift {V W X Y : C} [has_binary_product X Y] (f : V ⟶ W) (g : W ⟶ X) (h : W ⟶ Y) : f ≫ prod.lift g h = prod.lift (f ≫ g) (f ≫ h) := by { ext; simp } lemma prod.comp_diag {X Y : C} [has_binary_product Y Y] (f : X ⟶ Y) : f ≫ diag Y = prod.lift f f := by simp @[simp, reassoc] lemma prod.map_fst {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := lim_map_π _ _ @[simp, reassoc] lemma prod.map_snd {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := lim_map_π _ _ @[simp] lemma prod.map_id_id {X Y : C} [has_binary_product X Y] : prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by { ext; simp } @[simp] lemma prod.lift_fst_snd {X Y : C} [has_binary_product X Y] : prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) := by { ext; simp } @[simp, reassoc] lemma prod.lift_map {V W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by { ext; simp } @[simp] lemma prod.lift_fst_comp_snd_comp {W X Y Z : C} [has_binary_product W Y] [has_binary_product X Z] (g : W ⟶ X) (g' : Y ⟶ Z) : prod.lift (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' := by { rw ← prod.lift_map, simp } -- We take the right hand side here to be simp normal form, as this way composition lemmas for -- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `map_fst` and `map_snd` can still work just -- as well. @[simp, reassoc] lemma prod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C} [has_binary_product A₁ B₁] [has_binary_product A₂ B₂] [has_binary_product A₃ B₃] (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) : prod.map f g ≫ prod.map h k = prod.map (f ≫ h) (g ≫ k) := by { ext; simp } -- TODO: is it necessary to weaken the assumption here? @[reassoc] lemma prod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_limits_of_shape (discrete walking_pair) C] : prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f := by simp @[reassoc] lemma prod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_product X W] [has_binary_product Z W] [has_binary_product Y W] : prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) := by simp @[reassoc] lemma prod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_product W X] [has_binary_product W Y] [has_binary_product W Z] : prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g := by simp /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : X ≅ Z` induces an isomorphism `prod.map_iso f g : W ⨯ X ≅ Y ⨯ Z`. -/ @[simps] def prod.map_iso {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⨯ X ≅ Y ⨯ Z := { hom := prod.map f.hom g.hom, inv := prod.map f.inv g.inv } instance is_iso_prod {W X Y Z : C} [has_binary_product W X] [has_binary_product Y Z] (f : W ⟶ Y) (g : X ⟶ Z) [is_iso f] [is_iso g] : is_iso (prod.map f g) := is_iso.of_iso (prod.map_iso (as_iso f) (as_iso g)) instance prod.map_mono {C : Type*} [category C] {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [mono f] [mono g] [has_binary_product W X] [has_binary_product Y Z] : mono (prod.map f g) := ⟨λ A i₁ i₂ h, begin ext, { rw ← cancel_mono f, simpa using congr_arg (λ f, f ≫ prod.fst) h }, { rw ← cancel_mono g, simpa using congr_arg (λ f, f ≫ prod.snd) h } end⟩ @[simp, reassoc] lemma prod.diag_map {X Y : C} (f : X ⟶ Y) [has_binary_product X X] [has_binary_product Y Y] : diag X ≫ prod.map f f = f ≫ diag Y := by simp @[simp, reassoc] lemma prod.diag_map_fst_snd {X Y : C} [has_binary_product X Y] [has_binary_product (X ⨯ Y) (X ⨯ Y)] : diag (X ⨯ Y) ≫ prod.map prod.fst prod.snd = 𝟙 (X ⨯ Y) := by simp @[simp, reassoc] lemma prod.diag_map_fst_snd_comp [has_limits_of_shape (discrete walking_pair) C] {X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') : diag (X ⨯ X') ≫ prod.map (prod.fst ≫ g) (prod.snd ≫ g') = prod.map g g' := by simp instance {X : C} [has_binary_product X X] : is_split_mono (diag X) := is_split_mono.mk' { retraction := prod.fst } end prod_lemmas section coprod_lemmas @[simp, reassoc] lemma coprod.desc_comp {V W X Y : C} [has_binary_coproduct X Y] (f : V ⟶ W) (g : X ⟶ V) (h : Y ⟶ V) : coprod.desc g h ≫ f = coprod.desc (g ≫ f) (h ≫ f) := by { ext; simp } lemma coprod.diag_comp {X Y : C} [has_binary_coproduct X X] (f : X ⟶ Y) : codiag X ≫ f = coprod.desc f f := by simp @[simp, reassoc] lemma coprod.inl_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := ι_colim_map _ _ @[simp, reassoc] lemma coprod.inr_map {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := ι_colim_map _ _ @[simp] lemma coprod.map_id_id {X Y : C} [has_binary_coproduct X Y] : coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by { ext; simp } @[simp] lemma coprod.desc_inl_inr {X Y : C} [has_binary_coproduct X Y] : coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) := by { ext; simp } -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_desc {S T U V W : C} [has_binary_coproduct U W] [has_binary_coproduct T V] (f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) : coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) := by { ext; simp } @[simp] lemma coprod.desc_comp_inl_comp_inr {W X Y Z : C} [has_binary_coproduct W Y] [has_binary_coproduct X Z] (g : W ⟶ X) (g' : Y ⟶ Z) : coprod.desc (g ≫ coprod.inl) (g' ≫ coprod.inr) = coprod.map g g' := by { rw ← coprod.map_desc, simp } -- We take the right hand side here to be simp normal form, as this way composition lemmas for -- `f ≫ h` and `g ≫ k` can fire (eg `id_comp`) , while `inl_map` and `inr_map` can still work just -- as well. @[simp, reassoc] lemma coprod.map_map {A₁ A₂ A₃ B₁ B₂ B₃ : C} [has_binary_coproduct A₁ B₁] [has_binary_coproduct A₂ B₂] [has_binary_coproduct A₃ B₃] (f : A₁ ⟶ A₂) (g : B₁ ⟶ B₂) (h : A₂ ⟶ A₃) (k : B₂ ⟶ B₃) : coprod.map f g ≫ coprod.map h k = coprod.map (f ≫ h) (g ≫ k) := by { ext; simp } -- I don't think it's a good idea to make any of the following three simp lemmas. @[reassoc] lemma coprod.map_swap {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) [has_colimits_of_shape (discrete walking_pair) C] : coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f := by simp @[reassoc] lemma coprod.map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_coproduct Z W] [has_binary_coproduct Y W] [has_binary_coproduct X W] : coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) := by simp @[reassoc] lemma coprod.map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) [has_binary_coproduct W X] [has_binary_coproduct W Y] [has_binary_coproduct W Z] : coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g := by simp /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of isomorphisms `f : W ≅ Y` and `g : W ≅ Z` induces a isomorphism `coprod.map_iso f g : W ⨿ X ≅ Y ⨿ Z`. -/ @[simps] def coprod.map_iso {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⨿ X ≅ Y ⨿ Z := { hom := coprod.map f.hom g.hom, inv := coprod.map f.inv g.inv } instance is_iso_coprod {W X Y Z : C} [has_binary_coproduct W X] [has_binary_coproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) [is_iso f] [is_iso g] : is_iso (coprod.map f g) := is_iso.of_iso (coprod.map_iso (as_iso f) (as_iso g)) instance coprod.map_epi {C : Type*} [category C] {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [epi f] [epi g] [has_binary_coproduct W X] [has_binary_coproduct Y Z] : epi (coprod.map f g) := ⟨λ A i₁ i₂ h, begin ext, { rw ← cancel_epi f, simpa using congr_arg (λ f, coprod.inl ≫ f) h }, { rw ← cancel_epi g, simpa using congr_arg (λ f, coprod.inr ≫ f) h } end⟩ -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_codiag {X Y : C} (f : X ⟶ Y) [has_binary_coproduct X X] [has_binary_coproduct Y Y] : coprod.map f f ≫ codiag Y = codiag X ≫ f := by simp -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_inl_inr_codiag {X Y : C} [has_binary_coproduct X Y] [has_binary_coproduct (X ⨿ Y) (X ⨿ Y)] : coprod.map coprod.inl coprod.inr ≫ codiag (X ⨿ Y) = 𝟙 (X ⨿ Y) := by simp -- The simp linter says simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma coprod.map_comp_inl_inr_codiag [has_colimits_of_shape (discrete walking_pair) C] {X X' Y Y' : C} (g : X ⟶ Y) (g' : X' ⟶ Y') : coprod.map (g ≫ coprod.inl) (g' ≫ coprod.inr) ≫ codiag (Y ⨿ Y') = coprod.map g g' := by simp end coprod_lemmas variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. See <https://stacks.math.columbia.edu/tag/001T>. -/ abbreviation has_binary_products := has_limits_of_shape (discrete walking_pair) C /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. See <https://stacks.math.columbia.edu/tag/04AP>. -/ abbreviation has_binary_coproducts := has_colimits_of_shape (discrete walking_pair) C /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ lemma has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ lemma has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } section variables {C} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma braid_natural [has_binary_products C] {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f := by simp @[reassoc] lemma prod.symmetry' (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := (prod.braiding _ _).hom_inv_id /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma prod.symmetry (P Q : C) [has_binary_product P Q] [has_binary_product Q P] : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := (prod.braiding _ _).hom_inv_id /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator [has_binary_products C] (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } @[reassoc] lemma prod.pentagon [has_binary_products C] (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y ⨯ Z)).hom := by simp @[reassoc] lemma prod.associator_naturality [has_binary_products C] {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by simp variables [has_terminal C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) [has_binary_product (⊤_ C) P] : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) [has_binary_product P (⊤_ C)] : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } @[reassoc] lemma prod.left_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) : prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f := prod.map_snd _ _ @[reassoc] lemma prod.left_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) : (prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.left_unitor_hom_naturality] @[reassoc] lemma prod.right_unitor_hom_naturality [has_binary_products C] (f : X ⟶ Y) : prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f := prod.map_fst _ _ @[reassoc] lemma prod_right_unitor_inv_naturality [has_binary_products C] (f : X ⟶ Y) : (prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod.right_unitor_hom_naturality] lemma prod.triangle [has_binary_products C] (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts C] /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[reassoc] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := (coprod.braiding _ _).hom_inv_id /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := coprod.symmetry' _ _ /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X ⨿ Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W ⨿ X) Y Z).hom ≫ (coprod.associator W X (Y ⨿ Z)).hom := by simp lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by simp variables [has_initial C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end section prod_functor variables {C} [has_binary_products C] /-- The binary product functor. -/ @[simps] def prod.functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The product functor can be decomposed. -/ def prod.functor_left_comp (X Y : C) : prod.functor.obj (X ⨯ Y) ≅ prod.functor.obj Y ⋙ prod.functor.obj X := nat_iso.of_components (prod.associator _ _) (by tidy) end prod_functor section coprod_functor variables {C} [has_binary_coproducts C] /-- The binary coproduct functor. -/ @[simps] def coprod.functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨿ Y, map := λ Y Z, coprod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, coprod.map f (𝟙 T) }} /-- The coproduct functor can be decomposed. -/ def coprod.functor_left_comp (X Y : C) : coprod.functor.obj (X ⨿ Y) ≅ coprod.functor.obj Y ⋙ coprod.functor.obj X := nat_iso.of_components (coprod.associator _ _) (by tidy) end coprod_functor section prod_comparison universe w variables {C} {D : Type u₂} [category.{w} D] variables (F : C ⥤ D) {A A' B B' : C} variables [has_binary_product A B] [has_binary_product A' B'] variables [has_binary_product (F.obj A) (F.obj B)] [has_binary_product (F.obj A') (F.obj B')] /-- The product comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary products. -/ def prod_comparison (F : C ⥤ D) (A B : C) [has_binary_product A B] [has_binary_product (F.obj A) (F.obj B)] : F.obj (A ⨯ B) ⟶ F.obj A ⨯ F.obj B := prod.lift (F.map prod.fst) (F.map prod.snd) @[simp, reassoc] lemma prod_comparison_fst : prod_comparison F A B ≫ prod.fst = F.map prod.fst := prod.lift_fst _ _ @[simp, reassoc] lemma prod_comparison_snd : prod_comparison F A B ≫ prod.snd = F.map prod.snd := prod.lift_snd _ _ /-- Naturality of the prod_comparison morphism in both arguments. -/ @[reassoc] lemma prod_comparison_natural (f : A ⟶ A') (g : B ⟶ B') : F.map (prod.map f g) ≫ prod_comparison F A' B' = prod_comparison F A B ≫ prod.map (F.map f) (F.map g) := begin rw [prod_comparison, prod_comparison, prod.lift_map, ← F.map_comp, ← F.map_comp, prod.comp_lift, ← F.map_comp, prod.map_fst, ← F.map_comp, prod.map_snd] end /-- The product comparison morphism from `F(A ⨯ -)` to `FA ⨯ F-`, whose components are given by `prod_comparison`. -/ @[simps] def prod_comparison_nat_trans [has_binary_products C] [has_binary_products D] (F : C ⥤ D) (A : C) : prod.functor.obj A ⋙ F ⟶ F ⋙ prod.functor.obj (F.obj A) := { app := λ B, prod_comparison F A B, naturality' := λ B B' f, by simp [prod_comparison_natural] } @[reassoc] lemma inv_prod_comparison_map_fst [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.fst = prod.fst := by simp [is_iso.inv_comp_eq] @[reassoc] lemma inv_prod_comparison_map_snd [is_iso (prod_comparison F A B)] : inv (prod_comparison F A B) ≫ F.map prod.snd = prod.snd := by simp [is_iso.inv_comp_eq] /-- If the product comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma prod_comparison_inv_natural (f : A ⟶ A') (g : B ⟶ B') [is_iso (prod_comparison F A B)] [is_iso (prod_comparison F A' B')] : inv (prod_comparison F A B) ≫ F.map (prod.map f g) = prod.map (F.map f) (F.map g) ≫ inv (prod_comparison F A' B') := by rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq, prod_comparison_natural] /-- The natural isomorphism `F(A ⨯ -) ≅ FA ⨯ F-`, provided each `prod_comparison F A B` is an isomorphism (as `B` changes). -/ @[simps {rhs_md := semireducible}] def prod_comparison_nat_iso [has_binary_products C] [has_binary_products D] (A : C) [∀ B, is_iso (prod_comparison F A B)] : prod.functor.obj A ⋙ F ≅ F ⋙ prod.functor.obj (F.obj A) := { hom := prod_comparison_nat_trans F A ..(@as_iso _ _ _ _ _ (nat_iso.is_iso_of_is_iso_app ⟨_, _⟩)) } end prod_comparison section coprod_comparison universe w variables {C} {D : Type u₂} [category.{w} D] variables (F : C ⥤ D) {A A' B B' : C} variables [has_binary_coproduct A B] [has_binary_coproduct A' B'] variables [has_binary_coproduct (F.obj A) (F.obj B)] [has_binary_coproduct (F.obj A') (F.obj B')] /-- The coproduct comparison morphism. In `category_theory/limits/preserves` we show this is always an iso iff F preserves binary coproducts. -/ def coprod_comparison (F : C ⥤ D) (A B : C) [has_binary_coproduct A B] [has_binary_coproduct (F.obj A) (F.obj B)] : F.obj A ⨿ F.obj B ⟶ F.obj (A ⨿ B) := coprod.desc (F.map coprod.inl) (F.map coprod.inr) @[simp, reassoc] lemma coprod_comparison_inl : coprod.inl ≫ coprod_comparison F A B = F.map coprod.inl := coprod.inl_desc _ _ @[simp, reassoc] lemma coprod_comparison_inr : coprod.inr ≫ coprod_comparison F A B = F.map coprod.inr := coprod.inr_desc _ _ /-- Naturality of the coprod_comparison morphism in both arguments. -/ @[reassoc] lemma coprod_comparison_natural (f : A ⟶ A') (g : B ⟶ B') : coprod_comparison F A B ≫ F.map (coprod.map f g) = coprod.map (F.map f) (F.map g) ≫ coprod_comparison F A' B' := begin rw [coprod_comparison, coprod_comparison, coprod.map_desc, ← F.map_comp, ← F.map_comp, coprod.desc_comp, ← F.map_comp, coprod.inl_map, ← F.map_comp, coprod.inr_map] end /-- The coproduct comparison morphism from `FA ⨿ F-` to `F(A ⨿ -)`, whose components are given by `coprod_comparison`. -/ @[simps] def coprod_comparison_nat_trans [has_binary_coproducts C] [has_binary_coproducts D] (F : C ⥤ D) (A : C) : F ⋙ coprod.functor.obj (F.obj A) ⟶ coprod.functor.obj A ⋙ F := { app := λ B, coprod_comparison F A B, naturality' := λ B B' f, by simp [coprod_comparison_natural] } @[reassoc] lemma map_inl_inv_coprod_comparison [is_iso (coprod_comparison F A B)] : F.map coprod.inl ≫ inv (coprod_comparison F A B) = coprod.inl := by simp [is_iso.inv_comp_eq] @[reassoc] lemma map_inr_inv_coprod_comparison [is_iso (coprod_comparison F A B)] : F.map coprod.inr ≫ inv (coprod_comparison F A B) = coprod.inr := by simp [is_iso.inv_comp_eq] /-- If the coproduct comparison morphism is an iso, its inverse is natural. -/ @[reassoc] lemma coprod_comparison_inv_natural (f : A ⟶ A') (g : B ⟶ B') [is_iso (coprod_comparison F A B)] [is_iso (coprod_comparison F A' B')] : inv (coprod_comparison F A B) ≫ coprod.map (F.map f) (F.map g) = F.map (coprod.map f g) ≫ inv (coprod_comparison F A' B') := by rw [is_iso.eq_comp_inv, category.assoc, is_iso.inv_comp_eq, coprod_comparison_natural] /-- The natural isomorphism `FA ⨿ F- ≅ F(A ⨿ -)`, provided each `coprod_comparison F A B` is an isomorphism (as `B` changes). -/ @[simps {rhs_md := semireducible}] def coprod_comparison_nat_iso [has_binary_coproducts C] [has_binary_coproducts D] (A : C) [∀ B, is_iso (coprod_comparison F A B)] : F ⋙ coprod.functor.obj (F.obj A) ≅ coprod.functor.obj A ⋙ F := { hom := coprod_comparison_nat_trans F A ..(@as_iso _ _ _ _ _ (nat_iso.is_iso_of_is_iso_app ⟨_, _⟩)) } end coprod_comparison end category_theory.limits open category_theory.limits namespace category_theory variables {C : Type u} [category.{v} C] /-- Auxiliary definition for `over.coprod`. -/ @[simps] def over.coprod_obj [has_binary_coproducts C] {A : C} : over A → over A ⥤ over A := λ f, { obj := λ g, over.mk (coprod.desc f.hom g.hom), map := λ g₁ g₂ k, over.hom_mk (coprod.map (𝟙 _) k.left) } /-- A category with binary coproducts has a functorial `sup` operation on over categories. -/ @[simps] def over.coprod [has_binary_coproducts C] {A : C} : over A ⥤ over A ⥤ over A := { obj := λ f, over.coprod_obj f, map := λ f₁ f₂ k, { app := λ g, over.hom_mk (coprod.map k.left (𝟙 _)) (by { dsimp, rw [coprod.map_desc, category.id_comp, over.w k] }), naturality' := λ f g k, by ext; { dsimp, simp, }, }, map_id' := λ X, by ext; { dsimp, simp, }, map_comp' := λ X Y Z f g, by ext; { dsimp, simp, }, }. end category_theory
cdfba66c8ec1fed109c7f9489a45afdf95698879
4fc5f02f6ed9423b87987589bcc202f985d7e9ff
/src/game/intro.lean
3a2f77739e75c6b6ee301a39d2743d63a1ae77e4
[ "Apache-2.0" ]
permissive
grthomson/natural_number_game
2937533df0b83e73e6a873c0779ee21e30f09778
0a23a327ca724b95406c510ee27c55f5b97e612f
refs/heads/master
1,599,994,591,355
1,588,869,073,000
1,588,869,073,000
222,750,177
0
0
Apache-2.0
1,574,183,960,000
1,574,183,960,000
null
UTF-8
Lean
false
false
2,992
lean
/- # The Natural Number Game, version 1.3.2 ## By Kevin Buzzard and Mohammad Pedramfar. # What is this game? Welcome to the natural number game -- a part-book part-game which shows the power of induction. Blue nodes on the graph are ones that you are ready to enter. Grey nodes you should stay away from -- a grey node turns blue when *all* nodes above it are complete. Green nodes are completed. (Actually you can try any level at any time, but you might not know enough to complete it if it's grey). In this game, you get own version of the natural numbers, called `mynat`, in an interactive theorem prover called Lean. Your version of the natural numbers satisfies something called the principle of mathematical induction, and a couple of other things too (Peano's axioms). Unfortunately, nobody has proved any theorems about these natural numbers yet! For example, addition will be defined for you, but nobody has proved that `x + y = y + x` yet. This is your job. You're going to prove mathematical theorems using the Lean theorem prover. In other words, you're going to solve levels in a computer game. You're going to prove these theorems using *tactics*. The introductory world, Tutorial World, will take you through some of these tactics. During your proofs, your "goal" (i.e. what you're supposed to be proving) will be displayed with a `⊢` symbol in front of it. If the top right hand box reports "Theorem Proved!", you have closed all the goals in the level and can move on to the next level in the world you're in. When you've finished a world, hit "main menu" in the top left to get back here. For more info, see the <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game/FAQ.html" target="blank">FAQ</a>. # What's new in v1.3.2? The game now saves your progress! Thanks to everyone who asked for it, and to Mohammad for making it happen :-) # Thanks Special thanks to Rob Lewis for tactic hackery, Bryan Gin-Ge Chen for javascript hackery, Patrick Massot for his <a href="https://github.com/leanprover-community/format_lean" target="blank">Lean to html formatter</a>, Sian Carey for Power World, and, last but not least, all the people who fed back comments, including the 2019-20 Imperial College 1st year maths beta tester students, Marie-Amélie Lawn, Toby Gee, Joseph Myers, and all the people who have been in touch via the <a href="https://leanprover.zulipchat.com/" target="blank">Lean Zulip chat</a> or the <a href="https://xenaproject.wordpress.com/" target="blank">Xena Project blog</a> or via <a href="https://twitter.com/XenaProject" target="blank">Twitter</a>. The natural 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>. -/
190bd9ea1642a1f5178544109f1931185793f146
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/homotopy/basic.lean
ce67a22a6d9bdb56b3fa7e064a6c59e15f15f5e1
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,962
lean
/- Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam -/ import topology.unit_interval import topology.algebra.ordered.proj_Icc import topology.continuous_function.basic import topology.compact_open /-! # Homotopy between functions In this file, we define a homotopy between two functions `f₀` and `f₁`. First we define `homotopy` between the two functions, with no restrictions on the intermediate maps. Then, as in the formalisation in HOL-Analysis, we define `homotopy_with f₀ f₁ P`, for homotopies between `f₀` and `f₁`, where the intermediate maps satisfy the predicate `P`. Finally, we define `homotopy_rel f₀ f₁ S`, for homotopies between `f₀` and `f₁` which are fixed on `S`. ## Definitions * `homotopy f₀ f₁` is the type of homotopies between `f₀` and `f₁`. * `homotopy_with f₀ f₁ P` is the type of homotopies between `f₀` and `f₁`, where the intermediate maps satisfy the predicate `P`. * `homotopy_rel f₀ f₁ S` is the type of homotopies between `f₀` and `f₁` which are fixed on `S`. For each of the above, we have * `refl f`, which is the constant homotopy from `f` to `f`. * `symm F`, which reverses the homotopy `F`. For example, if `F : homotopy f₀ f₁`, then `F.symm : homotopy f₁ f₀`. * `trans F G`, which concatenates the homotopies `F` and `G`. For example, if `F : homotopy f₀ f₁` and `G : homotopy f₁ f₂`, then `F.trans G : homotopy f₀ f₂`. We also define the relations * `homotopic f₀ f₁` is defined to be `nonempty (homotopy f₀ f₁)` * `homotopic_with f₀ f₁ P` is defined to be `nonempty (homotopy_with f₀ f₁ P)` * `homotopic_rel f₀ f₁ P` is defined to be `nonempty (homotopy_rel f₀ f₁ P)` and for `homotopic` and `homotopic_rel`, we also define the `setoid` and `quotient` in `C(X, Y)` by these relations. ## References - [HOL-Analysis formalisation](https://isabelle.in.tum.de/library/HOL/HOL-Analysis/Homotopy.html) -/ noncomputable theory universes u v w variables {X : Type u} {Y : Type v} {Z : Type w} variables [topological_space X] [topological_space Y] [topological_space Z] open_locale unit_interval namespace continuous_map /-- The type of homotopies between two functions. -/ structure homotopy (f₀ f₁ : C(X, Y)) extends C(I × X, Y) := (to_fun_zero : ∀ x, to_fun (0, x) = f₀ x) (to_fun_one : ∀ x, to_fun (1, x) = f₁ x) namespace homotopy section variables {f₀ f₁ : C(X, Y)} instance : has_coe_to_fun (homotopy f₀ f₁) (λ _, I × X → Y) := ⟨λ F, F.to_fun⟩ lemma coe_fn_injective : @function.injective (homotopy f₀ f₁) (I × X → Y) coe_fn := begin rintros ⟨⟨F, _⟩, _⟩ ⟨⟨G, _⟩, _⟩ h, congr' 2, end @[ext] lemma ext {F G : homotopy f₀ f₁} (h : ∀ x, F x = G x) : F = G := coe_fn_injective $ funext h /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (F : homotopy f₀ f₁) : I × X → Y := F initialize_simps_projections homotopy (to_continuous_map_to_fun -> apply, -to_continuous_map) @[continuity] protected lemma continuous (F : homotopy f₀ f₁) : continuous F := F.continuous_to_fun @[simp] lemma apply_zero (F : homotopy f₀ f₁) (x : X) : F (0, x) = f₀ x := F.to_fun_zero x @[simp] lemma apply_one (F : homotopy f₀ f₁) (x : X) : F (1, x) = f₁ x := F.to_fun_one x @[simp] lemma coe_to_continuous_map (F : homotopy f₀ f₁) : ⇑F.to_continuous_map = F := rfl /-- Currying a homotopy to a continuous function fron `I` to `C(X, Y)`. -/ def curry (F : homotopy f₀ f₁) : C(I, C(X, Y)) := F.to_continuous_map.curry @[simp] lemma curry_apply (F : homotopy f₀ f₁) (t : I) (x : X) : F.curry t x = F (t, x) := rfl /-- Continuously extending a curried homotopy to a function from `ℝ` to `C(X, Y)`. -/ def extend (F : homotopy f₀ f₁) : C(ℝ, C(X, Y)) := F.curry.Icc_extend zero_le_one lemma extend_apply_of_le_zero (F : homotopy f₀ f₁) {t : ℝ} (ht : t ≤ 0) (x : X) : F.extend t x = f₀ x := begin rw [←F.apply_zero], exact continuous_map.congr_fun (set.Icc_extend_of_le_left (@zero_le_one ℝ _) F.curry ht) x, end lemma extend_apply_of_one_le (F : homotopy f₀ f₁) {t : ℝ} (ht : 1 ≤ t) (x : X) : F.extend t x = f₁ x := begin rw [←F.apply_one], exact continuous_map.congr_fun (set.Icc_extend_of_right_le (@zero_le_one ℝ _) F.curry ht) x, end @[simp] lemma extend_apply_coe (F : homotopy f₀ f₁) (t : I) (x : X) : F.extend t x = F (t, x) := continuous_map.congr_fun (set.Icc_extend_coe (@zero_le_one ℝ _) F.curry t) x @[simp] lemma extend_apply_of_mem_I (F : homotopy f₀ f₁) {t : ℝ} (ht : t ∈ I) (x : X) : F.extend t x = F (⟨t, ht⟩, x) := continuous_map.congr_fun (set.Icc_extend_of_mem (@zero_le_one ℝ _) F.curry ht) x lemma congr_fun {F G : homotopy f₀ f₁} (h : F = G) (x : I × X) : F x = G x := continuous_map.congr_fun (congr_arg _ h) x lemma congr_arg (F : homotopy f₀ f₁) {x y : I × X} (h : x = y) : F x = F y := F.to_continuous_map.congr_arg h end /-- Given a continuous function `f`, we can define a `homotopy f f` by `F (t, x) = f x` -/ @[simps] def refl (f : C(X, Y)) : homotopy f f := { to_fun := λ x, f x.2, to_fun_zero := λ _, rfl, to_fun_one := λ _, rfl } instance : inhabited (homotopy (continuous_map.id : C(X, X)) continuous_map.id) := ⟨homotopy.refl continuous_map.id⟩ /-- Given a `homotopy f₀ f₁`, we can define a `homotopy f₁ f₀` by reversing the homotopy. -/ @[simps] def symm {f₀ f₁ : C(X, Y)} (F : homotopy f₀ f₁) : homotopy f₁ f₀ := { to_fun := λ x, F (σ x.1, x.2), to_fun_zero := by norm_num, to_fun_one := by norm_num } @[simp] lemma symm_symm {f₀ f₁ : C(X, Y)} (F : homotopy f₀ f₁) : F.symm.symm = F := by { ext, simp } /-- Given `homotopy f₀ f₁` and `homotopy f₁ f₂`, we can define a `homotopy f₀ f₂` by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]`. -/ def trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) : homotopy f₀ f₂ := { to_fun := λ x, if (x.1 : ℝ) ≤ 1/2 then F.extend (2 * x.1) x.2 else G.extend (2 * x.1 - 1) x.2, continuous_to_fun := begin refine continuous_if_le (continuous_induced_dom.comp continuous_fst) continuous_const (F.continuous.comp (by continuity)).continuous_on (G.continuous.comp (by continuity)).continuous_on _, rintros x hx, norm_num [hx], end, to_fun_zero := λ x, by norm_num, to_fun_one := λ x, by norm_num } lemma trans_apply {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) (x : I × X) : (F.trans G) x = if h : (x.1 : ℝ) ≤ 1/2 then F (⟨2 * x.1, (unit_interval.mul_pos_mem_iff zero_lt_two).2 ⟨x.1.2.1, h⟩⟩, x.2) else G (⟨2 * x.1 - 1, unit_interval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.1.2.2⟩⟩, x.2) := show ite _ _ _ = _, by split_ifs; { rw [extend, continuous_map.coe_Icc_extend, set.Icc_extend_of_mem], refl } lemma symm_trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy f₀ f₁) (G : homotopy f₁ f₂) : (F.trans G).symm = G.symm.trans F.symm := begin ext x, simp only [symm_apply, trans_apply], split_ifs with h₁ h₂, { change (x.1 : ℝ) ≤ _ at h₂, change (1 : ℝ) - x.1 ≤ _ at h₁, have ht : (x.1 : ℝ) = 1/2, { linarith }, norm_num [ht] }, { congr' 2, apply subtype.ext, simp only [unit_interval.coe_symm_eq, subtype.coe_mk], linarith }, { congr' 2, apply subtype.ext, simp only [unit_interval.coe_symm_eq, subtype.coe_mk], linarith }, { change ¬ (x.1 : ℝ) ≤ _ at h, change ¬ (1 : ℝ) - x.1 ≤ _ at h₁, exfalso, linarith } end /-- Casting a `homotopy f₀ f₁` to a `homotopy g₀ g₁` where `f₀ = g₀` and `f₁ = g₁`. -/ @[simps] def cast {f₀ f₁ g₀ g₁ : C(X, Y)} (F : homotopy f₀ f₁) (h₀ : f₀ = g₀) (h₁ : f₁ = g₁) : homotopy g₀ g₁ := { to_fun := F, to_fun_zero := by simp [←h₀], to_fun_one := by simp [←h₁] } /-- If we have a `homotopy f₀ f₁` and a `homotopy g₀ g₁`, then we can compose them and get a `homotopy (g₀.comp f₀) (g₁.comp f₁)`. -/ @[simps] def hcomp {f₀ f₁ : C(X, Y)} {g₀ g₁ : C(Y, Z)} (F : homotopy f₀ f₁) (G : homotopy g₀ g₁) : homotopy (g₀.comp f₀) (g₁.comp f₁) := { to_fun := λ x, G (x.1, F x), to_fun_zero := by simp, to_fun_one := by simp } end homotopy /-- Given continuous maps `f₀` and `f₁`, we say `f₀` and `f₁` are homotopic if there exists a `homotopy f₀ f₁`. -/ def homotopic (f₀ f₁ : C(X, Y)) : Prop := nonempty (homotopy f₀ f₁) namespace homotopic @[refl] lemma refl (f : C(X, Y)) : homotopic f f := ⟨homotopy.refl f⟩ @[symm] lemma symm ⦃f g : C(X, Y)⦄ (h : homotopic f g) : homotopic g f := ⟨h.some.symm⟩ @[trans] lemma trans ⦃f g h : C(X, Y)⦄ (h₀ : homotopic f g) (h₁ : homotopic g h) : homotopic f h := ⟨h₀.some.trans h₁.some⟩ lemma hcomp {f₀ f₁ : C(X, Y)} {g₀ g₁ : C(Y, Z)} (h₀ : homotopic f₀ f₁) (h₁ : homotopic g₀ g₁) : homotopic (g₀.comp f₀) (g₁.comp f₁) := ⟨h₀.some.hcomp h₁.some⟩ lemma equivalence : equivalence (@homotopic X Y _ _) := ⟨refl, symm, trans⟩ end homotopic /-- The type of homotopies between `f₀ f₁ : C(X, Y)`, where the intermediate maps satisfy the predicate `P : C(X, Y) → Prop` -/ structure homotopy_with (f₀ f₁ : C(X, Y)) (P : C(X, Y) → Prop) extends homotopy f₀ f₁ := (prop' : ∀ t, P ⟨λ x, to_fun (t, x), continuous.comp continuous_to_fun (continuous_const.prod_mk continuous_id')⟩) namespace homotopy_with section variables {f₀ f₁ : C(X, Y)} {P : C(X, Y) → Prop} instance : has_coe_to_fun (homotopy_with f₀ f₁ P) (λ _, I × X → Y) := ⟨λ F, F.to_fun⟩ lemma coe_fn_injective : @function.injective (homotopy_with f₀ f₁ P) (I × X → Y) coe_fn := begin rintros ⟨⟨⟨F, _⟩, _⟩, _⟩ ⟨⟨⟨G, _⟩, _⟩, _⟩ h, congr' 3, end @[ext] lemma ext {F G : homotopy_with f₀ f₁ P} (h : ∀ x, F x = G x) : F = G := coe_fn_injective $ funext h /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (F : homotopy_with f₀ f₁ P) : I × X → Y := F initialize_simps_projections homotopy_with (to_homotopy_to_continuous_map_to_fun -> apply, -to_homotopy_to_continuous_map) @[continuity] protected lemma continuous (F : homotopy_with f₀ f₁ P) : continuous F := F.continuous_to_fun @[simp] lemma apply_zero (F : homotopy_with f₀ f₁ P) (x : X) : F (0, x) = f₀ x := F.to_fun_zero x @[simp] lemma apply_one (F : homotopy_with f₀ f₁ P) (x : X) : F (1, x) = f₁ x := F.to_fun_one x @[simp] lemma coe_to_continuous_map (F : homotopy_with f₀ f₁ P) : ⇑F.to_continuous_map = F := rfl @[simp] lemma coe_to_homotopy (F : homotopy_with f₀ f₁ P) : ⇑F.to_homotopy = F := rfl lemma prop (F : homotopy_with f₀ f₁ P) (t : I) : P (F.to_homotopy.curry t) := F.prop' t lemma extend_prop (F : homotopy_with f₀ f₁ P) (t : ℝ) : P (F.to_homotopy.extend t) := begin by_cases ht₀ : 0 ≤ t, { by_cases ht₁ : t ≤ 1, { convert F.prop ⟨t, ht₀, ht₁⟩, ext, rw [F.to_homotopy.extend_apply_of_mem_I ⟨ht₀, ht₁⟩, F.to_homotopy.curry_apply] }, { convert F.prop 1, ext, rw [F.to_homotopy.extend_apply_of_one_le (le_of_not_le ht₁), F.to_homotopy.curry_apply, F.to_homotopy.apply_one] } }, { convert F.prop 0, ext, rw [F.to_homotopy.extend_apply_of_le_zero (le_of_not_le ht₀), F.to_homotopy.curry_apply, F.to_homotopy.apply_zero] } end end variable {P : C(X, Y) → Prop} /-- Given a continuous function `f`, and a proof `h : P f`, we can define a `homotopy_with f f P` by `F (t, x) = f x` -/ @[simps] def refl (f : C(X, Y)) (hf : P f) : homotopy_with f f P := { prop' := λ t, by { convert hf, cases f, refl }, ..homotopy.refl f } instance : inhabited (homotopy_with (continuous_map.id : C(X, X)) continuous_map.id (λ f, true)) := ⟨homotopy_with.refl _ trivial⟩ /-- Given a `homotopy_with f₀ f₁ P`, we can define a `homotopy_with f₁ f₀ P` by reversing the homotopy. -/ @[simps] def symm {f₀ f₁ : C(X, Y)} (F : homotopy_with f₀ f₁ P) : homotopy_with f₁ f₀ P := { prop' := λ t, by simpa using F.prop (σ t), ..F.to_homotopy.symm } @[simp] lemma symm_symm {f₀ f₁ : C(X, Y)} (F : homotopy_with f₀ f₁ P) : F.symm.symm = F := ext $ homotopy.congr_fun $ homotopy.symm_symm _ /-- Given `homotopy_with f₀ f₁ P` and `homotopy_with f₁ f₂ P`, we can define a `homotopy_with f₀ f₂ P` by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]`. -/ def trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy_with f₀ f₁ P) (G : homotopy_with f₁ f₂ P) : homotopy_with f₀ f₂ P := { prop' := λ t, begin simp only [homotopy.trans], change P ⟨λ _, ite ((t : ℝ) ≤ _) _ _, _⟩, split_ifs, { exact F.extend_prop _ }, { exact G.extend_prop _ } end, ..F.to_homotopy.trans G.to_homotopy } lemma trans_apply {f₀ f₁ f₂ : C(X, Y)} (F : homotopy_with f₀ f₁ P) (G : homotopy_with f₁ f₂ P) (x : I × X) : (F.trans G) x = if h : (x.1 : ℝ) ≤ 1/2 then F (⟨2 * x.1, (unit_interval.mul_pos_mem_iff zero_lt_two).2 ⟨x.1.2.1, h⟩⟩, x.2) else G (⟨2 * x.1 - 1, unit_interval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.1.2.2⟩⟩, x.2) := homotopy.trans_apply _ _ _ lemma symm_trans {f₀ f₁ f₂ : C(X, Y)} (F : homotopy_with f₀ f₁ P) (G : homotopy_with f₁ f₂ P) : (F.trans G).symm = G.symm.trans F.symm := ext $ homotopy.congr_fun $ homotopy.symm_trans _ _ /-- Casting a `homotopy_with f₀ f₁ P` to a `homotopy_with g₀ g₁ P` where `f₀ = g₀` and `f₁ = g₁`. -/ @[simps] def cast {f₀ f₁ g₀ g₁ : C(X, Y)} (F : homotopy_with f₀ f₁ P) (h₀ : f₀ = g₀) (h₁ : f₁ = g₁) : homotopy_with g₀ g₁ P := { prop' := F.prop, ..F.to_homotopy.cast h₀ h₁ } end homotopy_with /-- Given continuous maps `f₀` and `f₁`, we say `f₀` and `f₁` are homotopic with respect to the predicate `P` if there exists a `homotopy_with f₀ f₁ P`. -/ def homotopic_with (f₀ f₁ : C(X, Y)) (P : C(X, Y) → Prop) : Prop := nonempty (homotopy_with f₀ f₁ P) namespace homotopic_with variable {P : C(X, Y) → Prop} @[refl] lemma refl (f : C(X, Y)) (hf : P f) : homotopic_with f f P := ⟨homotopy_with.refl f hf⟩ @[symm] lemma symm ⦃f g : C(X, Y)⦄ (h : homotopic_with f g P) : homotopic_with g f P := ⟨h.some.symm⟩ @[trans] lemma trans ⦃f g h : C(X, Y)⦄ (h₀ : homotopic_with f g P) (h₁ : homotopic_with g h P) : homotopic_with f h P := ⟨h₀.some.trans h₁.some⟩ end homotopic_with /-- A `homotopy_rel f₀ f₁ S` is a homotopy between `f₀` and `f₁` which is fixed on the points in `S`. -/ abbreviation homotopy_rel (f₀ f₁ : C(X, Y)) (S : set X) := homotopy_with f₀ f₁ (λ f, ∀ x ∈ S, f x = f₀ x ∧ f x = f₁ x) namespace homotopy_rel section variables {f₀ f₁ : C(X, Y)} {S : set X} lemma eq_fst (F : homotopy_rel f₀ f₁ S) (t : I) {x : X} (hx : x ∈ S) : F (t, x) = f₀ x := (F.prop t x hx).1 lemma eq_snd (F : homotopy_rel f₀ f₁ S) (t : I) {x : X} (hx : x ∈ S) : F (t, x) = f₁ x := (F.prop t x hx).2 lemma fst_eq_snd (F : homotopy_rel f₀ f₁ S) {x : X} (hx : x ∈ S) : f₀ x = f₁ x := F.eq_fst 0 hx ▸ F.eq_snd 0 hx end variables {f₀ f₁ f₂ : C(X, Y)} {S : set X} /-- Given a map `f : C(X, Y)` and a set `S`, we can define a `homotopy_rel f f S` by setting `F (t, x) = f x` for all `t`. This is defined using `homotopy_with.refl`, but with the proof filled in. -/ @[simps] def refl (f : C(X, Y)) (S : set X) : homotopy_rel f f S := homotopy_with.refl f (λ x hx, ⟨rfl, rfl⟩) /-- Given a `homotopy_rel f₀ f₁ S`, we can define a `homotopy_rel f₁ f₀ S` by reversing the homotopy. -/ @[simps] def symm (F : homotopy_rel f₀ f₁ S) : homotopy_rel f₁ f₀ S := { prop' := λ t x hx, by simp [F.eq_snd _ hx, F.fst_eq_snd hx], ..homotopy_with.symm F } @[simp] lemma symm_symm (F : homotopy_rel f₀ f₁ S) : F.symm.symm = F := homotopy_with.symm_symm F /-- Given `homotopy_rel f₀ f₁ S` and `homotopy_rel f₁ f₂ S`, we can define a `homotopy_rel f₀ f₂ S` by putting the first homotopy on `[0, 1/2]` and the second on `[1/2, 1]`. -/ def trans (F : homotopy_rel f₀ f₁ S) (G : homotopy_rel f₁ f₂ S) : homotopy_rel f₀ f₂ S := { prop' := λ t, begin intros x hx, simp only [homotopy.trans], change (⟨λ _, ite ((t : ℝ) ≤ _) _ _, _⟩ : C(X, Y)) _ = _ ∧ _ = _, split_ifs, { simp [(homotopy_with.extend_prop F (2 * t) x hx).1, F.fst_eq_snd hx, G.fst_eq_snd hx] }, { simp [(homotopy_with.extend_prop G (2 * t - 1) x hx).1, F.fst_eq_snd hx, G.fst_eq_snd hx] }, end, ..homotopy.trans F.to_homotopy G.to_homotopy } lemma trans_apply (F : homotopy_rel f₀ f₁ S) (G : homotopy_rel f₁ f₂ S) (x : I × X) : (F.trans G) x = if h : (x.1 : ℝ) ≤ 1/2 then F (⟨2 * x.1, (unit_interval.mul_pos_mem_iff zero_lt_two).2 ⟨x.1.2.1, h⟩⟩, x.2) else G (⟨2 * x.1 - 1, unit_interval.two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, x.1.2.2⟩⟩, x.2) := homotopy.trans_apply _ _ _ lemma symm_trans (F : homotopy_rel f₀ f₁ S) (G : homotopy_rel f₁ f₂ S) : (F.trans G).symm = G.symm.trans F.symm := homotopy_with.ext $ homotopy.congr_fun $ homotopy.symm_trans _ _ /-- Casting a `homotopy_rel f₀ f₁ S` to a `homotopy_rel g₀ g₁ S` where `f₀ = g₀` and `f₁ = g₁`. -/ @[simps] def cast {f₀ f₁ g₀ g₁ : C(X, Y)} (F : homotopy_rel f₀ f₁ S) (h₀ : f₀ = g₀) (h₁ : f₁ = g₁) : homotopy_rel g₀ g₁ S := { prop' := λ t x hx, by { simpa [←h₀, ←h₁] using F.prop t x hx }, ..homotopy.cast F.to_homotopy h₀ h₁ } end homotopy_rel /-- Given continuous maps `f₀` and `f₁`, we say `f₀` and `f₁` are homotopic relative to a set `S` if there exists a `homotopy_rel f₀ f₁ S`. -/ def homotopic_rel (f₀ f₁ : C(X, Y)) (S : set X) : Prop := nonempty (homotopy_rel f₀ f₁ S) namespace homotopic_rel variable {S : set X} @[refl] lemma refl (f : C(X, Y)) : homotopic_rel f f S := ⟨homotopy_rel.refl f S⟩ @[symm] lemma symm ⦃f g : C(X, Y)⦄ (h : homotopic_rel f g S) : homotopic_rel g f S := ⟨h.some.symm⟩ @[trans] lemma trans ⦃f g h : C(X, Y)⦄ (h₀ : homotopic_rel f g S) (h₁ : homotopic_rel g h S) : homotopic_rel f h S := ⟨h₀.some.trans h₁.some⟩ lemma equivalence : equivalence (λ f g : C(X, Y), homotopic_rel f g S) := ⟨refl, symm, trans⟩ end homotopic_rel end continuous_map
80450eb1057e26c402777066d642ead652aa0d8c
38a6d5def645a1887e1306ceb4da06ff71452096
/common/shannon_theory.lean
80506d23346e39fe7ea990fb3722de00dc581fc1
[]
no_license
QTM3x/Quantum-Internet
bcc2d61e2ae7233bb2b369fedaed22a1feb6fba1
f90e09fb6c03d35043654d8b1bec1c63d6012268
refs/heads/master
1,609,224,401,937
1,599,911,583,000
1,599,911,583,000
238,495,221
45
33
null
1,603,625,079,000
1,580,919,815,000
Jupyter Notebook
UTF-8
Lean
false
false
3,496
lean
import algebra.big_operators import data.real.basic import tactic import analysis.special_functions.exp_log import measure_theory.probability_mass_function -- open_locale big_operators -- this enables the notation noncomputable theory -- without this there is an error ---- HELPER LEMMAS lemma multiset.map_repeat {α β : Sort*} (f : α → β) (x : α) (n : ℕ) : (multiset.repeat x n).map f = multiset.repeat (f x) n := nat.rec_on n rfl $ λ n ih, by simp_rw [multiset.repeat_succ, multiset.map_cons, ih] theorem prod_ne_zero' {R : Type*} [integral_domain R] {m : multiset R} : (∀ x ∈ m, (x : _) ≠ 0) → m.prod ≠ 0 := begin intros, sorry -- multiset.induction_on m (λ _, one_ne_zero) $ λ hd tl ih H, -- by { rw multiset.forall_mem_cons at H, rw multiset.prod_cons, exact mul_ne_zero H.1 (ih H.2) } end lemma multiset.sum_geq_zero {m : multiset ℝ} : (∀ x ∈ m, (x : _) ≥ 0) → m.sum ≥ 0 := begin sorry end ---- SHANNON ENTROPY /- Definition (Shannon entropy): The entropy of a discrete random variable X with probability distribution p_X(x) -/ def shannon_entropy (X : multiset ℝ) : ℝ := (multiset.map (λ (x : ℝ), x * real.log(1/x)) X).sum /- Theorem (non-negativity): Shannon entropy is non-negative for any discrete random variable X. "It is perhaps intuitive that the entropy should be non-negative because non-negativity implies that we always learn some number of bits upon learning random variable X (if we already know beforehand what the outcome of a random experiment will be, then we learn zero bits of information once we perform it). In a classical sense, we can never learn a negative amount of information!" https://arxiv.org/pdf/1106.1445.pdf -/ theorem shannon_entropy_nonneg : ∀ (X : multiset ℝ) {hX : ∀ (x : ℝ), x ∈ X → x ≤ 1 ∧ x > 0}, shannon_entropy(X) ≥ 0 := begin intros, unfold shannon_entropy, -- Each x * log(1/x) term in the sum -- is non-negative because for x < 1 -- log(1/x) is positive and log(1/0) is -- defined to be 0. let X_image := multiset.map (λ (x : ℝ), x * real.log(1/x)) X, have h : ∀ x ∈ X_image, (x : _) ≥ 0, { intros x hx, sorry, }, -- And the sum of a set of nonnegative numbers is nonnegative. exact multiset.sum_geq_zero h, end /- Theorem (concavity): Shannon entropy is concave in the probability density. -/ theorem concavity := sorry /- Definition (deterministic random variable): -/ def is_deterministic := sorry /- Theorem (minimum value): Shannon entropy vanishes if and only if X is a deterministic variable. -/ theorem shannon_entropy_minimum_value : ∀ (X : multiset ℝ), shannon_entropy(X) = 0 ↔ is_deterministic X := begin sorry end /- Definition (uniform random variable): a random variable whose probabilities are equal to 1/n, where n is the number of symbols that the random variable can assume. -/ def is_uniform_rnd_var (X : multiset ℝ) : Prop := X = multiset.repeat (1/X.card) X.card /- Theorem: The Shannon entropy of a uniform random variable is log(n). -/ theorem shannon_entropy_uniform_rdm_var (X : multiset ℝ) (hX : X.card ≠ 0) : is_uniform_rnd_var(X) → shannon_entropy X = real.log(X.card) := begin intro, unfold is_uniform_rnd_var at a, rw a, simp, unfold shannon_entropy, rw multiset.map_repeat, simp, rw ← mul_assoc, rw mul_inv_cancel, simp, norm_cast, exact hX, end
d4a0d7ad788498bd3c2d62b8e04df3764528dd5f
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/category_theory/endomorphism.lean
fc3587a693dab9ec3cba1bdc8c5a3fb9041330b1
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
2,816
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Scott Morrison, Simon Hudon Definition and basic properties of endomorphisms and automorphisms of an object in a category. -/ import category_theory.category category_theory.isomorphism category_theory.groupoid category_theory.functor import algebra.group.units data.equiv.algebra universes v v' u u' namespace category_theory /-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `function.comp`, not with `category.comp`. -/ def End {C : Type u} [𝒞_struct : category_struct.{v} C] (X : C) := X ⟶ X namespace End section struct variables {C : Type u} [𝒞_struct : category_struct.{v} C] (X : C) include 𝒞_struct instance has_one : has_one (End X) := ⟨𝟙 X⟩ /-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/ instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩ variable {X} @[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl @[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl end struct /-- Endomorphisms of an object form a monoid -/ instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) := { mul_one := category.id_comp C, one_mul := category.comp_id C, mul_assoc := λ x y z, (category.assoc C z y x).symm, ..End.has_mul X, ..End.has_one X } /-- In a groupoid, endomorphisms form a group -/ instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) := { mul_left_inv := groupoid.comp_inv C, inv := groupoid.inv, ..End.monoid } end End variables {C : Type u} [𝒞 : category.{v} C] (X : C) include 𝒞 def Aut (X : C) := X ≅ X attribute [extensionality Aut] iso.ext namespace Aut instance: group (Aut X) := by refine { one := iso.refl X, inv := iso.symm, mul := flip iso.trans, .. } ; dunfold flip; obviously def units_End_eqv_Aut : units (End X) ≃* Aut X := { to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, map_mul' := λ f g, by rcases f; rcases g; refl } end Aut namespace functor variables {D : Type u'} [𝒟 : category.{v'} D] (f : C ⥤ D) (X) include 𝒟 /-- `f.map` as a monoid hom between endomorphism monoids. -/ def map_End : End X →* End (f.obj X) := { to_fun := functor.map f, map_mul' := λ x y, f.map_comp y x, map_one' := f.map_id X } /-- `f.map_iso` as a group hom between automorphism groups. -/ def map_Aut : Aut X →* Aut (f.obj X) := { to_fun := f.map_iso, map_mul' := λ x y, f.map_iso_trans y x, map_one' := f.map_iso_refl X } end functor end category_theory
c74e21e22956d6ac8eba1dc917eb20e7efb3da0e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/totient_auto.lean
e769f2fd0f9ce4400a4332ac05a30760f8c13a0c
[]
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
1,018
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.big_operators.basic import Mathlib.PostPort namespace Mathlib namespace nat /-- Euler's totient function. This counts the number of positive integers less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := finset.card (finset.filter (coprime n) (finset.range n)) @[simp] theorem totient_zero : totient 0 = 0 := rfl theorem totient_le (n : ℕ) : totient n ≤ n := trans_rel_left LessEq (finset.card_le_of_subset (finset.filter_subset (coprime n) (finset.range n))) (finset.card_range n) theorem totient_pos {n : ℕ} : 0 < n → 0 < totient n := sorry theorem sum_totient (n : ℕ) : (finset.sum (finset.filter (fun (_x : ℕ) => _x ∣ n) (finset.range (Nat.succ n))) fun (m : ℕ) => totient m) = n := sorry end Mathlib
370ecc904eebaffa4b1f8833a0ae0bd26c3f0f7e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/special_functions/integrals.lean
392fffb9c7455074fcca34f5dd4388053eade7cb
[ "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
25,925
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import measure_theory.integral.interval_integral import analysis.special_functions.trigonometric.arctan_deriv /-! # Integration of specific interval integrals This file contains proofs of the integrals of various specific functions. This includes: * Integrals of simple functions, such as `id`, `pow`, `inv`, `exp`, `log` * Integrals of some trigonometric functions, such as `sin`, `cos`, `1 / (1 + x^2)` * The integral of `cos x ^ 2 - sin x ^ 2` * Reduction formulae for the integrals of `sin x ^ n` and `cos x ^ n` for `n ≥ 2` * The computation of `∫ x in 0..π, sin x ^ n` as a product for even and odd `n` (used in proving the Wallis product for pi) * Integrals of the form `sin x ^ m * cos x ^ n` With these lemmas, many simple integrals can be computed by `simp` or `norm_num`. See `test/integration.lean` for specific examples. This file also contains some facts about the interval integrability of specific functions. This file is still being developed. ## Tags integrate, integration, integrable, integrability -/ open real nat set finset open_locale real big_operators interval variables {a b : ℝ} (n : ℕ) namespace interval_integral open measure_theory variables {f : ℝ → ℝ} {μ ν : measure ℝ} [is_locally_finite_measure μ] (c d : ℝ) /-! ### Interval integrability -/ @[simp] lemma interval_integrable_pow : interval_integrable (λ x, x^n) μ a b := (continuous_pow n).interval_integrable a b lemma interval_integrable_zpow {n : ℤ} (h : 0 ≤ n ∨ (0 : ℝ) ∉ [a, b]) : interval_integrable (λ x, x ^ n) μ a b := (continuous_on_id.zpow₀ n $ λ x hx, h.symm.imp (ne_of_mem_of_not_mem hx) id).interval_integrable lemma interval_integrable_rpow {r : ℝ} (h : 0 ≤ r ∨ (0 : ℝ) ∉ [a, b]) : interval_integrable (λ x, x ^ r) μ a b := (continuous_on_id.rpow_const $ λ x hx, h.symm.imp (ne_of_mem_of_not_mem hx) id).interval_integrable /-- Alternative version with a weaker hypothesis on `r`, but assuming the measure is volume. -/ lemma interval_integrable_rpow' {r : ℝ} (h : -1 < r) : interval_integrable (λ x, x ^ r) volume a b := begin suffices : ∀ (c : ℝ), interval_integrable (λ x, x ^ r) volume 0 c, { exact interval_integrable.trans (this a).symm (this b) }, have : ∀ (c : ℝ), (0 ≤ c) → interval_integrable (λ x, x ^ r) volume 0 c, { intros c hc, rw [interval_integrable_iff, interval_oc_of_le hc], have hderiv : ∀ x ∈ Ioo 0 c, has_deriv_at (λ x : ℝ, x ^ (r + 1) / (r + 1)) (x ^ r) x, { intros x hx, convert (real.has_deriv_at_rpow_const (or.inl hx.1.ne')).div_const (r + 1), field_simp [(by linarith : r + 1 ≠ 0)], ring, }, apply integrable_on_deriv_of_nonneg hc _ hderiv, { intros x hx, apply rpow_nonneg_of_nonneg hx.1.le, }, { refine (continuous_on_id.rpow_const _).div_const, intros x hx, right, linarith } }, intro c, rcases le_total 0 c with hc|hc, { exact this c hc }, { rw [interval_integrable.iff_comp_neg, neg_zero], have m := (this (-c) (by linarith)).smul (cos (r * π)), rw interval_integrable_iff at m ⊢, refine m.congr_fun _ measurable_set_Ioc, intros x hx, rw interval_oc_of_le (by linarith : 0 ≤ -c) at hx, simp only [pi.smul_apply, algebra.id.smul_eq_mul, log_neg_eq_log, mul_comm, rpow_def_of_pos hx.1, rpow_def_of_neg (by linarith [hx.1] : -x < 0)], } end lemma interval_integrable_cpow {r : ℂ} (ha : 0 < a) (hb : 0 < b) : interval_integrable (λ x : ℝ, (x : ℂ) ^ r) volume a b := begin refine (complex.continuous_of_real.continuous_on.cpow_const _).interval_integrable, intros c hc, left, exact_mod_cast lt_of_lt_of_le (lt_min ha hb) hc.left, end @[simp] lemma interval_integrable_id : interval_integrable (λ x, x) μ a b := continuous_id.interval_integrable a b @[simp] lemma interval_integrable_const : interval_integrable (λ x, c) μ a b := continuous_const.interval_integrable a b @[simp] lemma interval_integrable.const_mul (h : interval_integrable f ν a b) : interval_integrable (λ x, c * f x) ν a b := by convert h.smul c @[simp] lemma interval_integrable.mul_const (h : interval_integrable f ν a b) : interval_integrable (λ x, f x * c) ν a b := by simp only [mul_comm, interval_integrable.const_mul c h] @[simp] lemma interval_integrable.div (h : interval_integrable f ν a b) : interval_integrable (λ x, f x / c) ν a b := interval_integrable.mul_const c⁻¹ h lemma interval_integrable_one_div (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) (hf : continuous_on f [a, b]) : interval_integrable (λ x, 1 / f x) μ a b := (continuous_on_const.div hf h).interval_integrable @[simp] lemma interval_integrable_inv (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) (hf : continuous_on f [a, b]) : interval_integrable (λ x, (f x)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div h hf @[simp] lemma interval_integrable_exp : interval_integrable exp μ a b := continuous_exp.interval_integrable a b @[simp] lemma interval_integrable.log (hf : continuous_on f [a, b]) (h : ∀ x : ℝ, x ∈ [a, b] → f x ≠ 0) : interval_integrable (λ x, log (f x)) μ a b := (continuous_on.log hf h).interval_integrable @[simp] lemma interval_integrable_log (h : (0:ℝ) ∉ [a, b]) : interval_integrable log μ a b := interval_integrable.log continuous_on_id $ λ x hx, ne_of_mem_of_not_mem hx h @[simp] lemma interval_integrable_sin : interval_integrable sin μ a b := continuous_sin.interval_integrable a b @[simp] lemma interval_integrable_cos : interval_integrable cos μ a b := continuous_cos.interval_integrable a b lemma interval_integrable_one_div_one_add_sq : interval_integrable (λ x : ℝ, 1 / (1 + x^2)) μ a b := begin refine (continuous_const.div _ (λ x, _)).interval_integrable a b, { continuity }, { nlinarith }, end @[simp] lemma interval_integrable_inv_one_add_sq : interval_integrable (λ x : ℝ, (1 + x^2)⁻¹) μ a b := by simpa only [one_div] using interval_integrable_one_div_one_add_sq /-! ### Integrals of the form `c * ∫ x in a..b, f (c * x + d)` -/ @[simp] lemma mul_integral_comp_mul_right : c * ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := smul_integral_comp_mul_right f c @[simp] lemma mul_integral_comp_mul_left : c * ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := smul_integral_comp_mul_left f c @[simp] lemma inv_mul_integral_comp_div : c⁻¹ * ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := inv_smul_integral_comp_div f c @[simp] lemma mul_integral_comp_mul_add : c * ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := smul_integral_comp_mul_add f c d @[simp] lemma mul_integral_comp_add_mul : c * ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := smul_integral_comp_add_mul f c d @[simp] lemma inv_mul_integral_comp_div_add : c⁻¹ * ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := inv_smul_integral_comp_div_add f c d @[simp] lemma inv_mul_integral_comp_add_div : c⁻¹ * ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := inv_smul_integral_comp_add_div f c d @[simp] lemma mul_integral_comp_mul_sub : c * ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := smul_integral_comp_mul_sub f c d @[simp] lemma mul_integral_comp_sub_mul : c * ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := smul_integral_comp_sub_mul f c d @[simp] lemma inv_mul_integral_comp_div_sub : c⁻¹ * ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := inv_smul_integral_comp_div_sub f c d @[simp] lemma inv_mul_integral_comp_sub_div : c⁻¹ * ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := inv_smul_integral_comp_sub_div f c d end interval_integral open interval_integral /-! ### Integrals of simple functions -/ lemma integral_rpow {r : ℝ} (h : -1 < r ∨ (r ≠ -1 ∧ (0 : ℝ) ∉ [a, b])) : ∫ x in a..b, x ^ r = (b ^ (r + 1) - a ^ (r + 1)) / (r + 1) := begin rw sub_div, have hderiv : ∀ (x : ℝ), x ≠ 0 → has_deriv_at (λ x : ℝ, x ^ (r + 1) / (r + 1)) (x ^ r) x, { intros x hx, convert (real.has_deriv_at_rpow_const (or.inl hx)).div_const (r + 1), rw [add_sub_cancel, mul_div_cancel_left], contrapose! h, rw ←eq_neg_iff_add_eq_zero at h, rw h, tauto, }, cases h, { suffices : ∀ (c : ℝ), ∫ x in 0..c, x ^ r = c ^ (r + 1) / (r + 1), { rw [←integral_add_adjacent_intervals (interval_integrable_rpow' h) (interval_integrable_rpow' h), this b], have t := this a, rw integral_symm at t, apply_fun (λ x, -x) at t, rw neg_neg at t, rw t, ring }, intro c, rcases le_total 0 c with hc|hc, { convert integral_eq_sub_of_has_deriv_at_of_le hc _ (λ x hx, hderiv x hx.1.ne') _, { rw zero_rpow, ring, linarith,}, { apply continuous_at.continuous_on, intros x hx, refine (continuous_at_id.rpow_const _).div_const, right, linarith,}, apply interval_integrable_rpow' h }, { rw integral_symm, symmetry, rw eq_neg_iff_eq_neg, convert integral_eq_sub_of_has_deriv_at_of_le hc _ (λ x hx, hderiv x hx.2.ne) _, { rw zero_rpow, ring, linarith }, { apply continuous_at.continuous_on, intros x hx, refine (continuous_at_id.rpow_const _).div_const, right, linarith }, apply interval_integrable_rpow' h, } }, { have hderiv' : ∀ (x : ℝ), x ∈ [a, b] → has_deriv_at (λ x : ℝ, x ^ (r + 1) / (r + 1)) (x ^ r) x, { intros x hx, apply hderiv x, exact ne_of_mem_of_not_mem hx h.2 }, exact integral_eq_sub_of_has_deriv_at hderiv' (interval_integrable_rpow (or.inr h.2)) }, end lemma integral_cpow {r : ℂ} (ha : 0 < a) (hb : 0 < b) (hr : r ≠ -1) : ∫ (x : ℝ) in a..b, (x : ℂ) ^ r = (b ^ (r + 1) - a ^ (r + 1)) / (r + 1) := begin suffices : ∀ x ∈ set.interval a b, has_deriv_at (λ x : ℝ, (x : ℂ) ^ (r + 1) / (r + 1)) (x ^ r) x, { rw sub_div, exact integral_eq_sub_of_has_deriv_at this (interval_integrable_cpow ha hb) }, intros x hx, suffices : has_deriv_at (λ z : ℂ, z ^ (r + 1) / (r + 1)) (x ^ r) x, { simpa using has_deriv_at.comp x this complex.of_real_clm.has_deriv_at }, have hx' : 0 < (x : ℂ).re ∨ (x : ℂ).im ≠ 0, { left, norm_cast, calc 0 < min a b : lt_min ha hb ... ≤ x : hx.left, }, convert ((has_deriv_at_id (x:ℂ)).cpow_const hx').div_const (r + 1), simp only [id.def, add_sub_cancel, mul_one], rw [mul_comm, mul_div_cancel], contrapose! hr, rwa add_eq_zero_iff_eq_neg at hr, end lemma integral_zpow {n : ℤ} (h : 0 ≤ n ∨ n ≠ -1 ∧ (0 : ℝ) ∉ [a, b]) : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) := begin replace h : -1 < (n : ℝ) ∨ (n : ℝ) ≠ -1 ∧ (0 : ℝ) ∉ [a, b], by exact_mod_cast h, exact_mod_cast integral_rpow h, end @[simp] lemma integral_pow : ∫ x in a..b, x ^ n = (b ^ (n + 1) - a ^ (n + 1)) / (n + 1) := by simpa using integral_zpow (or.inl (int.coe_nat_nonneg n)) /-- Integral of `|x - a| ^ n` over `Ι a b`. This integral appears in the proof of the Picard-Lindelöf/Cauchy-Lipschitz theorem. -/ lemma integral_pow_abs_sub_interval_oc : ∫ x in Ι a b, |x - a| ^ n = |b - a| ^ (n + 1) / (n + 1) := begin cases le_or_lt a b with hab hab, { calc ∫ x in Ι a b, |x - a| ^ n = ∫ x in a..b, |x - a| ^ n : by rw [interval_oc_of_le hab, ← integral_of_le hab] ... = ∫ x in 0..(b - a), x ^ n : begin simp only [integral_comp_sub_right (λ x, |x| ^ n), sub_self], refine integral_congr (λ x hx, congr_arg2 has_pow.pow (abs_of_nonneg $ _) rfl), rw interval_of_le (sub_nonneg.2 hab) at hx, exact hx.1 end ... = |b - a| ^ (n + 1) / (n + 1) : by simp [abs_of_nonneg (sub_nonneg.2 hab)] }, { calc ∫ x in Ι a b, |x - a| ^ n = ∫ x in b..a, |x - a| ^ n : by rw [interval_oc_of_lt hab, ← integral_of_le hab.le] ... = ∫ x in b - a..0, (-x) ^ n : begin simp only [integral_comp_sub_right (λ x, |x| ^ n), sub_self], refine integral_congr (λ x hx, congr_arg2 has_pow.pow (abs_of_nonpos $ _) rfl), rw interval_of_le (sub_nonpos.2 hab.le) at hx, exact hx.2 end ... = |b - a| ^ (n + 1) / (n + 1) : by simp [integral_comp_neg (λ x, x ^ n), abs_of_neg (sub_neg.2 hab)] } end @[simp] lemma integral_id : ∫ x in a..b, x = (b ^ 2 - a ^ 2) / 2 := by simpa using integral_pow 1 @[simp] lemma integral_one : ∫ x in a..b, (1 : ℝ) = b - a := by simp only [mul_one, smul_eq_mul, integral_const] lemma integral_const_on_unit_interval : ∫ x in a..(a + 1), b = b := by simp @[simp] lemma integral_inv (h : (0:ℝ) ∉ [a, b]) : ∫ x in a..b, x⁻¹ = log (b / a) := begin have h' := λ x hx, ne_of_mem_of_not_mem hx h, rw [integral_deriv_eq_sub' _ deriv_log' (λ x hx, differentiable_at_log (h' x hx)) (continuous_on_inv₀.mono $ subset_compl_singleton_iff.mpr h), log_div (h' b right_mem_interval) (h' a left_mem_interval)], end @[simp] lemma integral_inv_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_lt ha hb @[simp] lemma integral_inv_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, x⁻¹ = log (b / a) := integral_inv $ not_mem_interval_of_gt ha hb lemma integral_one_div (h : (0:ℝ) ∉ [a, b]) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv h] lemma integral_one_div_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_pos ha hb] lemma integral_one_div_of_neg (ha : a < 0) (hb : b < 0) : ∫ x : ℝ in a..b, 1/x = log (b / a) := by simp only [one_div, integral_inv_of_neg ha hb] @[simp] lemma integral_exp : ∫ x in a..b, exp x = exp b - exp a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_exp] lemma integral_exp_mul_complex {c : ℂ} (hc : c ≠ 0) : ∫ x in a..b, complex.exp (c * x) = (complex.exp (c * b) - complex.exp (c * a)) / c := begin have D : ∀ (x : ℝ), has_deriv_at (λ (y : ℝ), complex.exp (c * y) / c) (complex.exp (c * x)) x, { intro x, conv { congr, skip, rw ←mul_div_cancel (complex.exp (c * x)) hc, }, convert ((complex.has_deriv_at_exp _).comp x _).div_const c using 1, simpa only [complex.of_real_clm_apply, complex.of_real_one, one_mul, mul_one, mul_comm] using complex.of_real_clm.has_deriv_at.mul_const c }, rw integral_deriv_eq_sub' _ (funext (λ x, (D x).deriv)) (λ x hx, (D x).differentiable_at), { ring_nf }, { apply continuous.continuous_on, continuity,} end @[simp] lemma integral_log (h : (0:ℝ) ∉ [a, b]) : ∫ x in a..b, log x = b * log b - a * log a - b + a := begin obtain ⟨h', heq⟩ := ⟨λ x hx, ne_of_mem_of_not_mem hx h, λ x hx, mul_inv_cancel (h' x hx)⟩, convert integral_mul_deriv_eq_deriv_mul (λ x hx, has_deriv_at_log (h' x hx)) (λ x hx, has_deriv_at_id x) (continuous_on_inv₀.mono $ subset_compl_singleton_iff.mpr h).interval_integrable continuous_on_const.interval_integrable using 1; simp [integral_congr heq, mul_comm, ← sub_add], end @[simp] lemma integral_log_of_pos (ha : 0 < a) (hb : 0 < b) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_lt ha hb @[simp] lemma integral_log_of_neg (ha : a < 0) (hb : b < 0) : ∫ x in a..b, log x = b * log b - a * log a - b + a := integral_log $ not_mem_interval_of_gt ha hb @[simp] lemma integral_sin : ∫ x in a..b, sin x = cos a - cos b := by rw integral_deriv_eq_sub' (λ x, -cos x); norm_num [continuous_on_sin] @[simp] lemma integral_cos : ∫ x in a..b, cos x = sin b - sin a := by rw integral_deriv_eq_sub'; norm_num [continuous_on_cos] lemma integral_cos_sq_sub_sin_sq : ∫ x in a..b, cos x ^ 2 - sin x ^ 2 = sin b * cos b - sin a * cos a := by simpa only [sq, sub_eq_add_neg, neg_mul_eq_mul_neg] using integral_deriv_mul_eq_sub (λ x hx, has_deriv_at_sin x) (λ x hx, has_deriv_at_cos x) continuous_on_cos.interval_integrable continuous_on_sin.neg.interval_integrable @[simp] lemma integral_inv_one_add_sq : ∫ x : ℝ in a..b, (1 + x^2)⁻¹ = arctan b - arctan a := begin simp only [← one_div], refine integral_deriv_eq_sub' _ _ _ (continuous_const.div _ (λ x, _)).continuous_on, { norm_num }, { norm_num }, { continuity }, { nlinarith }, end lemma integral_one_div_one_add_sq : ∫ x : ℝ in a..b, 1 / (1 + x^2) = arctan b - arctan a := by simp only [one_div, integral_inv_one_add_sq] /-! ### Integral of `sin x ^ n` -/ lemma integral_sin_pow_aux : ∫ x in a..b, sin x ^ (n + 2) = sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) := begin let C := sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, sin y ^ (n + 1)) ((n + 1 : ℕ) * cos x * sin x ^ n) x := λ x hx, by simpa only [mul_right_comm] using (has_deriv_at_sin x).pow (n+1), have hv : ∀ x ∈ [a, b], has_deriv_at (-cos) (sin x) x := λ x hx, by simpa only [neg_neg] using (has_deriv_at_cos x).neg, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, sin x ^ (n + 2) = ∫ x in a..b, sin x ^ (n + 1) * sin x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, cos x ^ 2 * sin x ^ n : by simp [H, h, sq] ... = C + (n + 1) * ∫ x in a..b, sin x ^ n - sin x ^ (n + 2) : by simp [cos_sq', sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, sin x ^ n) - (n + 1) * ∫ x in a..b, sin x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `sin x ^ n` for any natural `n ≥ 2`. -/ lemma integral_sin_pow : ∫ x in a..b, sin x ^ (n + 2) = (sin a ^ (n + 1) * cos a - sin b ^ (n + 1) * cos b) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, sin x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_sin_pow_aux n), ring, end @[simp] lemma integral_sin_sq : ∫ x in a..b, sin x ^ 2 = (sin a * cos a - sin b * cos b + b - a) / 2 := by field_simp [integral_sin_pow, add_sub_assoc] theorem integral_sin_pow_odd : ∫ x in 0..π, sin x ^ (2 * n + 1) = 2 * ∏ i in range n, (2 * i + 2) / (2 * i + 3) := begin induction n with k ih, { norm_num }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end theorem integral_sin_pow_even : ∫ x in 0..π, sin x ^ (2 * n) = π * ∏ i in range n, (2 * i + 1) / (2 * i + 2) := begin induction n with k ih, { simp }, rw [prod_range_succ_comm, mul_left_comm, ← ih, mul_succ, integral_sin_pow], norm_cast, simp [-cast_add] with field_simps, end lemma integral_sin_pow_pos : 0 < ∫ x in 0..π, sin x ^ n := begin rcases even_or_odd' n with ⟨k, (rfl | rfl)⟩; simp only [integral_sin_pow_even, integral_sin_pow_odd]; refine mul_pos (by norm_num [pi_pos]) (prod_pos (λ n hn, div_pos _ _)); norm_cast; linarith, end lemma integral_sin_pow_succ_le : ∫ x in 0..π, sin x ^ (n + 1) ≤ ∫ x in 0..π, sin x ^ n := let H := λ x h, pow_le_pow_of_le_one (sin_nonneg_of_mem_Icc h) (sin_le_one x) (n.le_add_right 1) in by refine integral_mono_on pi_pos.le _ _ H; exact (continuous_sin.pow _).interval_integrable 0 π lemma integral_sin_pow_antitone : antitone (λ n : ℕ, ∫ x in 0..π, sin x ^ n) := antitone_nat_of_succ_le integral_sin_pow_succ_le /-! ### Integral of `cos x ^ n` -/ lemma integral_cos_pow_aux : ∫ x in a..b, cos x ^ (n + 2) = cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) := begin let C := cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a, have h : ∀ α β γ : ℝ, α * (β * α * γ) = β * (α * α * γ) := λ α β γ, by ring, have hu : ∀ x ∈ _, has_deriv_at (λ y, cos y ^ (n + 1)) (-(n + 1 : ℕ) * sin x * cos x ^ n) x := λ x hx, by simpa only [mul_right_comm, neg_mul, mul_neg] using (has_deriv_at_cos x).pow (n+1), have hv : ∀ x ∈ [a, b], has_deriv_at sin (cos x) x := λ x hx, has_deriv_at_sin x, have H := integral_mul_deriv_eq_deriv_mul hu hv _ _, calc ∫ x in a..b, cos x ^ (n + 2) = ∫ x in a..b, cos x ^ (n + 1) * cos x : by simp only [pow_succ'] ... = C + (n + 1) * ∫ x in a..b, sin x ^ 2 * cos x ^ n : by simp [H, h, sq, -neg_add_rev] ... = C + (n + 1) * ∫ x in a..b, cos x ^ n - cos x ^ (n + 2) : by simp [sin_sq, sub_mul, ← pow_add, add_comm] ... = C + (n + 1) * (∫ x in a..b, cos x ^ n) - (n + 1) * ∫ x in a..b, cos x ^ (n + 2) : by rw [integral_sub, mul_sub, add_sub_assoc]; apply continuous.interval_integrable; continuity, all_goals { apply continuous.interval_integrable, continuity }, end /-- The reduction formula for the integral of `cos x ^ n` for any natural `n ≥ 2`. -/ lemma integral_cos_pow : ∫ x in a..b, cos x ^ (n + 2) = (cos b ^ (n + 1) * sin b - cos a ^ (n + 1) * sin a) / (n + 2) + (n + 1) / (n + 2) * ∫ x in a..b, cos x ^ n := begin have : (n : ℝ) + 2 ≠ 0 := by exact_mod_cast succ_ne_zero n.succ, field_simp, convert eq_sub_iff_add_eq.mp (integral_cos_pow_aux n), ring, end @[simp] lemma integral_cos_sq : ∫ x in a..b, cos x ^ 2 = (cos b * sin b - cos a * sin a + b - a) / 2 := by field_simp [integral_cos_pow, add_sub_assoc] /-! ### Integral of `sin x ^ m * cos x ^ n` -/ /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `n` is odd. -/ lemma integral_sin_pow_mul_cos_pow_odd (m n : ℕ) : ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n := have hc : continuous (λ u : ℝ, u ^ m * (1 - u ^ 2) ^ n), by continuity, calc ∫ x in a..b, sin x ^ m * cos x ^ (2 * n + 1) = ∫ x in a..b, sin x ^ m * (1 - sin x ^ 2) ^ n * cos x : by simp only [pow_succ', ← mul_assoc, pow_mul, cos_sq'] ... = ∫ u in sin a..sin b, u ^ m * (1 - u ^ 2) ^ n : integral_comp_mul_deriv (λ x hx, has_deriv_at_sin x) continuous_on_cos hc /-- The integral of `sin x * cos x`, given in terms of sin². See `integral_sin_mul_cos₂` below for the integral given in terms of cos². -/ @[simp] lemma integral_sin_mul_cos₁ : ∫ x in a..b, sin x * cos x = (sin b ^ 2 - sin a ^ 2) / 2 := by simpa using integral_sin_pow_mul_cos_pow_odd 1 0 @[simp] lemma integral_sin_sq_mul_cos : ∫ x in a..b, sin x ^ 2 * cos x = (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 2 0 @[simp] lemma integral_cos_pow_three : ∫ x in a..b, cos x ^ 3 = sin b - sin a - (sin b ^ 3 - sin a ^ 3) / 3 := by simpa using integral_sin_pow_mul_cos_pow_odd 0 1 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` is odd. -/ lemma integral_sin_pow_odd_mul_cos_pow (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m := have hc : continuous (λ u : ℝ, u ^ n * (1 - u ^ 2) ^ m), by continuity, calc ∫ x in a..b, sin x ^ (2 * m + 1) * cos x ^ n = -∫ x in b..a, sin x ^ (2 * m + 1) * cos x ^ n : by rw integral_symm ... = ∫ x in b..a, (1 - cos x ^ 2) ^ m * -sin x * cos x ^ n : by simp [pow_succ', pow_mul, sin_sq] ... = ∫ x in b..a, cos x ^ n * (1 - cos x ^ 2) ^ m * -sin x : by { congr, ext, ring } ... = ∫ u in cos b..cos a, u ^ n * (1 - u ^ 2) ^ m : integral_comp_mul_deriv (λ x hx, has_deriv_at_cos x) continuous_on_sin.neg hc /-- The integral of `sin x * cos x`, given in terms of cos². See `integral_sin_mul_cos₁` above for the integral given in terms of sin². -/ lemma integral_sin_mul_cos₂ : ∫ x in a..b, sin x * cos x = (cos a ^ 2 - cos b ^ 2) / 2 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 1 @[simp] lemma integral_sin_mul_cos_sq : ∫ x in a..b, sin x * cos x ^ 2 = (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 0 2 @[simp] lemma integral_sin_pow_three : ∫ x in a..b, sin x ^ 3 = cos a - cos b - (cos a ^ 3 - cos b ^ 3) / 3 := by simpa using integral_sin_pow_odd_mul_cos_pow 1 0 /-- Simplification of the integral of `sin x ^ m * cos x ^ n`, case `m` and `n` are both even. -/ lemma integral_sin_pow_even_mul_cos_pow_even (m n : ℕ) : ∫ x in a..b, sin x ^ (2 * m) * cos x ^ (2 * n) = ∫ x in a..b, ((1 - cos (2 * x)) / 2) ^ m * ((1 + cos (2 * x)) / 2) ^ n := by field_simp [pow_mul, sin_sq, cos_sq, ← sub_sub, (by ring : (2:ℝ) - 1 = 1)] @[simp] lemma integral_sin_sq_mul_cos_sq : ∫ x in a..b, sin x ^ 2 * cos x ^ 2 = (b - a) / 8 - (sin (4 * b) - sin (4 * a)) / 32 := begin convert integral_sin_pow_even_mul_cos_pow_even 1 1 using 1, have h1 : ∀ c : ℝ, (1 - c) / 2 * ((1 + c) / 2) = (1 - c ^ 2) / 4 := λ c, by ring, have h2 : continuous (λ x, cos (2 * x) ^ 2) := by continuity, have h3 : ∀ x, cos x * sin x = sin (2 * x) / 2, { intro, rw sin_two_mul, ring }, have h4 : ∀ d : ℝ, 2 * (2 * d) = 4 * d := λ d, by ring, simp [h1, h2.interval_integrable, integral_comp_mul_left (λ x, cos x ^ 2), h3, h4], ring, end
cb759d9a5f6625fe3b98e8dac0bf6d8a9ce288c7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/def_bug1.hlean
f37e9c92172f1cc994d4898e176501890f2d5f39
[ "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
485
hlean
open eq eq.ops variable {A : Type} definition trans : Π {x y z : A} (p : x = y) (q : y = z), x = z | trans (refl a) (refl a) := refl a set_option pp.purify_locals false definition con_inv_cancel_left : Π {x y z : A} (p : x = y) (q : x = z), p ⬝ (p⁻¹ ⬝ q) = q | con_inv_cancel_left (refl a) (refl a) := refl (refl a) definition inv_con_cancel_left : Π {x y z : A} (p : x = y) (q : y = z), p⁻¹ ⬝ (p ⬝ q) = q | inv_con_cancel_left (refl a) (refl a) := refl (refl a)
7221d3433a8f2733180266140eef5265f886a7ce
f7c63613a4933f66368ef2802a50c417a46cddfc
/library/init/meta/mk_has_reflect_instance.lean
785d29b3ec3c79dca39bd21b1b9e5f4efff53be3
[ "Apache-2.0" ]
permissive
avigad/lean
28cef71cd8c4eae53f342c87f81ca78d7cc75874
5410178203ab5ae854b5804586ace074ffd63aae
refs/heads/master
1,608,801,379,340
1,504,894,459,000
1,505,174,163,000
22,361,408
0
0
null
null
null
null
UTF-8
Lean
false
false
3,595
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Helper tactic for constructing a has_reflect instance. -/ prelude import init.meta.rec_util namespace tactic open expr environment list /- Retrieve the name of the type we are building a has_reflect instance for. -/ private meta def get_has_reflect_type_name : tactic name := do { (app (const n ls) t) ← target, when (n ≠ `has_reflect) failed, (const I ls) ← return (get_app_fn t), return I } <|> fail "mk_has_reflect_instance tactic failed, target type is expected to be of the form (has_reflect ...)" /- Try to synthesize constructor argument using type class resolution -/ private meta def mk_has_reflect_instance_for (a : expr) : tactic expr := do t ← infer_type a, do { m ← mk_app `reflected [a], inst ← mk_instance m <|> do { f ← pp t, fail (to_fmt "mk_has_reflect_instance failed, failed to generate instance for" ++ format.nest 2 (format.line ++ f)) }, mk_app `reflect [a, inst] } /- Synthesize (recursive) instances of `reflected` for all fields -/ private meta def mk_reflect : name → name → list name → nat → tactic (list expr) | I_name F_name [] num_rec := return [] | I_name F_name (fname::fnames) num_rec := do field ← get_local fname, rec ← is_type_app_of field I_name, quote ← if rec then mk_brec_on_rec_value F_name num_rec else mk_has_reflect_instance_for field, quotes ← mk_reflect I_name F_name fnames (if rec then num_rec + 1 else num_rec), return (quote :: quotes) /- Solve the subgoal for constructor `F_name` -/ private meta def has_reflect_case (I_name F_name : name) (field_names : list name) : tactic unit := do field_quotes ← mk_reflect I_name F_name field_names 0, -- fn should be of the form `F_name ps fs`, where ps are the inductive parameter arguments, -- and `fs.length = field_names.length` `(reflected %%fn) ← target, -- `reflected (F_name ps)` should be synthesizable directly, using instances from the context let fn := field_names.foldl (λ fn _, expr.app_fn fn) fn, quote ← mk_app `reflected [fn] >>= mk_instance, -- now extend to an instance of `reflected (F_name ps fs)` quote ← field_quotes.mfoldl (λ quote fquote, to_expr ``(reflected.subst %%quote %%fquote)) quote, exact quote private meta def for_each_has_reflect_goal : name → name → list (list name) → tactic unit | I_name F_name [] := done <|> fail "mk_has_reflect_instance failed, unexpected number of cases" | I_name F_name (ns::nss) := do solve1 (has_reflect_case I_name F_name ns), for_each_has_reflect_goal I_name F_name nss /-- Solves a goal of the form `has_reflect α` where α is an inductive type. Needs to synthesize a `reflected` instance for each inductive parameter type of α and for each constructor parameter of α. -/ meta def mk_has_reflect_instance : tactic unit := do I_name ← get_has_reflect_type_name, env ← get_env, v_name : name ← return `_v, F_name : name ← return `_F, -- Use brec_on if type is recursive. -- We store the functional in the variable F. if is_recursive env I_name then intro `_v >>= (λ x, induction x [v_name, F_name] (some $ I_name <.> "brec_on") >> return ()) else intro v_name >> return (), arg_names : list (list name) ← mk_constructors_arg_names I_name `_p, get_local v_name >>= λ v, cases v (join arg_names), for_each_has_reflect_goal I_name F_name arg_names end tactic
80ca967277f9dbbba2cf28829923d8e45406b698
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/ring_theory/principal_ideal_domain.lean
39c15cd082a4542d3b59c782a7acfbbb71e52348
[ "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
4,446
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes, Morenikeji Neri -/ import algebra.euclidean_domain ring_theory.ideals variables {α : Type*} [comm_ring α] open set function is_ideal local attribute [instance] classical.prop_decidable class is_principal_ideal (S : set α) : Prop := (principal : ∃ a : α, S = {x | a ∣ x}) class principal_ideal_domain (α : Type*) extends integral_domain α := (principal : ∀ (S : set α) [is_ideal S], is_principal_ideal S) namespace is_principal_ideal noncomputable def generator (S : set α) [is_principal_ideal S] : α := classical.some (principal S) lemma generator_generates (S : set α) [is_principal_ideal S] : {x | generator S ∣ x} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : set α) [is_principal_ideal S] : generator S ∈ S := by conv {to_rhs, rw ← generator_generates S}; exact dvd_refl _ lemma mem_iff_generator_dvd (S : set α) [is_principal_ideal S] {x : α} : x ∈ S ↔ generator S ∣ x := by conv {to_lhs, rw ← generator_generates S}; refl lemma eq_trivial_iff_generator_eq_zero (S : set α) [is_principal_ideal S] : S = trivial α ↔ generator S = 0 := ⟨λ h, by rw [← mem_trivial, ← h]; exact generator_mem S, λ h, set.ext $ λ x, by rw [mem_iff_generator_dvd S, h, zero_dvd_iff, mem_trivial]⟩ instance to_is_ideal (S : set α) [is_principal_ideal S] : is_ideal S := { to_is_submodule := { zero_ := by rw ← generator_generates S; simp, add_ := λ x y h, by rw ← generator_generates S at *; exact (dvd_add_iff_right h).1, smul := λ c x h, by rw ← generator_generates S at h ⊢; exact dvd_mul_of_dvd_right h _ } } end is_principal_ideal open euclidean_domain is_principal_ideal is_ideal lemma mod_mem_iff {α : Type*} [euclidean_domain α] {S : set α} [is_ideal S] {x y : α} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ is_ideal.add (is_ideal.mul_right hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ is_ideal.sub hx (is_ideal.mul_right hy)⟩ instance euclidean_domain.to_principal_ideal_domain {α : Type*} [euclidean_domain α] : principal_ideal_domain α := { principal := λ S h, by exactI ⟨if h : {x : α | x ∈ S ∧ x ≠ 0} = ∅ then ⟨0, set.ext $ λ a, ⟨by finish [set.ext_iff], λ h₁, (show a = 0, by simpa using h₁).symm ▸ is_ideal.zero S⟩⟩ else have wf : well_founded euclidean_domain.r := euclidean_domain.r_well_founded α, have hmin : well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : α | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h, set.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ▸ dvd_add (dvd_mul_right _ _) (have (x % (well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h) ∉ {x : α | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : α | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := hx in hy.symm ▸ is_ideal.mul_right hmin.1⟩⟩⟩ } lemma is_prime_ideal.to_maximal_ideal {α : Type*} [principal_ideal_domain α] {S : set α} [hpi : is_prime_ideal S] (hS : S ≠ trivial α) : is_maximal_ideal S := is_maximal_ideal.mk _ (is_proper_ideal_iff_one_not_mem.1 (by apply_instance)) begin assume x T i hST hxS hxT, haveI := principal_ideal_domain.principal S, haveI := principal_ideal_domain.principal T, cases (mem_iff_generator_dvd _).1 (hST ((mem_iff_generator_dvd _).2 (dvd_refl _))) with z hz, cases is_prime_ideal.mem_or_mem_of_mul_mem (show generator T * z ∈ S, by rw [mem_iff_generator_dvd S, ← hz]), { have hST' : S = T := set.subset.antisymm hST (λ y hyT, (mem_iff_generator_dvd _).2 (dvd.trans ((mem_iff_generator_dvd _).1 h) ((mem_iff_generator_dvd _).1 hyT))), cc }, { cases (mem_iff_generator_dvd _).1 h with y hy, rw [← mul_one (generator S), hy, mul_left_comm, domain.mul_left_inj (mt (eq_trivial_iff_generator_eq_zero S).2 hS)] at hz, exact hz.symm ▸ is_ideal.mul_right (generator_mem T) } end
1a5034eb5c4459fa3e2c1ce8dae907130f71a774
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/pythagorean_triples.lean
98342e8198626c9ab6e22bc053eb3bace186d37a
[ "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
25,741
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul van Wamelen -/ import algebra.field.basic import ring_theory.int.basic import algebra.group_with_zero.power import tactic.ring import tactic.ring_exp import tactic.field_simp import data.zmod.basic /-! # Pythagorean Triples The main result is the classification of Pythagorean triples. The final result is for general Pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ lemma sq_ne_two_fin_zmod_four (z : zmod 4) : z * z ≠ 2 := begin change fin 4 at z, fin_cases z; norm_num [fin.ext_iff, fin.coe_bit0, fin.coe_bit1] end lemma int.sq_ne_two_mod_four (z : ℤ) : (z * z) % 4 ≠ 2 := suffices ¬ (z * z) % (4 : ℕ) = 2 % (4 : ℕ), by norm_num at this, begin rw ← zmod.int_coe_eq_int_coe_iff', simpa using sq_ne_two_fin_zmod_four _ end noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z /-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`. This comes from additive commutativity. -/ lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } /-- The zeroth Pythagorean triple is all zeros. -/ lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] /-- A triple is still a triple if you multiply `x`, `y` and `z` by a constant `k`. -/ lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring omit h /-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if `(x, y, z)` is also a triple. -/ lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, apply int.sq_ne_two_mod_four z, rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, norm_num [int.add_mod] } end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff zero_lt_two, sq z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨t, co, pp⟩, rw [one_mul, one_mul], exact ⟨t, co⟩, end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, norm_num at this }, rw [← h.eq, ← sq, ← sq], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (sq_pos_of_ne_zero x hxz) (sq_nonneg y) }, { apply lt_add_of_le_of_pos (sq_nonneg x) (sq_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_sq hp _ _) hpy, rw [sq, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub ((hpz).mul_right _) ((hpy).mul_right _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0 := mt eq_neg_of_add_eq_zero_left hy, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h3], ring }, { field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_sq_sub_sq_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m, have hnc : p = 2 ∨ p ∣ int.nat_abs n := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [sq, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_sq_sub_sq_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_sq_sub_sq_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_sq_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2 := (nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [sq, int.sub_mod, int.mul_mod, hm, hn] }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact (int.coe_nat_dvd_left.mpr hpn).mul_right n end private lemma coprime_sq_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_sq_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_sq_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_sq_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_sq_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_sq_sub_sq_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, sq], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_sq, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (sq_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m := (rat.num_div_denom q).symm, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (sq_nonneg n), exact lt_of_le_of_ne (sq_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, rat.denom_ne_zero q, -rat.num_div_denom] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q, -rat.num_div_denom], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_sq_sub_sq_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_sq_sub_sq_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_sq_sub_sq_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [sq, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [sq, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_sq_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_sq_sub_mul co pp } } end /-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/ theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) : ∃ m n, x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∧ z = m ^ 2 + n ^ 2 ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) ∧ 0 ≤ m := begin obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ := pythagorean_triple.coprime_classification.mp (and.intro h h_coprime), cases le_or_lt 0 m with hm hm, { use [m, n], cases ht1 with h_odd h_even, { apply and.intro h_odd.1, apply and.intro h_odd.2, cases ht2 with h_pos h_neg, { apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity }, { use [-m, -n], cases ht1 with h_odd h_even, { rw [neg_sq m], rw [neg_sq n], apply and.intro h_odd.1, split, { rw h_odd.2, ring }, cases ht2 with h_pos h_neg, { apply and.intro h_pos, split, { delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 }, { rw [int.neg_mod_two, int.neg_mod_two], apply and.intro ht4, linarith } }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity } end /-- **Formula for Pythagorean Triples** -/ theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [sq, ← h.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [sq, ← h.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
998e4f36a42bc4975b79bbf58f48fe24643d2420
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/normed_space/enorm.lean
88477248844b66b0355e2b445031e047a984a4fc
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,751
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed_space.basic /-! # Extended norm In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for an `enorm` because the same space can have more than one extended norm. For example, the space of measurable functions `f : α → ℝ` has a family of `L_p` extended norms. We prove some basic inequalities, then define * `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`; * the subspace of vectors with finite norm, called `e.finite_subspace`; * a `normed_space` structure on this space. The last definition is an instance because the type involves `e`. ## Implementation notes We do not define extended normed groups. They can be added to the chain once someone will need them. ## Tags normed space, extended norm -/ noncomputable theory local attribute [instance, priority 1001] classical.prop_decidable open_locale ennreal /-- Extended norm on a vector space. As in the case of normed spaces, we require only `∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/ structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] := (to_fun : V → ℝ≥0∞) (eq_zero' : ∀ x, to_fun x = 0 → x = 0) (map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y) (map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ nnnorm c * to_fun x) namespace enorm variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [module 𝕜 V] (e : enorm 𝕜 V) instance : has_coe_to_fun (enorm 𝕜 V) (λ _, V → ℝ≥0∞) := ⟨enorm.to_fun⟩ lemma coe_fn_injective : function.injective (coe_fn : enorm 𝕜 V → (V → ℝ≥0∞)) := λ e₁ e₂ h, by cases e₁; cases e₂; congr; exact h @[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coe_fn_injective $ funext h lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, norm_cast] lemma coe_inj {e₁ e₂ : enorm 𝕜 V} : (e₁ : V → ℝ≥0∞) = e₂ ↔ e₁ = e₂ := coe_fn_injective.eq_iff @[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = nnnorm c * e x := le_antisymm (e.map_smul_le' c x) $ begin by_cases hc : c = 0, { simp [hc] }, calc (nnnorm c : ℝ≥0∞) * e x = nnnorm c * e (c⁻¹ • c • x) : by rw [inv_smul_smul₀ hc] ... ≤ nnnorm c * (nnnorm (c⁻¹) * e (c • x)) : _ ... = e (c • x) : _, { exact ennreal.mul_le_mul (le_refl _) (e.map_smul_le' _ _) }, { rw [← mul_assoc, normed_field.nnnorm_inv, ennreal.coe_inv, ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] } end @[simp] lemma map_zero : e 0 = 0 := by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num } @[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 := ⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩ @[simp] lemma map_neg (x : V) : e (-x) = e x := calc e (-x) = nnnorm (-1:𝕜) * e x : by rw [← map_smul, neg_one_smul] ... = e x : by simp lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) := by rw [← neg_sub, e.map_neg] lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y := calc e (x - y) = e (x + -y) : by rw sub_eq_add_neg ... ≤ e x + e (-y) : e.map_add_le x (-y) ... = e x + e y : by rw [e.map_neg] instance : partial_order (enorm 𝕜 V) := { le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x, le_refl := λ e x, le_refl _, le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) } /-- The `enorm` sending each non-zero vector to infinity. -/ noncomputable instance : has_top (enorm 𝕜 V) := ⟨{ to_fun := λ x, if x = 0 then 0 else ⊤, eq_zero' := λ x, by { split_ifs; simp [*] }, map_add_le' := λ x y, begin split_ifs with hxy hx hy hy hx hy hy; try { simp [*] }, simpa [hx, hy] using hxy end, map_smul_le' := λ c x, begin split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx, { simp only [mul_zero, le_refl] }, { have : c = 0, by tauto, simp [this] }, { tauto }, { simp [hcx.1] } end }⟩ noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩ lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx noncomputable instance : semilattice_sup_top (enorm 𝕜 V) := { le := (≤), lt := (<), top := ⊤, le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h], sup := λ e₁ e₂, { to_fun := λ x, max (e₁ x) (e₂ x), eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1, map_add_le' := λ x y, max_le (le_trans (e₁.map_add_le _ _) $ add_le_add (le_max_left _ _) (le_max_left _ _)) (le_trans (e₂.map_add_le _ _) $ add_le_add (le_max_right _ _) (le_max_right _ _)), map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] }, le_sup_left := λ e₁ e₂ x, le_max_left _ _, le_sup_right := λ e₁ e₂ x, le_max_right _ _, sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), .. enorm.partial_order } @[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl @[norm_cast] lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl /-- Structure of an `emetric_space` defined by an extended norm. -/ def emetric_space : emetric_space V := { edist := λ x y, e (x - y), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero], edist_comm := e.map_sub_rev, edist_triangle := λ x y z, calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel] ... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) } /-- The subspace of vectors with finite enorm. -/ def finite_subspace : subspace 𝕜 V := { carrier := {x | e x < ⊤}, zero_mem' := by simp, add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩), smul_mem' := λ c x (hx : _ < _), calc e (c • x) = nnnorm c * e x : e.map_smul c x ... < ⊤ : ennreal.mul_lt_top ennreal.coe_ne_top hx.ne } /-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist` to ensure that this definition agrees with `e.emetric_space`. -/ instance : metric_space e.finite_subspace := begin letI := e.emetric_space, refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl), change e (x - y) ≠ ⊤, exact ne_top_of_le_ne_top (ennreal.add_lt_top.2 ⟨x.2, y.2⟩).ne (e.map_sub_le x y) end lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl /-- Normed group instance on `e.finite_subspace`. -/ instance : normed_group e.finite_subspace := { norm := λ x, (e x).to_real, dist_eq := λ x y, rfl } lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl /-- Normed space instance on `e.finite_subspace`. -/ instance : normed_space 𝕜 e.finite_subspace := { norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ennreal.to_real_mul] } end enorm
3a24ab14f1a0fdb54613d6e1080cf5ff1f9841f9
8c02fed42525b65813b55c064afe2484758d6d09
/src/spec/closed.lean
6ae42b0995ac5fa6065d89468c0146f7e7d3e41c
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/AliveInLean
3eac351a34154efedd3ffc4fe2fa4ec01b219e0d
4b739dd6e4266b26a045613849df221374119871
refs/heads/master
1,691,419,737,939
1,689,365,567,000
1,689,365,568,000
131,156,103
23
18
NOASSERTION
1,660,342,040,000
1,524,747,538,000
Lean
UTF-8
Lean
false
false
21,661
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import ..smtexpr import ..bitvector import .spec --import .lemmas import .irstate import .freevar import .equiv import smt2.syntax import system.io import init.meta.tactic import init.meta.interactive namespace spec open irsem open freevar -- An SMT bit-vector expression bv is closed if it does not have a (free) SMT variable. -- -- (bvadd x 1) is not closed because it has a free variable 'x' -- (bvadd 1 2) is closed because it does not have that. -- -- We define closedness as follows: for any given mapping η, replacing the free -- variable with any value (η⟦bv⟧) does not change the expression. def closed_bv {sz:size} (bv:sbitvec sz) := ∀ (η:freevar.env), η⟦bv⟧ = bv -- Same definition for boolean SMT expressions too. def closed_b (b:sbool) := ∀ (η:freevar.env), η⟦b⟧ = b def closed_valty (v:valty irsem_smt) := ∀ (η:freevar.env), η⟦v⟧ = v def closed_regfile (rf:regfile irsem_smt) := ∀ (η:freevar.env), rf.apply_to_values irsem_smt (η.replace_valty) = rf def closed_irstate (ss:irstate irsem_smt) := ∀ (η:freevar.env), η⟦ss⟧ = ss -- An interesting lemma about closedness: -- Given an SMT bit-vector expression sb and LEAN bitvector value bv -- and environment η, -- If (1) η⟦sb⟧ is equivalent to bv, and (2) sb has no free variable, -- then sb and bv are also equivalent. lemma closed_bv_equiv: ∀ {sz:size} (η:freevar.env) (sb:sbitvec sz) (bv:bitvector sz) (HEQ2:bv_equiv (η⟦sb⟧) bv) (HC:closed_bv sb), bv_equiv sb bv := begin intros, unfold closed_bv at HC, have HC' := HC η, rw HC' at HEQ2, assumption end lemma closed_b_equiv: ∀ (η:freevar.env) (sb:sbool) (b:bool) (HEQ:b_equiv (η⟦sb⟧) b) (HC:closed_b sb), b_equiv sb b := begin intros, unfold closed_b at HC, have HC := HC η, rw HC at HEQ, assumption end lemma closed_irstate_equiv: ∀ (η:freevar.env) (ss:irstate irsem_smt) (se:irstate irsem_exec) (HEQ:irstate_equiv (η⟦ss⟧) se) (HC:closed_irstate ss), irstate_equiv ss se := begin intros, unfold closed_irstate at HC, have HC := HC η, rw HC at HEQ, assumption end lemma closed_b_never_var: ∀ s, ¬ closed_b (sbool.var s) := begin intros, intro H, unfold closed_b at H, have H' := H (freevar.env.empty.add_b s tt), unfold env.add_b at H', unfold freevar.env.replace_sb at H', simp at H', cases H' end lemma closed_bv_never_var: ∀ sz s, ¬ closed_bv (sbitvec.var sz s) := begin intros, intro H, unfold closed_bv at H, have H' := H (freevar.env.empty.add_bv s 1), unfold env.add_bv at H', unfold freevar.env.replace_sbv at H', simp at H', cases H' end lemma closed_irstate_closed_ub: ∀ {η:freevar.env} {ss:irstate irsem_smt} (HC:closed_irstate (η⟦ss⟧)), closed_b (η⟦irstate.getub irsem_smt ss⟧) := begin intros, cases ss, unfold closed_irstate at HC, unfold closed_b, intros η', have HC := HC η', unfold freevar.env.replace at HC, rw irstate.getub_apply_to_values at HC, unfold irstate.getub at *, unfold irstate.setub at HC, unfold irstate.apply_to_values at HC, injection HC end lemma closed_irstate_split: ∀ ub rf, closed_irstate (ub, rf) ↔ closed_b ub ∧ closed_regfile rf := begin intros, unfold closed_irstate, unfold freevar.env.replace, unfold closed_b, unfold closed_regfile, unfold irstate.getub, unfold irstate.setub, unfold irstate.apply_to_values, simp, split, { intros H, split, any_goals { intros, have H' := H η, cases H',tauto } }, { intros H, cases H, intros, rw [H_left, H_right],tauto } end lemma closed_regfile_empty: closed_regfile (regfile.empty irsem_smt) := begin unfold regfile.empty, unfold closed_regfile, intros, refl end lemma closed_irstate_empty: closed_irstate (irstate.empty irsem_smt) := begin unfold irstate.empty, unfold closed_irstate, intros, refl end -- This lemma says that, for example, since -- {x |-> tt}[[x]] (which is simply tt) is closed -- where x is an SMT boolean variable, -- {x |-> tt, n |-> v}[[x]] is also closed. lemma closed_b_var_add: ∀ (η:freevar.env) (n:string) (v:bool) (s:string) (HC: closed_b (η⟦sbool.var s⟧)), closed_b ((env.add_b η n v)⟦sbool.var s⟧) := begin unfold freevar.env.replace_sb, unfold env.add_b, simp, intros, generalize Hb': (η.b s) = b', rw Hb' at *, -- LEAN is based on Calculus of Inductive Construction, which cannot prove -- excluded middle (∀x, P x \/ ¬ P x) in general. (If you prove it, then I bet -- you will be really famous) -- However, if P is decidable (meaning that it has a concrete computing function -- that yields either true or false), then now you can use excluded middle. have Heq: decidable (s = n), { apply_instance }, -- Prove that there exists the computing function for s = n { cases Heq, { rw if_neg, assumption, assumption }, { rw if_pos, unfold env.replace_sb._match_1 at *, cases v; unfold closed_b; intros; refl, assumption } } end lemma closed_b_var_add2: ∀ (η:freevar.env) (v:bool) (s:string), closed_b ((η.add_b s v)⟦sbool.var s⟧) := begin unfold env.add_b, unfold freevar.env.replace_sb, simp, intros, generalize Hb': (η.b s) = b', unfold closed_b, intros, cases v, refl, refl end -- This lemma is similar to closed_b_var_add lemma closed_bv_var_add: ∀ (η:freevar.env) sz (n:string) v (s:string) (HC: closed_bv (η⟦sbitvec.var sz s⟧)), closed_bv ((env.add_bv η n v)⟦sbitvec.var sz s⟧) := begin unfold freevar.env.replace_sbv, unfold env.add_bv, simp, intros, generalize Hb': (η.b s) = b', rw Hb' at *, have Heq: decidable (s = n), apply_instance, cases Heq, { rw if_neg, assumption, assumption }, { rw if_pos, unfold env.replace_sbv._match_1 at *, unfold closed_bv, cases v, any_goals { unfold sbitvec.of_int; intros; unfold freevar.env.replace_sbv }, assumption } end lemma closed_bv_var_add2: ∀ (η:freevar.env) sz v (s:string), closed_bv ((η.add_bv s v)⟦sbitvec.var sz s⟧) := begin unfold env.add_bv, intros, generalize Hb': (η.b s) = b', unfold closed_bv, intros, cases v; unfold freevar.env.replace_sbv; simp, { unfold sbitvec.of_int, unfold env.replace_sbv }, { unfold sbitvec.of_int, unfold env.replace_sbv }, end lemma ival_closed: ∀ sz vn pn (η:freevar.env) z b, closed_valty (((η.add_bv vn z).add_b pn b) ⟦irsem.valty.ival sz (sbitvec.var sz vn) (sbool.var pn)⟧) := begin intros, unfold closed_valty, intros, unfold env.add_b, unfold env.add_bv, simp, split, { cases z; unfold sbitvec.of_int; unfold freevar.env.replace_sbv }, { rw env.replace_sb_of_bool } end lemma closed_ival_split: ∀ sz bv p, closed_valty (irsem.valty.ival sz bv p) ↔ closed_b p ∧ closed_bv bv := begin intros, unfold closed_valty, split, { intros H, unfold freevar.env.replace_valty at H, split, { unfold closed_b, intros, have H' := H η, injection H' }, { unfold closed_bv, intros, have H' := H η, injection H', apply eq_of_heq, assumption } }, { intros H, cases H, intros, unfold freevar.env.replace_valty, rw H_left, rw H_right } end lemma closed_regfile_update_split: ∀ {rf:regfile irsem_smt} {n} {v}, closed_regfile (regfile.update irsem_smt rf n v) ↔ closed_regfile rf ∧ closed_valty v := begin intros, unfold regfile.update, unfold closed_valty, unfold closed_regfile, split, { intros HC, unfold regfile.apply_to_values at *, simp at HC, split, { intros, have HC := HC η, injection HC }, { intros, have HC := HC η, injection HC, injection h_1 } }, { intros HC η, cases HC with HC1 HC2, have HC1 := HC1 η, have HC2 := HC2 η, unfold regfile.apply_to_values at *, simp at *, rw HC1, rw HC2 } end -- TODO 1: Merge closed_b_add_b and closed_bv_add_b into a single -- theorem (I tried merging them -- but it raised excessive memory consumption error.) -- TODO 2: closed_b_add_b, closed_b_add_bv, closed_bv_add_b, -- closed_bv_add_bv are very similar. Is there any good way -- to merge all of them into single theorem lemma closed_b_add_b: ∀ {η s} n v (HC: closed_b (η⟦s⟧)), closed_b ((η.add_b n v)⟦s⟧) := begin intros, revert s, apply sbool.induction (λ s, closed_b (η⟦s⟧) → closed_b ((η.add_b n v)⟦s⟧)) (λ {sz} sb, closed_bv (η⟦sb⟧) → closed_bv ((η.add_b n v)⟦sb⟧)), { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { intros, apply closed_b_var_add; assumption }, -- I didn't use any_goals because it raises excessive -- memory consumptions. { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 b3 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b IH H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_b, unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros b IH H0 η', unfold freevar.env.replace_sbv, done }, { intros, generalize Hb': (η.bv n_1) = b', unfold env.add_b, unfold freevar.env.replace_sbv at *, rw Hb' at *, cases b'; unfold env.replace_sbv._match_1 at *; assumption }, any_goals { unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_bv, intros sz v sz' IH H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH, { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { intros sz sz' v h l IH1 IH2 H0 η', unfold freevar.env.replace_sbv at *, rw IH2, unfold closed_bv at *, { intros η'', have H0' := H0 η'', unfold freevar.env.replace_sbv at H0', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros sz b v1 v2 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sbv at *, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } } end lemma closed_b_add_bv: ∀ {η s} n v (HC: closed_b (η⟦s⟧)), closed_b ((η.add_bv n v)⟦s⟧) := begin intros, revert s, apply sbool.induction (λ s, closed_b (η⟦s⟧) → closed_b ((η.add_bv n v)⟦s⟧)) (λ {sz} sb, closed_bv (η⟦sb⟧) → closed_bv ((η.add_bv n v)⟦sb⟧)), { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { intros b1 b2 IH1 IH2 H η, unfold env.add_bv at *, unfold closed_b at *, unfold freevar.env.replace_sb at *, simp at *, rw IH1, rw IH2, any_goals { split; refl }, all_goals { intros η', have H' := H η', cases H'; assumption } }, any_goals { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 b3 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b IH H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_b, unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros b IH H0 η', unfold freevar.env.replace_sbv, done }, { intros, apply closed_bv_var_add; assumption }, any_goals { unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_bv, intros sz v sz' IH H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH, { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { intros sz sz' v h l IH1 IH2 H0 η', unfold freevar.env.replace_sbv at *, rw IH2, unfold closed_bv at *, { intros η'', have H0' := H0 η'', unfold freevar.env.replace_sbv at H0', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros sz b v1 v2 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sbv at *, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } } end lemma closed_bv_add_b: ∀ {sz} {η} {s:sbitvec sz} n v (HC: closed_bv (η⟦s⟧)), closed_bv ((η.add_b n v)⟦s⟧) := begin intros, revert s, apply sbitvec.induction (λ s, closed_b (η⟦s⟧) → closed_b ((η.add_b n v)⟦s⟧)) (λ {sz} sb, closed_bv (η⟦sb⟧) → closed_bv ((η.add_b n v)⟦sb⟧)), { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { intros, apply closed_b_var_add; assumption }, -- I didn't use any_goals because it raises excessive -- memory consumptions. { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 b3 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b IH H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_b, unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros b IH H0 η', unfold freevar.env.replace_sbv, done }, { intros, generalize Hb': (η.bv n_1) = b', unfold env.add_b, unfold freevar.env.replace_sbv at *, rw Hb' at *, cases b'; unfold env.replace_sbv._match_1 at *; assumption }, any_goals { unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_bv, intros sz v sz' IH H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH, { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { intros sz sz' v h l IH1 IH2 H0 η', unfold freevar.env.replace_sbv at *, rw IH2, unfold closed_bv at *, { intros η'', have H0' := H0 η'', unfold freevar.env.replace_sbv at H0', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros sz b v1 v2 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sbv at *, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } } end lemma closed_bv_add_bv: ∀ {sz} {η} {s:sbitvec sz} n v (HC: closed_bv (η⟦s⟧)), closed_bv ((η.add_bv n v)⟦s⟧) := begin intros, revert s, apply sbitvec.induction (λ s, closed_b (η⟦s⟧) → closed_b ((η.add_bv n v)⟦s⟧)) (λ {sz} sb, closed_bv (η⟦sb⟧) → closed_bv ((η.add_bv n v)⟦sb⟧)), { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { unfold freevar.env.replace_sb, intros, assumption }, { intros b1 b2 IH1 IH2 H η, unfold env.add_bv at *, unfold closed_b at *, unfold freevar.env.replace_sb at *, simp at *, rw IH1, rw IH2, any_goals { split; refl }, all_goals { intros η', have H' := H η', cases H'; assumption } }, any_goals { unfold closed_b, intros b1 b2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b1 b2 b3 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, { unfold closed_b, intros b IH H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_b, unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sb, unfold freevar.env.replace_sb at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros b IH H0 η', unfold freevar.env.replace_sbv, done }, { intros, apply closed_bv_var_add; assumption }, any_goals { unfold closed_bv, intros sz v1 v2 IH1 IH2 H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH1, rw IH2, all_goals { intros η'', have H0' := H0 η'', injection H0', done } }, any_goals { unfold closed_bv, intros sz v sz' IH H0 η', unfold freevar.env.replace_sbv, unfold freevar.env.replace_sbv at H0, rw IH, { intros η'', have H0' := H0 η'', injection H0', apply eq_of_heq, assumption } }, { intros sz sz' v h l IH1 IH2 H0 η', unfold freevar.env.replace_sbv at *, rw IH2, unfold closed_bv at *, { intros η'', have H0' := H0 η'', unfold freevar.env.replace_sbv at H0', injection H0', apply eq_of_heq, assumption } }, { unfold closed_bv, intros sz b v1 v2 IH1 IH2 IH3 H0 η', unfold freevar.env.replace_sbv at *, rw IH1, rw IH2, rw IH3, all_goals { intros η'', have H0' := H0 η'', injection H0', done } } end end spec
6bd9c25d585e2400dd90a0edf453d24bbecc9899
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/tests/lean/run/inj2.lean
c20d5c1f64814b39e492601b4a6d1293e532f55c
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,120
lean
universes u v inductive Vec2 (α : Type u) (β : Type v) : Nat → Type (max u v) | nil : Vec2 α β 0 | cons : α → β → forall {n}, Vec2 α β n → Vec2 α β (n+1) inductive Fin2 : Nat → Type | zero (n : Nat) : Fin2 (n+1) | succ {n : Nat} (s : Fin2 n) : Fin2 (n+1) theorem test1 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : a₁ = a₂ := by { injection h; assumption } theorem test2 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : v = w := by { injection h with h1 h2 h3 h4; assumption } theorem test3 {α β} {n} (a₁ a₂ : α) (b₁ b₂ : β) (v w : Vec2 α β n) (h : Vec2.cons a₁ b₁ v = Vec2.cons a₂ b₂ w) : v = w := by { injection h with _ _ _ h4; exact h4 } theorem test4 {α} (v : Fin2 0) : α := by cases v def test5 {α β} {n} (v : Vec2 α β (n+1)) : α := by cases v | cons h1 h2 n tail => exact h1 def test6 {α β} {n} (v : Vec2 α β (n+2)) : α := by cases v | cons h1 h2 n tail => exact h1
e5ffed49f19a0c1422e5ad1b7b3287dc03f821c0
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/library/init/meta/simp_tactic.lean
66f179a10a4713bb733ee980cc49a889565b63c9
[ "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
22,027
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.instances open tactic def simp.default_max_steps := 10000000 meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default : tactic simp_lemmas meta constant simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas := hs.mfoldl simp_lemmas.add s /-- `simp_lemmas.rewrite_core s e prove R` apply a simplification lemma from 's' - 'e' is the expression to be "simplified" - 'prove' is used to discharge proof obligations. - 'r' is the equivalence relation being used (e.g., 'eq', 'iff') Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic (expr × expr) /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr meta constant is_valid_simp_lemma_cnst : name → tactic bool meta constant is_valid_simp_lemma : expr → tactic bool meta constant simp_lemmas.pp : simp_lemmas → tactic format meta instance : has_to_tactic_format simp_lemmas := ⟨simp_lemmas.pp⟩ namespace tactic meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, t ← target, match t with | expr.pi n bi d b := do h_simp ← transform d, unsafe_change $ expr.pi n bi h_simp b | expr.elet n g e f := do h_simp ← transform g, unsafe_change $ expr.elet n h_simp e f | _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)" end, intron num_reverted /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) structure dsimp_config := (md := reducible) (max_steps : nat := simp.default_max_steps) (canonize_instances : bool := tt) (single_pass : bool := ff) (fail_if_unchanged := tt) (eta := tt) (zeta : bool := tt) (beta : bool := tt) (proj : bool := tt) -- reduce projections (iota : bool := tt) (unfold_reducible := ff) -- if tt, reducible definitions will be unfolded (delta-reduced) (memoize := tt) end tactic /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/ meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr namespace tactic /- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/ meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) (e : expr) (cfg : dsimp_config := {}) : tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas | none := simp_lemmas.mk_default | (some s) := return s meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, t ← target >>= instantiate_mvars, s.dsimplify u t cfg >>= unsafe_change meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: (@has_add.add nat nat.has_add a b) -/ /-- Tries to unfold `e` if it is a constant or a constant application. Remark: this is not a recursive procedure. -/ meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr structure dunfold_config extends dsimp_config := (md := transparency.instances) /- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for performance reasons. -/ meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit := do t ← target, dunfold cs t cfg >>= unsafe_change meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit := revert_and_transform (λ e, dunfold cs e cfg) h structure delta_config := (max_steps := simp.default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /-- Delta reduce the given constant names -/ meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances}, return new_e meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit := do t ← target, delta cs t cfg >>= unsafe_change meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit := revert_and_transform (λ e, delta cs e cfg) h structure unfold_proj_config extends dsimp_config := (md := transparency.instances) /-- If `e` is a projection application, try to unfold it, otherwise fail. -/ meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr := let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do new_e ← unfold_proj e cfg.md, return (tt, new_e, tt) in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold", return new_e meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit := do t ← target, unfold_projs t cfg >>= unsafe_change meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit := revert_and_transform (λ e, unfold_projs e cfg) h structure simp_config := (max_steps : nat := simp.default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections (iota : bool := tt) (single_pass : bool := ff) (fail_if_unchanged := tt) (memoize := tt) /-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal. `discharger` is a tactic for dischaging new subgoals created by the simplifier. If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`. The parameter `to_unfold` specifies definitions that should be delta-reduced, and projection applications that should be unfolded. -/ meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq) (discharger : tactic unit := failed) : tactic (expr × expr) meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit := do t ← target, (new_t, pr) ← simplify s to_unfold t cfg `eq discharger, replace_target new_t pr meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic expr := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, (h_new_type, pr) ← simplify s to_unfold htype cfg `eq discharger, replace_hyp h h_new_type pr meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simp_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (discharger : α → tactic α) /- (pre a S r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps section simp_intros meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed structure simp_intros_config extends simp_config := (use_hyps := ff) meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simp_target S to_unfold cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d) ← simplify S to_unfold d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new) (return S) else return S, simp_intros_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns else try (simp_target S to_unfold cfg) >> mcond (expr.is_pi <$> target) (simp_intros_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit := step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids end simp_intros meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do let t := `(caching_user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := if no_dflt then join_user_simp_lemmas_core simp_lemmas.mk attrs else do s ← simp_lemmas.mk_default, join_user_simp_lemmas_core s attrs /-- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr private meta def remove_deps (s : name_set) (h : expr) : name_set := if s.empty then s else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s) /- Return the list of hypothesis that are propositions and do not have forward dependencies. -/ meta def non_dep_prop_hyps : tactic (list expr) := do ctx ← local_context, s ← ctx.mfoldl (λ s h, do h_type ← infer_type h, let s := remove_deps s h_type, h_val ← head_zeta h, let s := if h_val =ₐ h then s else remove_deps s h_val, mcond (is_prop h_type) (return $ s.insert h.local_uniq_name) (return s)) mk_name_set, t ← target, let s := remove_deps s t, return $ ctx.filter (λ h, s.contains h.local_uniq_name) section simp_all meta structure simp_all_entry := (h : expr) -- hypothesis (new_type : expr) -- new type (pr : option expr) -- proof that type of h is equal to new_type (s : simp_lemmas) -- simplification lemmas for simplifying new_type private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) := es.mmap $ λ e, do new_s ← e.s.add h, return {e with s := new_s} /- Helper tactic for `init`. Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions). We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/ private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry) | [] s r := return (s, r) | (h::hs) s r := do new_r ← update_simp_lemmas r h, new_s ← s.add h, h_type ← infer_type h, init_aux hs new_s (⟨h, h_type, none, s⟩::new_r) private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) := init_aux hs s [] private meta def add_new_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, match e.pr with | none := return () | some pr := assert e.h.local_pp_name e.new_type >> mk_eq_mp pr e.h >>= exact end private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h)) private meta def join_pr : option expr → expr → tactic expr | none pr₂ := return pr₂ | (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂ private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name) : list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic unit | [] r s m := if m then loop r [] s ff else do add_new_hyps r, target_changed ← (simp_target s to_unfold cfg discharger >> return tt) <|> return ff, guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify", clear_old_hyps r | (e::es) r s m := do let ⟨h, h_type, h_pr, s'⟩ := e, (new_h_type, new_pr) ← simplify s' to_unfold h_type {cfg with fail_if_unchanged := ff} `eq discharger, if h_type =ₐ new_h_type then loop es (e::r) s m else do new_pr ← join_pr h_pr new_pr, new_fact_pr ← mk_eq_mp new_pr h, if new_h_type = `(false) then do tgt ← target, to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact else do h0_type ← infer_type h, let new_fact_pr := mk_id_locked_proof new_h_type new_fact_pr, new_es ← update_simp_lemmas es new_fact_pr, new_r ← update_simp_lemmas r new_fact_pr, let new_r := {e with new_type := new_h_type, pr := new_pr} :: new_r, new_s ← s.add new_fact_pr, loop new_es new_r new_s tt meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit := do hs ← non_dep_prop_hyps, (s, es) ← init s hs, loop cfg discharger to_unfold es [] s ff end simp_all /- debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr)
cf992ad8a6d2a71c5549c9550294cab9219b3d1b
618003631150032a5676f229d13a079ac875ff77
/src/tactic/omega/prove_unsats.lean
45708ce72e434b1bff803776f19b8b2f74fabc24
[ "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
2,078
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek A tactic which constructs exprs to discharge goals of the form `clauses.unsat cs`. -/ import tactic.omega.find_ees import tactic.omega.find_scalars import tactic.omega.lin_comb namespace omega open tactic /-- Return expr of proof that given int is negative -/ meta def prove_neg : int → tactic expr | (int.of_nat _) := failed | -[1+ m] := return `(int.neg_succ_lt_zero %%`(m)) lemma forall_mem_repeat_zero_eq_zero (m : nat) : (∀ x ∈ (list.repeat (0 : int) m), x = (0 : int)) := λ x, list.eq_of_mem_repeat /-- Return expr of proof that elements of (repeat 0 is.length) are all 0 -/ meta def prove_forall_mem_eq_zero (is : list int) : tactic expr := return `(forall_mem_repeat_zero_eq_zero is.length) /-- Return expr of proof that the combination of linear constraints represented by ks and ts is unsatisfiable -/ meta def prove_unsat_lin_comb (ks : list nat) (ts : list term) : tactic expr := let ⟨b,as⟩ := lin_comb ks ts in do x1 ← prove_neg b, x2 ← prove_forall_mem_eq_zero as, to_expr ``(unsat_lin_comb_of %%`(ks) %%`(ts) %%x1 %%x2) /-- Given a (([],les) : clause), return the expr of a term (t : clause.unsat ([],les)). -/ meta def prove_unsat_ef : clause → tactic expr | ((_::_), _) := failed | ([], les) := do ks ← find_scalars les, x ← prove_unsat_lin_comb ks les, return `(unsat_of_unsat_lin_comb %%`(ks) %%`(les) %%x) /-- Given a (c : clause), return the expr of a term (t : clause.unsat c) -/ meta def prove_unsat (c : clause) : tactic expr := do ee ← find_ees c, x ← prove_unsat_ef (eq_elim ee c), return `(unsat_of_unsat_eq_elim %%`(ee) %%`(c) %%x) /-- Given a (cs : list clause), return the expr of a term (t : clauses.unsat cs) -/ meta def prove_unsats : list clause → tactic expr | [] := return `(clauses.unsat_nil) | (p::ps) := do x ← prove_unsat p, xs ← prove_unsats ps, to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs) end omega
1833c7262e9bfd74f5333c3f2cca9e260c24bd92
ccb7cdf8ebc2d015a000e8e7904952a36b910425
/src/heap/basic.lean
93aabb3ab92e0310aaed1436012c98beb7e81439
[]
no_license
cipher1024/lean-pl
f7258bda55606b75e3e39deaf7ce8928ed177d66
829680605ac17e91038d793c0188e9614353ca25
refs/heads/master
1,592,558,951,987
1,565,043,356,000
1,565,043,531,000
196,661,367
1
0
null
null
null
null
UTF-8
Lean
false
false
3,283
lean
import data.finmap run_cmd mk_simp_attr `separation_logic open finmap namespace memory variables value : Type @[reducible] def ptr := ℕ @[reducible] def heap := finmap (λ _ : ptr, value) variables {value} def add (x y : option (heap value)) : option (heap value) := do x ← x, y ← y, if disjoint x y then pure $ x ∪ y else none infixr ` ⊗ `:55 := add instance {α : Type*} {β : α → Type*} : has_subset (finmap β) := ⟨ λ x y, ∀ a, a ∈ x → a ∈ y ⟩ lemma disjoint_mono' {ha hb ha' hb' : heap value} (H₀ : ha' ⊆ ha) (H₁ : hb' ⊆ hb) : disjoint ha hb → disjoint ha' hb' := λ H₂ x H₃ H₄, H₂ x (H₀ _ H₃) (H₁ _ H₄) lemma union_eq_add_of_disjoint {h h' : heap value} (H₀ : disjoint h h') : some (h ∪ h') = some h ⊗ some h' := by simp [add,if_pos H₀]; refl lemma add_assoc (h₀ h₁ h₂ : option (heap value)) : (h₀ ⊗ h₁) ⊗ h₂ = h₀ ⊗ (h₁ ⊗ h₂) := begin simp only [add] with monad_norm; congr; ext : 1; congr; ext : 1, split_ifs, { simp, congr, ext : 1, split_ifs; simp [disjoint_union_left] at h_1, { simp, rw [if_pos,finmap.union_assoc], simp [disjoint_union_right], exact ⟨h,h_1.1⟩ }, { exfalso, apply h_2 h_1.2 }, simp, split_ifs, { exfalso, rw disjoint_union_right at h_3, apply h_1 h_3.2 h_2, }, { refl }, simp }, simp, cases h₂, { refl }, change none = pure h₂ >>= _, simp, split_ifs, { simp, split_ifs, exfalso, rw disjoint_union_right at h_2, apply h h_2.1, refl }, refl end lemma add_comm (h₀ h₁ : option (heap value)) : h₀ ⊗ h₁ = h₁ ⊗ h₀ := begin cases h₀; cases h₁; try { refl }, simp only [add, @disjoint.symm_iff _ _ h₀, option.some_bind]; split_ifs, ext : 1, simp only [ext_iff,pure], rw finmap.union_comm_of_disjoint, symmetry, assumption, refl end instance : is_associative _ (@add value) := ⟨ add_assoc ⟩ instance : is_commutative _ (@add value) := ⟨ add_comm ⟩ @[simp] lemma empty_add (h : option (heap value)) : some ∅ ⊗ h = h := by cases h; [ simp [add], { rw [← union_eq_add_of_disjoint,empty_union]; apply disjoint_empty }] @[simp] lemma add_empty (h : option (heap value)) : h ⊗ some ∅ = h := by cases h; [ simp [add], { rw [← union_eq_add_of_disjoint,union_empty]; apply empty_disjoint }] lemma add_eq_some (x y : option (heap value)) (z : heap value) : some z = x ⊗ y → ∃ x', some x' = x := by intro h; cases x; [ { simp [add] at h, cases h }, exact ⟨_,rfl⟩ ] lemma add_eq_some' (x y : option (heap value)) (z : heap value) : some z = x ⊗ y → ∃ y', some y' = y := assume h, add_eq_some y x z (@add_comm _ x y ▸ h) lemma disjoint_iff {h h' : heap value} : disjoint h h' ↔ ∃ h'', some h'' = some h ⊗ some h' := by by_cases disjoint h h'; simp only [add, *, option.some_bind, exists_false, if_false, if_true, true_iff]; exact ⟨_,rfl⟩ lemma disjoint_of_add {h h' : heap value} (h'' : heap value) : some h'' = some h ⊗ some h' → disjoint h h' := λ HH, disjoint_iff.mpr ⟨_, HH⟩ lemma eq_union_of_eq_add {h h' h'' : heap value} : some h'' = some h ⊗ some h' → h'' = h ∪ h' := λ HH, option.some.inj (eq.trans HH (union_eq_add_of_disjoint (disjoint_of_add _ HH)).symm) end memory
7d986a9db901a7dd9d892af7a933e31af3d18700
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/instances/ereal.lean
54e64c041113d23fcc8446f1d7eb1b5c449da180
[ "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
13,315
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.instances.ennreal import data.real.ereal /-! # Topological structure on `ereal` We endow `ereal` with the order topology, and prove basic properties of this topology. ## Main results * `coe : ℝ → ereal` is an open embedding * `coe : ℝ≥0∞ → ereal` is an embedding * The addition on `ereal` is continuous except at `(⊥, ⊤)` and at `(⊤, ⊥)`. * Negation is a homeomorphism on `ereal`. ## Implementation Most proofs are adapted from the corresponding proofs on `ℝ≥0∞`. -/ noncomputable theory open classical set filter metric topological_space open_locale classical topological_space ennreal nnreal big_operators filter variables {α : Type*} [topological_space α] namespace ereal instance : topological_space ereal := preorder.topology ereal instance : order_topology ereal := ⟨rfl⟩ instance : t2_space ereal := by apply_instance instance : second_countable_topology ereal := ⟨begin refine ⟨⋃ (q : ℚ), {{a : ereal | a < (q : ℝ)}, {a : ereal | ((q : ℝ) : ereal) < a}}, countable_Union (λ a, (countable_singleton _).insert _), _⟩, refine le_antisymm (le_generate_from $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt}) _, apply le_generate_from (λ s h, _), rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | a < (q : ℝ)}, {b | ((q : ℝ) : ereal) < b}, by { ext x, simpa only [hs, exists_prop, mem_Union] using lt_iff_exists_rat_btwn }, rw show s = ⋃q∈{q:ℚ | ((q : ℝ) : ereal) < a}, {b | b < ((q : ℝ) : ereal)}, by { ext x, simpa only [hs, and_comm, exists_prop, mem_Union] using lt_iff_exists_rat_btwn }]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, apply generate_open.basic, exact mem_Union.2 ⟨q, by simp⟩ }, end⟩ /-! ### Real coercion -/ lemma embedding_coe : embedding (coe : ℝ → ereal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ereal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ | a < ↑b}, { rcases a.cases with rfl|⟨x, rfl⟩|rfl, { simp only [is_open_univ, bot_lt_coe, set_of_true] }, { simp only [ereal.coe_lt_coe_iff], exact is_open_Ioi }, { simp only [set_of_false, is_open_empty, not_top_lt] } }, show is_open {b : ℝ | ↑b < a}, { rcases a.cases with rfl|⟨x, rfl⟩|rfl, { simp only [not_lt_bot, set_of_false, is_open_empty] }, { simp only [ereal.coe_lt_coe_iff], exact is_open_Iio }, { simp only [is_open_univ, coe_lt_top, set_of_true] } } }, { rw [@order_topology.topology_eq_generate_intervals ℝ _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, by simp only [imp_self, ereal.coe_eq_coe_iff]⟩ lemma open_embedding_coe : open_embedding (coe : ℝ → ereal) := ⟨embedding_coe, begin convert @is_open_Ioo ereal _ _ _ ⊥ ⊤, ext x, rcases x.cases with rfl|⟨y, rfl⟩|rfl, { simp only [left_mem_Ioo, mem_range, coe_ne_bot, exists_false, not_false_iff] }, { simp only [mem_range_self, mem_Ioo, bot_lt_coe, coe_lt_top, and_self] }, { simp only [mem_range, right_mem_Ioo, exists_false, coe_ne_top] } end⟩ @[norm_cast] lemma tendsto_coe {α : Type*} {f : filter α} {m : α → ℝ} {a : ℝ} : tendsto (λ a, (m a : ereal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma _root_.continuous_coe_real_ereal : continuous (coe : ℝ → ereal) := embedding_coe.continuous lemma continuous_coe_iff {f : α → ℝ} : continuous (λa, (f a : ereal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ} : 𝓝 (r : ereal) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma nhds_coe_coe {r p : ℝ} : 𝓝 ((r : ereal), (p : ereal)) = (𝓝 (r, p)).map (λp:ℝ × ℝ, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma tendsto_to_real {a : ereal} (ha : a ≠ ⊤) (h'a : a ≠ ⊥) : tendsto ereal.to_real (𝓝 a) (𝓝 a.to_real) := begin lift a to ℝ using and.intro ha h'a, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma continuous_on_to_real : continuous_on ereal.to_real ({⊥, ⊤} : set ereal).compl := λ a ha, continuous_at.continuous_within_at (tendsto_to_real (by { simp [not_or_distrib] at ha, exact ha.2 }) (by { simp [not_or_distrib] at ha, exact ha.1 })) /-- The set of finite `ereal` numbers is homeomorphic to `ℝ`. -/ def ne_bot_top_homeomorph_real : ({⊥, ⊤} : set ereal).compl ≃ₜ ℝ := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_real, continuous_inv_fun := continuous_subtype_mk _ continuous_coe_real_ereal, .. ne_top_bot_equiv_real } /-! ### ennreal coercion -/ lemma embedding_coe_ennreal : embedding (coe : ℝ≥0∞ → ereal) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ereal _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0∞ | a < ↑b}, { rcases a.cases with rfl|⟨x, rfl⟩|rfl, { simp only [is_open_univ, bot_lt_coe_ennreal, set_of_true] }, { rcases le_or_lt 0 x with h|h, { have : (x : ereal) = ((id ⟨x, h⟩ : ℝ≥0) : ℝ≥0∞) := rfl, rw this, simp only [id.def, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Ioi, }, { have : ∀ (y : ℝ≥0∞), (x : ereal) < y := λ y, (ereal.coe_lt_coe_iff.2 h).trans_le (coe_ennreal_nonneg _), simp only [this, is_open_univ, set_of_true] } }, { simp only [set_of_false, is_open_empty, not_top_lt] } }, show is_open {b : ℝ≥0∞ | ↑b < a}, { rcases a.cases with rfl|⟨x, rfl⟩|rfl, { simp only [not_lt_bot, set_of_false, is_open_empty] }, { rcases le_or_lt 0 x with h|h, { have : (x : ereal) = ((id ⟨x, h⟩ : ℝ≥0) : ℝ≥0∞) := rfl, rw this, simp only [id.def, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Iio, }, { convert is_open_empty, apply eq_empty_iff_forall_not_mem.2 (λ y hy, lt_irrefl (x : ereal) _), exact ((ereal.coe_lt_coe_iff.2 h).trans_le (coe_ennreal_nonneg y)).trans hy } }, { simp only [← coe_ennreal_top, coe_ennreal_lt_coe_ennreal_iff], exact is_open_Iio } } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, by simp only [imp_self, coe_ennreal_eq_coe_ennreal_iff]⟩ @[norm_cast] lemma tendsto_coe_ennreal {α : Type*} {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ a, (m a : ereal)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe_ennreal.tendsto_nhds_iff.symm lemma _root_.continuous_coe_ennreal_ereal : continuous (coe : ℝ≥0∞ → ereal) := embedding_coe_ennreal.continuous lemma continuous_coe_ennreal_iff {f : α → ℝ≥0∞} : continuous (λa, (f a : ereal)) ↔ continuous f := embedding_coe_ennreal.continuous_iff.symm /-! ### Neighborhoods of infinity -/ lemma nhds_top : 𝓝 (⊤ : ereal) = ⨅ a ≠ ⊤, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 (⊤ : ereal) = ⨅ a : ℝ, 𝓟 (Ioi a) := begin rw [nhds_top], apply le_antisymm, { exact infi_le_infi2 (λ x, ⟨x, by simp⟩) }, { refine le_infi (λ r, le_infi (λ hr, _)), rcases r.cases with rfl|⟨x, rfl⟩|rfl, { exact (infi_le _ 0).trans (by simp) }, { exact infi_le _ _ }, { simpa using hr, } } end lemma mem_nhds_top_iff {s : set ereal} : s ∈ 𝓝 (⊤ : ereal) ↔ ∃ (y : ℝ), Ioi (y : ereal) ⊆ s := begin rw [nhds_top', mem_infi_of_directed], { refl }, exact λ x y, ⟨max x y, by simp [le_refl], by simp [le_refl]⟩, end lemma tendsto_nhds_top_iff_real {α : Type*} {m : α → ereal} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', mem_Ioi, tendsto_infi, tendsto_principal] lemma nhds_bot : 𝓝 (⊥ : ereal) = ⨅ a ≠ ⊥, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot] lemma nhds_bot' : 𝓝 (⊥ : ereal) = ⨅ a : ℝ, 𝓟 (Iio a) := begin rw [nhds_bot], apply le_antisymm, { exact infi_le_infi2 (λ x, ⟨x, by simp⟩) }, { refine le_infi (λ r, le_infi (λ hr, _)), rcases r.cases with rfl|⟨x, rfl⟩|rfl, { simpa using hr }, { exact infi_le _ _ }, { exact (infi_le _ 0).trans (by simp) } } end lemma mem_nhds_bot_iff {s : set ereal} : s ∈ 𝓝 (⊥ : ereal) ↔ ∃ (y : ℝ), Iio (y : ereal) ⊆ s := begin rw [nhds_bot', mem_infi_of_directed], { refl }, exact λ x y, ⟨min x y, by simp [le_refl], by simp [le_refl]⟩, end lemma tendsto_nhds_bot_iff_real {α : Type*} {m : α → ereal} {f : filter α} : tendsto m f (𝓝 ⊥) ↔ ∀ x : ℝ, ∀ᶠ a in f, m a < x := by simp only [nhds_bot', mem_Iio, tendsto_infi, tendsto_principal] /-! ### Continuity of addition -/ lemma continuous_at_add_coe_coe (a b :ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, b) := by simp only [continuous_at, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] lemma continuous_at_add_top_coe (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊤, a) := begin simp only [continuous_at, tendsto_nhds_top_iff_real, top_add, nhds_prod_eq], assume r, rw eventually_prod_iff, refine ⟨λ z, ((r - (a - 1): ℝ) : ereal) < z, Ioi_mem_nhds (coe_lt_top _), λ z, ((a - 1 : ℝ) : ereal) < z, Ioi_mem_nhds (by simp [zero_lt_one]), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp, end lemma continuous_at_add_coe_top (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, ⊤) := begin change continuous_at ((λ (p : ereal × ereal), p.2 + p.1) ∘ prod.swap) (a, ⊤), apply continuous_at.comp _ continuous_swap.continuous_at, simp_rw add_comm, exact continuous_at_add_top_coe a end lemma continuous_at_add_top_top : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊤, ⊤) := begin simp only [continuous_at, tendsto_nhds_top_iff_real, top_add, nhds_prod_eq], assume r, rw eventually_prod_iff, refine ⟨λ z, (r : ereal) < z, Ioi_mem_nhds (coe_lt_top _), λ z, ((0 : ℝ) : ereal) < z, Ioi_mem_nhds (by simp [zero_lt_one]), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp, end lemma continuous_at_add_bot_coe (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊥, a) := begin simp only [continuous_at, tendsto_nhds_bot_iff_real, nhds_prod_eq, bot_add_coe], assume r, rw eventually_prod_iff, refine ⟨λ z, z < ((r - (a + 1): ℝ) : ereal), Iio_mem_nhds (bot_lt_coe _), λ z, z < ((a + 1 : ℝ) : ereal), Iio_mem_nhds (by simp [-coe_add, zero_lt_one]), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, dsimp, ring, end lemma continuous_at_add_coe_bot (a : ℝ) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (a, ⊥) := begin change continuous_at ((λ (p : ereal × ereal), p.2 + p.1) ∘ prod.swap) (a, ⊥), apply continuous_at.comp _ continuous_swap.continuous_at, simp_rw add_comm, exact continuous_at_add_bot_coe a end lemma continuous_at_add_bot_bot : continuous_at (λ (p : ereal × ereal), p.1 + p.2) (⊥, ⊥) := begin simp only [continuous_at, tendsto_nhds_bot_iff_real, nhds_prod_eq, bot_add_bot], assume r, rw eventually_prod_iff, refine ⟨λ z, z < r, Iio_mem_nhds (bot_lt_coe _), λ z, z < 0, Iio_mem_nhds (bot_lt_coe _), λ x hx y hy, _⟩, dsimp, convert add_lt_add hx hy, simp end /-- The addition on `ereal` is continuous except where it doesn't make sense (i.e., at `(⊥, ⊤)` and at `(⊤, ⊥)`). -/ lemma continuous_at_add {p : ereal × ereal} (h : p.1 ≠ ⊤ ∨ p.2 ≠ ⊥) (h' : p.1 ≠ ⊥ ∨ p.2 ≠ ⊤) : continuous_at (λ (p : ereal × ereal), p.1 + p.2) p := begin rcases p with ⟨x, y⟩, rcases x.cases with rfl|⟨x, rfl⟩|rfl; rcases y.cases with rfl|⟨y, rfl⟩|rfl, { exact continuous_at_add_bot_bot }, { exact continuous_at_add_bot_coe _ }, { simpa using h' }, { exact continuous_at_add_coe_bot _ }, { exact continuous_at_add_coe_coe _ _ }, { exact continuous_at_add_coe_top _ }, { simpa using h }, { exact continuous_at_add_top_coe _ }, { exact continuous_at_add_top_top }, end /-! ### Negation-/ /-- Negation on `ereal` as a homeomorphism -/ def neg_homeo : ereal ≃ₜ ereal := neg_order_iso.to_homeomorph lemma continuous_neg : continuous (λ (x : ereal), -x) := neg_homeo.continuous end ereal
521b75611c6b0cec5cba96b4d98c969aa09dce2c
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/openInScopeBug.lean
52f4fc5f73777886010b02d6a7122c4ecbfd457d
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
807
lean
constant f : Nat → Nat constant g : Nat → Nat namespace Foo @[scoped simp] axiom ax1 (x : Nat) : f (g x) = x @[scoped simp] axiom ax2 (x : Nat) : g (g x) = g x end Foo theorem ex1 : f (g (g (g x))) = x := by simp -- does not use ax1 and ax2 simp [Foo.ax1, Foo.ax2] theorem ex2 : f (g (g (g x))) = x := have h₁ : f (g (g (g x))) = f (g x) by simp; /- try again with `Foo` scoped lemmas -/ open Foo in simp have h₂ : f (g x) = x by simp; open Foo in simp Eq.trans h₁ h₂ -- open Foo in simp -- works theorem ex3 : f (g (g (g x))) = x := by simp simp [Foo.ax1, Foo.ax2] open Foo in theorem ex4 : f (g (g (g x))) = x := by simp theorem ex5 : f (g (g (g x))) = x ∧ f (g x) = x := by apply And.intro { simp; open Foo in simp } { simp; open Foo in simp }
0f0f1a471569bc8c9e97b86472b3dd19e097c8b0
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Util/CollectLevelParams.lean
e4afca6126f9558093283adad429742e74790886
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,372
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 CollectLevelParams structure State := (visitedLevel : LevelSet := {}) (visitedExpr : ExprSet := {}) (params : Array Name := #[]) instance : Inhabited State := ⟨{}⟩ abbrev Visitor := State → State @[inline] def visitLevel (f : Level → Visitor) (u : Level) : Visitor := fun s => if !u.hasParam || s.visitedLevel.contains u then s else f u { s with visitedLevel := s.visitedLevel.insert u } partial def collect : Level → Visitor | Level.succ v _ => visitLevel collect v | Level.max u v _ => visitLevel collect v ∘ visitLevel collect u | Level.imax u v _ => visitLevel collect v ∘ visitLevel collect u | Level.param n _ => fun s => { s with params := s.params.push n } | _ => id @[inline] def visitExpr (f : Expr → Visitor) (e : Expr) : Visitor := fun s => if !e.hasLevelParam then s else if s.visitedExpr.contains e then s else f e { s with visitedExpr := s.visitedExpr.insert e } partial def main : Expr → Visitor | Expr.proj _ _ s _ => visitExpr main s | Expr.forallE _ d b _ => visitExpr main b ∘ visitExpr main d | Expr.lam _ d b _ => visitExpr main b ∘ visitExpr main d | Expr.letE _ t v b _ => visitExpr main b ∘ visitExpr main v ∘ visitExpr main t | Expr.app f a _ => visitExpr main a ∘ visitExpr main f | Expr.mdata _ b _ => visitExpr main b | Expr.const _ us _ => fun s => us.foldl (fun s u => visitLevel collect u s) s | Expr.sort u _ => visitLevel collect u | _ => id partial def State.getUnusedLevelParam (s : CollectLevelParams.State) (pre : Name := `v) : Level := let v := mkLevelParam pre; if s.visitedLevel.contains v then let rec loop (i : Nat) := let v := mkLevelParam (pre.appendIndexAfter i); if s.visitedLevel.contains v then loop (i+1) else v loop 1 else v end CollectLevelParams def collectLevelParams (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := CollectLevelParams.main e s def CollectLevelParams.State.collect (s : CollectLevelParams.State) (e : Expr) : CollectLevelParams.State := collectLevelParams s e end Lean
fd51f1e5ff7b6e248d960635c4739144ecde3b4e
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0703.lean
3b5eca7a5f3fb9d59b0cabd0c24b3b88dda44b56
[]
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
128
lean
variable p : Prop example : ¬(p ↔ ¬p) := assume h, suffices hnp : ¬p, from hnp (h.mpr hnp), assume hp, h.mp hp hp
f4a2b517c55b6741e7d91df9cdc85fb5bb2cd6bc
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/std_basis.lean
0cc92187283bb71134f1e566c3036131c483a4fe
[ "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
10,863
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.matrix.basis import linear_algebra.basis import linear_algebra.pi /-! # The standard basis > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the standard basis `pi.basis (s : ∀ j, basis (ι j) R (M j))`, which is the `Σ j, ι j`-indexed basis of Π j, M j`. The basis vectors are given by `pi.basis s ⟨j, i⟩ j' = linear_map.std_basis R M j' (s j) i = if j = j' then s i else 0`. The standard basis on `R^η`, i.e. `η → R` is called `pi.basis_fun`. To give a concrete example, `linear_map.std_basis R (λ (i : fin 3), R) i 1` gives the `i`th unit basis vector in `R³`, and `pi.basis_fun R (fin 3)` proves this is a basis over `fin 3 → R`. ## Main definitions - `linear_map.std_basis R M`: if `x` is a basis vector of `M i`, then `linear_map.std_basis R M i x` is the `i`th standard basis vector of `Π i, M i`. - `pi.basis s`: given a basis `s i` for each `M i`, the standard basis on `Π i, M i` - `pi.basis_fun R η`: the standard basis on `R^η`, i.e. `η → R`, given by `pi.basis_fun R η i j = if i = j then 1 else 0`. - `matrix.std_basis R n m`: the standard basis on `matrix n m R`, given by `matrix.std_basis R n m (i, j) i' j' = if (i, j) = (i', j') then 1 else 0`. -/ open function submodule open_locale big_operators namespace linear_map variables (R : Type*) {ι : Type*} [semiring R] (φ : ι → Type*) [Π i, add_comm_monoid (φ i)] [Π i, module R (φ i)] [decidable_eq ι] /-- The standard basis of the product of `φ`. -/ def std_basis : Π (i : ι), φ i →ₗ[R] (Πi, φ i) := single lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := rfl @[simp] lemma std_basis_apply' (i i' : ι) : (std_basis R (λ (_x : ι), R) i) 1 i' = ite (i = i') 1 0 := begin rw [linear_map.std_basis_apply, function.update_apply, pi.zero_apply], congr' 1, rw [eq_iff_iff, eq_comm], end lemma coe_std_basis (i : ι) : ⇑(std_basis R φ i) = pi.single i := rfl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := pi.single_eq_same i b lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := pi.single_eq_of_ne h b lemma std_basis_eq_pi_diag (i : ι) : std_basis R φ i = pi (diag i) := begin ext x j, convert (update_apply 0 x i j _).symm, refl, end lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot_of_injective $ pi.single_injective _ _ lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis_eq_pi_diag, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := linear_map.ext $ std_basis_same R φ i lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := linear_map.ext $ std_basis_ne R φ _ _ h lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) := begin refine (supr_le $ λ i, supr_le $ λ hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, set_like.le_def, mem_ker, comap_infi, mem_infi], rintro b - j hj, rw [proj_std_basis_ne R φ j i, zero_apply], rintro rfl, exact h.le_bot ⟨hi, hj⟩ end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) ≤ (⨆i∈I, range (std_basis R φ i)) := set_like.le_def.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show ∑ i in I, std_basis R φ i (b i) = b, { ext i, rw [finset.sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem_bsupr (λ i hi, mem_range_self (std_basis R φ i) (b i)) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i : (Πi, φ i) →ₗ[R] φ i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [hI.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_mono $ assume i, _), rw [set.finite.mem_to_finset], exact le_rfl end lemma supr_range_std_basis [finite ι] : (⨆ i, range (std_basis R φ i)) = ⊤ := begin casesI nonempty_fintype ι, convert top_unique (infi_emptyset.ge.trans $ infi_ker_proj_le_supr_range_std_basis R φ _), { exact funext (λ i, (@supr_pos _ _ _ (λ h, range $ std_basis R φ i) $ finset.mem_univ i).symm) }, { rw [finset.coe_univ, set.union_empty] } end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ disjoint_compl_right) _, simp only [disjoint_iff_inf_le, set_like.le_def, mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h.le_bot ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := funext $ λ i, (finsupp.single_eq_pi_single i a).symm end linear_map namespace pi open linear_map open set variables {R : Type*} section module variables {η : Type*} {ιs : η → Type*} {Ms : η → Type*} lemma linear_independent_std_basis [ring R] [∀i, add_comm_group (Ms i)] [∀i, module R (Ms i)] [decidable_eq η] (v : Πj, ιs j → (Ms j)) (hs : ∀i, linear_independent R (v i)) : linear_independent R (λ (ji : Σ j, ιs j), std_basis R Ms ji.1 (v ji.1 ji.2)) := begin have hs' : ∀j : η, linear_independent R (λ i : ιs j, std_basis R Ms j (v j i)), { intro j, exact (hs j).map' _ (ker_std_basis _ _ _) }, apply linear_independent_Union_finite hs', { assume j J _ hiJ, simp [(set.Union.equations._eqn_1 _).symm, submodule.span_image, submodule.span_Union], have h₀ : ∀ j, span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ range (std_basis R Ms j), { intro j, rw [span_le, linear_map.range_coe], apply range_comp_subset_range }, have h₁ : span R (range (λ (i : ιs j), std_basis R Ms j (v j i))) ≤ ⨆ i ∈ {j}, range (std_basis R Ms i), { rw @supr_singleton _ _ _ (λ i, linear_map.range (std_basis R (λ (j : η), Ms j) i)), apply h₀ }, have h₂ : (⨆ j ∈ J, span R (range (λ (i : ιs j), std_basis R Ms j (v j i)))) ≤ ⨆ j ∈ J, range (std_basis R (λ (j : η), Ms j) j) := supr₂_mono (λ i _, h₀ i), have h₃ : disjoint (λ (i : η), i ∈ {j}) J, { convert set.disjoint_singleton_left.2 hiJ using 0 }, exact (disjoint_std_basis_std_basis _ _ _ _ h₃).mono h₁ h₂ } end variables [semiring R] [∀i, add_comm_monoid (Ms i)] [∀i, module R (Ms i)] variable [fintype η] section open linear_equiv /-- `pi.basis (s : ∀ j, basis (ιs j) R (Ms j))` is the `Σ j, ιs j`-indexed basis on `Π j, Ms j` given by `s j` on each component. For the standard basis over `R` on the finite-dimensional space `η → R` see `pi.basis_fun`. -/ protected noncomputable def basis (s : ∀ j, basis (ιs j) R (Ms j)) : basis (Σ j, ιs j) R (Π j, Ms j) := -- The `add_comm_monoid (Π j, Ms j)` instance was hard to find. -- Defining this in tactic mode seems to shake up instance search enough that it works by itself. by { refine basis.of_repr (_ ≪≫ₗ (finsupp.sigma_finsupp_lequiv_pi_finsupp R).symm), exact linear_equiv.Pi_congr_right (λ j, (s j).repr) } @[simp] lemma basis_repr_std_basis [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (j i) : (pi.basis s).repr (std_basis R _ j (s j i)) = finsupp.single ⟨j, i⟩ 1 := begin ext ⟨j', i'⟩, by_cases hj : j = j', { subst hj, simp only [pi.basis, linear_equiv.trans_apply, basis.repr_self, std_basis_same, linear_equiv.Pi_congr_right_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply], symmetry, exact finsupp.single_apply_left (λ i i' (h : (⟨j, i⟩ : Σ j, ιs j) = ⟨j, i'⟩), eq_of_heq (sigma.mk.inj h).2) _ _ _ }, simp only [pi.basis, linear_equiv.trans_apply, finsupp.sigma_finsupp_lequiv_pi_finsupp_symm_apply, linear_equiv.Pi_congr_right_apply], dsimp, rw [std_basis_ne _ _ _ _ (ne.symm hj), linear_equiv.map_zero, finsupp.zero_apply, finsupp.single_eq_of_ne], rintros ⟨⟩, contradiction end @[simp] lemma basis_apply [decidable_eq η] (s : ∀ j, basis (ιs j) R (Ms j)) (ji) : pi.basis s ji = std_basis R _ ji.1 (s ji.1 ji.2) := basis.apply_eq_iff.mpr (by simp) @[simp] lemma basis_repr (s : ∀ j, basis (ιs j) R (Ms j)) (x) (ji) : (pi.basis s).repr x ji = (s ji.1).repr (x ji.1) ji.2 := rfl end section variables (R η) /-- The basis on `η → R` where the `i`th basis vector is `function.update 0 i 1`. -/ noncomputable def basis_fun : basis η R (Π (j : η), R) := basis.of_equiv_fun (linear_equiv.refl _ _) @[simp] lemma basis_fun_apply [decidable_eq η] (i) : basis_fun R η i = std_basis R (λ (i : η), R) i 1 := by { simp only [basis_fun, basis.coe_of_equiv_fun, linear_equiv.refl_symm, linear_equiv.refl_apply, std_basis_apply] } @[simp] lemma basis_fun_repr (x : η → R) (i : η) : (pi.basis_fun R η).repr x i = x i := by simp [basis_fun] end end module end pi namespace matrix variables (R : Type*) (m n : Type*) [fintype m] [fintype n] [semiring R] /-- The standard basis of `matrix m n R`. -/ noncomputable def std_basis : basis (m × n) R (matrix m n R) := basis.reindex (pi.basis (λ (i : m), pi.basis_fun R n)) (equiv.sigma_equiv_prod _ _) variables {n m} lemma std_basis_eq_std_basis_matrix (i : n) (j : m) [decidable_eq n] [decidable_eq m] : std_basis R n m (i, j) = std_basis_matrix i j (1 : R) := begin ext a b, by_cases hi : i = a; by_cases hj : j = b, { simp [std_basis, hi, hj] }, { simp [std_basis, hi, hj, ne.symm hj, linear_map.std_basis_ne] }, { simp [std_basis, hi, hj, ne.symm hi, linear_map.std_basis_ne] }, { simp [std_basis, hi, hj, ne.symm hj, ne.symm hi, linear_map.std_basis_ne] } end end matrix
2d65f8ce4672672127229e4cdd16b509986d2ae8
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/int/basic.lean
1aaf655304910a50b8b376ca8c54b8d3a7578b43
[ "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
47,767
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, .. int.comm_ring, .. int.decidable_linear_order, .. int.nontrivial } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply mul_right_cancel' h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0 | (-[1+n]) _ := rfl | (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int
32b8bb7db3d7a687f10d0c681403d828b6f34c89
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/number_theory/sum_two_squares.lean
7156185247eb79f18b6a05438ba87d5b2cf140f2
[ "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
819
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 number_theory.zsqrtd.gaussian_int /-! # Sums of two squares Proof of Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum of two squares -/ open gaussian_int principal_ideal_ring namespace nat namespace prime /-- Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum of two squares -/ lemma sq_add_sq (p : ℕ) [hp : _root_.fact p.prime] (hp1 : p % 4 = 1) : ∃ a b : ℕ, a ^ 2 + b ^ 2 = p := begin apply sq_add_sq_of_nat_prime_of_not_irreducible p, rw [principal_ideal_ring.irreducible_iff_prime, prime_iff_mod_four_eq_three_of_nat_prime p, hp1], norm_num end end prime end nat
73c2e23b73dab445275276d2f9eb2654fb955f28
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Server/Watchdog.lean
52227bcff43bb07f281b697fd376aee38f36ec0a
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,282
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Init.Data.ByteArray import Std.Data.RBMap import Lean.Elab.Import import Lean.Data.Lsp import Lean.Server.Utils import Lean.Server.Requests /-! For general server architecture, see `README.md`. This module implements the watchdog process. ## Watchdog state Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes to the header and thus restart the corresponding worker, freeing its imports. TODO(WN): We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed (continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic, users may be confused about why the server seemingly stopped working for a single file. ## Watchdog <-> worker communication The watchdog process and its file worker processes communicate via LSP. If the necessity arises, we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications are forwarded to the corresponding file worker process, with the exception of these notifications: - textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to asynchronously receive LSP packets from the worker (e.g. request responses). - textDocument/didChange: Update the local file state. If the header was mutated, signal a shutdown to the file worker by closing the I/O channels. Then restart the file worker. Otherwise, forward the `didChange` notification. - textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state. Moreover, we don't implement the full protocol at this level: - Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker. - After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of the file. No additional `didOpen` notifications will be forwarded to the worker process. - `$/cancelRequest` notifications are forwarded to all file workers. - File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request. Similarly, they never receive a `didClose` notification. ## Watchdog <-> client communication The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add non-standard extensions in case they're needed, for example to communicate tactic state. -/ namespace Lean.Server.Watchdog open IO open Std (RBMap RBMap.empty) open Lsp open JsonRpc section Utils structure OpenDocument where meta : DocumentMeta headerAst : Syntax def workerCfg : Process.StdioConfig := { stdin := Process.Stdio.piped stdout := Process.Stdio.piped -- We pass workers' stderr through to the editor. stderr := Process.Stdio.inherit } /-- Events that worker-specific tasks signal to the main thread. -/ inductive WorkerEvent where /- A synthetic event signalling that the grouped edits should be processed. -/ | processGroupedEdits | terminated | crashed (e : IO.Error) | ioError (e : IO.Error) inductive WorkerState where /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker and when reading a request reply. In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task. Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored. Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file worker arrives. -/ | crashed (queuedMsgs : Array JsonRpc.Message) | running abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare private def parseHeaderAst (input : String) : IO Syntax := do let inputCtx := Parser.mkInputContext input "<input>" let (stx, _, _) ← Parser.parseHeader inputCtx return stx end Utils section FileWorker /-- A group of edits which will be processed at a future instant. -/ structure GroupedEdits where /-- When to process the edits. -/ applyTime : Nat params : DidChangeTextDocumentParams /-- Signals when `applyTime` has been reached. -/ signalTask : Task WorkerEvent /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/ queuedMsgs : Array JsonRpc.Message structure FileWorker where doc : OpenDocument proc : Process.Child workerCfg commTask : Task WorkerEvent state : WorkerState -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state /-- The pending requests map contains all requests that have been received from the LSP client, but were not answered yet. This includes the queued messages in the grouped edits. -/ pendingRequestsRef : IO.Ref PendingRequestMap groupedEditsRef : IO.Ref (Option GroupedEdits) namespace FileWorker def stdin (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdin def stdout (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdout def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit := fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty)) for ⟨id, _⟩ in pendingRequests do hError.writeLspResponseError { id := id, code := code, message := msg } partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification let rec loopAction : IO WorkerEvent := do let now ← monoMsNow let some ge ← fw.groupedEditsRef.get | throwServerError "Internal error: empty grouped edits reference in signal task" if ge.applyTime ≤ now then return WorkerEvent.processGroupedEdits else IO.sleep <| UInt32.ofNat <| ge.applyTime - now loopAction let t ← IO.asTask loopAction return t.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e end FileWorker end FileWorker section ServerM abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream /-- Command line arguments. -/ args : List String fileWorkersRef : IO.Ref FileWorkerMap /-- We store these to pass them to workers. -/ initParams : InitializeParams editDelay : Nat workerPath : System.FilePath abbrev ServerM := ReaderT ServerContext IO def updateFileWorkers (val : FileWorker) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val) def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do match (←(←read).fileWorkersRef.get).find? uri with | some fw => fw | none => throwServerError s!"Got unknown document URI ({uri})" def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri) def log (msg : String) : ServerM Unit := do let st ← read st.hLog.putStrLn msg st.hLog.flush /-- Creates a Task which forwards a worker's messages into the output stream until an event which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/ private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do let o := (←read).hOut let rec loop : ServerM WorkerEvent := do try let msg ← fw.stdout.readLspMessage if let Message.response id _ := msg then fw.erasePendingRequest id if let Message.responseError id _ _ _ := msg then fw.erasePendingRequest id -- Writes to Lean I/O channels are atomic, so these won't trample on each other. o.writeLspMessage msg catch err => -- If writeLspMessage from above errors we will block here, but the main task will -- quit eventually anyways if that happens let exitCode ← fw.proc.wait if exitCode = 0 then -- Worker was terminated fw.errorPendingRequests o ErrorCode.contentModified ("The file worker has been terminated. Either the header has changed," ++ " or the file was closed, or the server is shutting down.") return WorkerEvent.terminated else -- Worker crashed fw.errorPendingRequests o ErrorCode.internalError s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow in user code"}." return WorkerEvent.crashed err loop let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated task.map $ fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e def startFileWorker (m : DocumentMeta) : ServerM Unit := do publishProgressAtPos m 0 (← read).hOut let st ← read let headerAst ← parseHeaderAst m.text.source let workerProc ← Process.spawn { toStdioConfig := workerCfg cmd := st.workerPath.toString args := #["--worker"] ++ st.args.toArray } let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap) -- The task will never access itself, so this is fine let fw : FileWorker := { doc := ⟨m, headerAst⟩ proc := workerProc commTask := Task.pure WorkerEvent.terminated state := WorkerState.running pendingRequestsRef := pendingRequestsRef groupedEditsRef := ← IO.mkRef none } let commTask ← forwardMessages fw let fw : FileWorker := { fw with commTask := commTask } fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩ fw.stdin.writeLspNotification { method := "textDocument/didOpen" param := { textDocument := { uri := m.uri languageId := "lean" version := m.version text := m.text.source } : DidOpenTextDocumentParams } } updateFileWorkers fw def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do /- The file worker must have crashed just when we were about to terminate it! That's fine - just forget about it then. (on didClose we won't need the crashed file worker anymore, when the header changed we'll start a new one right after anyways and when we're shutting down the server it's over either way.) -/ try (←findFileWorker uri).stdin.writeLspMessage (Message.notification "exit" none) catch err => () eraseFileWorker uri def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do updateFileWorkers { ←findFileWorker uri with state := WorkerState.crashed queuedMsgs } /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed and restarts the file worker if the `crashed` flag was already set. Messages that couldn't be sent can be queued up via the queueFailedMessage flag and will be discharged after the FileWorker is restarted. -/ def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) : ServerM Unit := do let fw ← findFileWorker uri let pendingEdit ← fw.groupedEditsRef.modifyGet fun | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg }) | none => (false, none) if pendingEdit then return match fw.state with | WorkerState.crashed queuedMsgs => let mut queuedMsgs := queuedMsgs if queueFailedMessage then queuedMsgs := queuedMsgs.push msg if !restartCrashedWorker then return -- restart the crashed FileWorker eraseFileWorker uri startFileWorker fw.doc.meta let newFw ← findFileWorker uri let mut crashedMsgs := #[] -- try to discharge all queued msgs, tracking the ones that we can't discharge for msg in queuedMsgs do try newFw.stdin.writeLspMessage msg catch _ => crashedMsgs := crashedMsgs.push msg if ¬ crashedMsgs.isEmpty then handleCrash uri crashedMsgs | WorkerState.running => let initialQueuedMsgs := if queueFailedMessage then #[msg] else #[] try fw.stdin.writeLspMessage msg catch _ => handleCrash uri initialQueuedMsgs end ServerM section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleEdits (fw : FileWorker) : ServerM Unit := do let some ge ← fw.groupedEditsRef.modifyGet (·, none) | throwServerError "Internal error: empty grouped edits reference" let doc := ge.params.textDocument let changes := ge.params.contentChanges let oldDoc := fw.doc let some newVersion ← pure doc.version? | throwServerError "Expected version number" if newVersion <= oldDoc.meta.version then throwServerError "Got outdated version number" if changes.isEmpty then return let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩ let newHeaderAst ← parseHeaderAst newDocText.source if newHeaderAst != oldDoc.headerAst then terminateFileWorker doc.uri startFileWorker newMeta else let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩ updateFileWorkers { fw with doc := newDoc } tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true) for msg in ge.queuedMsgs do tryWriteMessage doc.uri msg def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit := terminateFileWorker p.textDocument.uri def handleCancelRequest (p : CancelParams) : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, fw⟩ in fileWorkers do -- Cancelled requests still require a response, so they can't be removed -- from the pending requests map. if (← fw.pendingRequestsRef.get).contains p.id then tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false) def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit := tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do match (← routeLspRequest method params) with | Except.error e => (←read).hOut.writeLspResponseError <| e.toLspResponseError id | Except.ok uri => let fw ← try findFileWorker uri catch _ => -- VS Code sometimes sends us requests just after closing a file? -- This is permitted by the spec, but seems pointless, and there's not much we can do, -- so we return an error instead. (←read).hOut.writeLspResponseError { id := id code := ErrorCode.contentModified message := s!"Cannot process request to closed file '{uri}'" } return let r := Request.mk id method params fw.pendingRequestsRef.modify (·.insert id r) tryWriteMessage uri r def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler) match method with | "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen /- NOTE: textDocument/didChange is handled in the main loop. -/ | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method) | "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method) | _ => if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored (←read).hLog.putStrLn s!"Got unsupported notification: {method}" end MessageHandling section MainLoop def shutdown : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, _⟩ in fileWorkers do terminateFileWorker uri for ⟨_, fw⟩ in fileWorkers do discard <| IO.wait fw.commTask inductive ServerEvent where | workerEvent (fw : FileWorker) (ev : WorkerEvent) | clientMsg (msg : JsonRpc.Message) | clientError (e : IO.Error) def runClientTask : ServerM (Task ServerEvent) := do let st ← read let readMsgAction : IO ServerEvent := do /- Runs asynchronously. -/ let msg ← st.hIn.readLspMessage ServerEvent.clientMsg msg let clientTask := (←IO.asTask readMsgAction).map $ fun | Except.ok ev => ev | Except.error e => ServerEvent.clientError e return clientTask partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do let st ← read let workers ← st.fileWorkersRef.get let mut workerTasks := #[] for (_, fw) in workers do if let WorkerState.running := fw.state then workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw) if let some ge ← fw.groupedEditsRef.get then workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw) let ev ← IO.waitAny (workerTasks.push clientTask |>.toList) match ev with | ServerEvent.clientMsg msg => match msg with | Message.request id "shutdown" _ => shutdown st.hOut.writeLspResponse ⟨id, Json.null⟩ | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop (←runClientTask) | Message.notification "textDocument/didChange" (some params) => let p ← parseParams DidChangeTextDocumentParams (toJson params) let fw ← findFileWorker p.textDocument.uri let now ← monoMsNow /- We wait `editDelay`ms since last edit before applying the changes. -/ let applyTime := now + st.editDelay let queuedMsgs? ← fw.groupedEditsRef.modifyGet fun | some ge => (some ge.queuedMsgs, some { ge with applyTime := applyTime params.textDocument := p.textDocument params.contentChanges := ge.params.contentChanges ++ p.contentChanges -- drain now-outdated messages and respond with `contentModified` below queuedMsgs := #[] }) | none => (none, some { applyTime := applyTime params := p /- This is overwritten just below. -/ signalTask := Task.pure WorkerEvent.processGroupedEdits queuedMsgs := #[] }) match queuedMsgs? with | some queuedMsgs => for msg in queuedMsgs do match msg with | JsonRpc.Message.request id _ _ => fw.erasePendingRequest id (← read).hOut.writeLspResponseError { id := id code := ErrorCode.contentModified message := "File changed." } | _ => () -- notifications do not need to be cancelled | _ => let t ← fw.runEditsSignalTask fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } ) mainLoop (←runClientTask) | Message.notification method (some params) => handleNotification method (toJson params) mainLoop (←runClientTask) | _ => throwServerError "Got invalid JSON-RPC message" | ServerEvent.clientError e => throw e | ServerEvent.workerEvent fw ev => match ev with | WorkerEvent.processGroupedEdits => handleEdits fw mainLoop clientTask | WorkerEvent.ioError e => throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}" | WorkerEvent.crashed e => handleCrash fw.doc.meta.uri #[] mainLoop clientTask | WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed" end MainLoop def mkLeanServerCapabilities : ServerCapabilities := { textDocumentSync? := some { openClose := true change := TextDocumentSyncKind.incremental willSave := false willSaveWaitUntil := false save? := none } -- refine completionProvider? := some { triggerCharacters? := some #["."] } hoverProvider := true declarationProvider := true definitionProvider := true typeDefinitionProvider := true documentHighlightProvider := true documentSymbolProvider := true semanticTokensProvider? := some { legend := { tokenTypes := SemanticTokenType.names tokenModifiers := #[] } full := true range := true } } def initAndRunWatchdogAux : ServerM Unit := do let st ← read try discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams let clientTask ← runClientTask mainLoop clientTask let Message.notification "exit" none ← st.hIn.readLspMessage | throwServerError "Expected an exit notification" catch err => shutdown throw err def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do let mut workerPath ← IO.appPath if let some path := (←IO.getEnv "LEAN_SYSROOT") then workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then workerPath := System.FilePath.mk path let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap) let i ← maybeTee "wdIn.txt" false i let o ← maybeTee "wdOut.txt" true o let e ← maybeTee "wdErr.txt" true e let initRequest ← i.readLspRequestAs "initialize" InitializeParams o.writeLspResponse { id := initRequest.id result := { capabilities := mkLeanServerCapabilities serverInfo? := some { name := "Lean 4 server" version? := "0.0.1" } : InitializeResult } } ReaderT.run initAndRunWatchdogAux { hIn := i hOut := o hLog := e args := args fileWorkersRef := fileWorkersRef initParams := initRequest.param editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200 workerPath := workerPath : ServerContext } @[export lean_server_watchdog_main] def watchdogMain (args : List String) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWatchdog args i o e return 0 catch err => e.putStrLn s!"Watchdog error: {err}" return 1 end Lean.Server.Watchdog
1e114499653c718d8f549902d5fcb4618cfbbd8f
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/alternating.lean
2d3cd2ddb8b22e42d4ece3b23ac9da21e5ad1b49
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,460
lean
/- Copyright (c) 2020 Zhangir Azerbayev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Zhangir Azerbayev -/ import linear_algebra.multilinear.tensor_product import linear_algebra.linear_independent import group_theory.perm.sign import group_theory.perm.subgroup import data.equiv.fin import group_theory.quotient_group /-! # Alternating Maps We construct the bundled function `alternating_map`, which extends `multilinear_map` with all the arguments of the same type. ## Main definitions * `alternating_map R M N ι` is the space of `R`-linear alternating maps from `ι → M` to `N`. * `f.map_eq_zero_of_eq` expresses that `f` is zero when two inputs are equal. * `f.map_swap` expresses that `f` is negated when two inputs are swapped. * `f.map_perm` expresses how `f` varies by a sign change under a permutation of its inputs. * An `add_comm_monoid`, `add_comm_group`, and `module` structure over `alternating_map`s that matches the definitions over `multilinear_map`s. * `multilinear_map.alternatization`, which makes an alternating map out of a non-alternating one. * `alternating_map.dom_coprod`, which behaves as a product between two alternating maps. ## Implementation notes `alternating_map` is defined in terms of `map_eq_zero_of_eq`, as this is easier to work with than using `map_swap` as a definition, and does not require `has_neg N`. `alternating_map`s are provided with a coercion to `multilinear_map`, along with a set of `norm_cast` lemmas that act on the algebraic structure: * `alternating_map.coe_add` * `alternating_map.coe_zero` * `alternating_map.coe_sub` * `alternating_map.coe_neg` * `alternating_map.coe_smul` -/ -- semiring / add_comm_monoid variables {R : Type*} [semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] -- semiring / add_comm_group variables {M' : Type*} [add_comm_group M'] [module R M'] variables {N' : Type*} [add_comm_group N'] [module R N'] variables {ι : Type*} [decidable_eq ι] set_option old_structure_cmd true section variables (R M N ι) /-- An alternating map is a multilinear map that vanishes when two of its arguments are equal. -/ structure alternating_map extends multilinear_map R (λ i : ι, M) N := (map_eq_zero_of_eq' : ∀ (v : ι → M) (i j : ι) (h : v i = v j) (hij : i ≠ j), to_fun v = 0) end /-- The multilinear map associated to an alternating map -/ add_decl_doc alternating_map.to_multilinear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! Basic coercion simp lemmas, largely copied from `ring_hom` and `multilinear_map` -/ section coercions instance : has_coe_to_fun (alternating_map R M N ι) (λ _, (ι → M) → N) := ⟨λ x, x.to_fun⟩ initialize_simps_projections alternating_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) = f := rfl theorem congr_fun {f g : alternating_map R M N ι} (h : f = g) (x : ι → M) : f x = g x := congr_arg (λ h : alternating_map R M N ι, h x) h theorem congr_arg (f : alternating_map R M N ι) {x y : ι → M} (h : x = y) : f x = f y := congr_arg (λ x : ι → M, f x) h theorem coe_injective : injective (coe_fn : alternating_map R M N ι → ((ι → M) → N)) := λ f g h, by { cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : alternating_map R M N ι} : (f : (ι → M) → N) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : alternating_map R M N ι} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : alternating_map R M N ι} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : has_coe (alternating_map R M N ι) (multilinear_map R (λ i : ι, M) N) := ⟨λ x, x.to_multilinear_map⟩ @[simp, norm_cast] lemma coe_multilinear_map : ⇑(f : multilinear_map R (λ i : ι, M) N) = f := rfl lemma coe_multilinear_map_injective : function.injective (coe : alternating_map R M N ι → multilinear_map R (λ i : ι, M) N) := λ x y h, ext $ multilinear_map.congr_fun h @[simp] lemma to_multilinear_map_eq_coe : f.to_multilinear_map = f := rfl @[simp] lemma coe_multilinear_map_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = ⟨f, h₁, h₂⟩ := rfl end coercions /-! ### Simp-normal forms of the structure fields These are expressed in terms of `⇑f` instead of `f.to_fun`. -/ @[simp] lemma map_add (i : ι) (x y : M) : f (update v i (x + y)) = f (update v i x) + f (update v i y) := f.to_multilinear_map.map_add' v i x y @[simp] lemma map_sub (i : ι) (x y : M') : g' (update v' i (x - y)) = g' (update v' i x) - g' (update v' i y) := g'.to_multilinear_map.map_sub v' i x y @[simp] lemma map_neg (i : ι) (x : M') : g' (update v' i (-x)) = -g' (update v' i x) := g'.to_multilinear_map.map_neg v' i x @[simp] lemma map_smul (i : ι) (r : R) (x : M) : f (update v i (r • x)) = r • f (update v i x) := f.to_multilinear_map.map_smul' v i r x @[simp] lemma map_eq_zero_of_eq (v : ι → M) {i j : ι} (h : v i = v j) (hij : i ≠ j) : f v = 0 := f.map_eq_zero_of_eq' v i j h hij lemma map_coord_zero {m : ι → M} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_update_zero (m : ι → M) (i : ι) : f (update m i 0) = 0 := f.to_multilinear_map.map_update_zero m i @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero /-! ### Algebraic structure inherited from `multilinear_map` `alternating_map` carries the same `add_comm_monoid`, `add_comm_group`, and `module` structure as `multilinear_map` -/ instance : has_add (alternating_map R M N ι) := ⟨λ a b, { map_eq_zero_of_eq' := λ v i j h hij, by simp [a.map_eq_zero_of_eq v h hij, b.map_eq_zero_of_eq v h hij], ..(a + b : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma add_apply : (f + f') v = f v + f' v := rfl @[norm_cast] lemma coe_add : (↑(f + f') : multilinear_map R (λ i : ι, M) N) = f + f' := rfl instance : has_zero (alternating_map R M N ι) := ⟨{map_eq_zero_of_eq' := λ v i j h hij, by simp, ..(0 : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma zero_apply : (0 : alternating_map R M N ι) v = 0 := rfl @[norm_cast] lemma coe_zero : ((0 : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = 0 := rfl instance : inhabited (alternating_map R M N ι) := ⟨0⟩ instance : add_comm_monoid (alternating_map R M N ι) := { zero := 0, add := (+), zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], add_assoc := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N)) }, nsmul_zero' := by { intros, ext, simp [add_smul], }, nsmul_succ' := by { intros, ext, simp [add_smul, nat.succ_eq_one_add], } } instance : has_neg (alternating_map R M N' ι) := ⟨λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(-(f : multilinear_map R (λ i : ι, M) N')) }⟩ @[simp] lemma neg_apply (m : ι → M) : (-g) m = -(g m) := rfl @[norm_cast] lemma coe_neg : ((-g : alternating_map R M N' ι) : multilinear_map R (λ i : ι, M) N') = -g := rfl instance : has_sub (alternating_map R M N' ι) := ⟨λ f g, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij, g.map_eq_zero_of_eq v h hij], ..(f - g : multilinear_map R (λ i : ι, M) N') }⟩ @[simp] lemma sub_apply (m : ι → M) : (g - g₂) m = g m - g₂ m := rfl @[norm_cast] lemma coe_sub : (↑(g - g₂) : multilinear_map R (λ i : ι, M) N') = g - g₂ := rfl instance : add_comm_group (alternating_map R M N' ι) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N')) }, gsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N')) }, gsmul_zero' := _, gsmul_succ' := _, gsmul_neg' := _, .. alternating_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one, gsmul_coe_nat] section distrib_mul_action variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : has_scalar S (alternating_map R M N ι) := ⟨λ c f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..((c • f : multilinear_map R (λ i : ι, M) N)) }⟩ @[simp] lemma smul_apply (c : S) (m : ι → M) : (c • f) m = c • f m := rfl @[norm_cast] lemma coe_smul (c : S): ((c • f : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = c • f := rfl instance : distrib_mul_action S (alternating_map R M N ι) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {S : Type*} [semiring S] [module S N] [smul_comm_class R S N] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module S (alternating_map R M N ι) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } end module section variables (R N) /-- The evaluation map from `ι → N` to `N` at a given `i` is alternating when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i : ι) : alternating_map R N N ι := { to_fun := function.eval i, map_eq_zero_of_eq' := λ v i j hv hij, (hij $ subsingleton.elim _ _).elim, ..multilinear_map.of_subsingleton R N i } end end alternating_map /-! ### Composition with linear maps -/ namespace linear_map variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] /-- Composing a alternating map with a linear map gives again a alternating map. -/ def comp_alternating_map (g : N →ₗ[R] N₂) : alternating_map R M N ι →+ alternating_map R M N₂ ι := { to_fun := λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(g.comp_multilinear_map (f : multilinear_map R (λ _ : ι, M) N)) }, map_zero' := by { ext, simp }, map_add' := λ a b, by { ext, simp } } @[simp] lemma coe_comp_alternating_map (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) : ⇑(g.comp_alternating_map f) = g ∘ f := rfl lemma comp_alternating_map_apply (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) (m : ι → M) : g.comp_alternating_map f m = g (f m) := rfl end linear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! ### Other lemmas from `multilinear_map` -/ section open_locale big_operators lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M) (m : ι → M): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := f.to_multilinear_map.map_update_sum t i g m end /-! ### Theorems specific to alternating maps Various properties of reordered and repeated inputs which follow from `alternating_map.map_eq_zero_of_eq`. -/ lemma map_update_self {i j : ι} (hij : i ≠ j) : f (function.update v i (v j)) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij.symm]) hij lemma map_update_update {i j : ι} (hij : i ≠ j) (m : M) : f (function.update (function.update v i m) j m) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij, function.update_same]) hij lemma map_swap_add {i j : ι} (hij : i ≠ j) : f (v ∘ equiv.swap i j) + f v = 0 := begin rw equiv.comp_swap_eq_update, convert f.map_update_update v hij (v i + v j), simp [f.map_update_self _ hij, f.map_update_self _ hij.symm, function.update_comm hij (v i + v j) (v _) v, function.update_comm hij.symm (v i) (v i) v], end lemma map_add_swap {i j : ι} (hij : i ≠ j) : f v + f (v ∘ equiv.swap i j) = 0 := by { rw add_comm, exact f.map_swap_add v hij } lemma map_swap {i j : ι} (hij : i ≠ j) : g (v ∘ equiv.swap i j) = - g v := eq_neg_of_add_eq_zero (g.map_swap_add v hij) lemma map_perm [fintype ι] (v : ι → M) (σ : equiv.perm ι) : g (v ∘ σ) = σ.sign • g v := begin apply equiv.perm.swap_induction_on' σ, { simp }, { intros s x y hxy hI, simpa [g.map_swap (v ∘ s) hxy, equiv.perm.sign_swap hxy] using hI, } end lemma map_congr_perm [fintype ι] (σ : equiv.perm ι) : g v = σ.sign • g (v ∘ σ) := by { rw [g.map_perm, smul_smul], simp } lemma coe_dom_dom_congr [fintype ι] (σ : equiv.perm ι) : (g : multilinear_map R (λ _ : ι, M) N').dom_dom_congr σ = σ.sign • (g : multilinear_map R (λ _ : ι, M) N') := multilinear_map.ext $ λ v, g.map_perm v σ /-- If the arguments are linearly dependent then the result is `0`. -/ lemma map_linear_dependent {K : Type*} [ring K] {M : Type*} [add_comm_group M] [module K M] {N : Type*} [add_comm_group N] [module K N] [no_zero_smul_divisors K N] (f : alternating_map K M N ι) (v : ι → M) (h : ¬linear_independent K v) : f v = 0 := begin obtain ⟨s, g, h, i, hi, hz⟩ := linear_dependent_iff.mp h, suffices : f (update v i (g i • v i)) = 0, { rw [f.map_smul, function.update_eq_self, smul_eq_zero] at this, exact or.resolve_left this hz, }, conv at h in (g _ • v _) { rw ←if_t_t (i = x) (g _ • v _), }, rw [finset.sum_ite, finset.filter_eq, finset.filter_ne, if_pos hi, finset.sum_singleton, add_eq_zero_iff_eq_neg] at h, rw [h, f.map_neg, f.map_update_sum, neg_eq_zero, finset.sum_eq_zero], intros j hj, obtain ⟨hij, _⟩ := finset.mem_erase.mp hj, rw [f.map_smul, f.map_update_self _ hij.symm, smul_zero], end end alternating_map open_locale big_operators namespace multilinear_map open equiv variables [fintype ι] private lemma alternization_map_eq_zero_of_eq_aux (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) (i j : ι) (i_ne_j : i ≠ j) (hv : v i = v j) : (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ) v = 0 := begin rw sum_apply, exact finset.sum_involution (λ σ _, swap i j * σ) (λ σ _, by simp [perm.sign_swap i_ne_j, apply_swap_eq_self hv]) (λ σ _ _, (not_congr swap_mul_eq_iff).mpr i_ne_j) (λ σ _, finset.mem_univ _) (λ σ _, swap_mul_involutive i j σ) end /-- Produce an `alternating_map` out of a `multilinear_map`, by summing over all argument permutations. -/ def alternatization : multilinear_map R (λ i : ι, M) N' →+ alternating_map R M N' ι := { to_fun := λ m, { to_fun := ⇑(∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ), map_eq_zero_of_eq' := λ v i j hvij hij, alternization_map_eq_zero_of_eq_aux m v i j hij hvij, .. (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ)}, map_add' := λ a b, begin ext, simp only [ finset.sum_add_distrib, smul_add, add_apply, dom_dom_congr_apply, alternating_map.add_apply, alternating_map.coe_mk, smul_apply, sum_apply], end, map_zero' := begin ext, simp only [ finset.sum_const_zero, smul_zero, zero_apply, dom_dom_congr_apply, alternating_map.zero_apply, alternating_map.coe_mk, smul_apply, sum_apply], end } lemma alternatization_def (m : multilinear_map R (λ i : ι, M) N') : ⇑(alternatization m) = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := rfl lemma alternatization_coe (m : multilinear_map R (λ i : ι, M) N') : ↑m.alternatization = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := coe_injective rfl lemma alternatization_apply (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) : alternatization m v = ∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ v := by simp only [alternatization_def, smul_apply, sum_apply] end multilinear_map namespace alternating_map /-- Alternatizing a multilinear map that is already alternating results in a scale factor of `n!`, where `n` is the number of inputs. -/ lemma coe_alternatization [fintype ι] (a : alternating_map R M N' ι) : (↑a : multilinear_map R (λ ι, M) N').alternatization = nat.factorial (fintype.card ι) • a := begin apply alternating_map.coe_injective, simp_rw [multilinear_map.alternatization_def, coe_dom_dom_congr, smul_smul, int.units_mul_self, one_smul, finset.sum_const, finset.card_univ, fintype.card_perm, ←coe_multilinear_map, coe_smul], end end alternating_map namespace linear_map variables {N'₂ : Type*} [add_comm_group N'₂] [module R N'₂] [fintype ι] /-- Composition with a linear map before and after alternatization are equivalent. -/ lemma comp_multilinear_map_alternatization (g : N' →ₗ[R] N'₂) (f : multilinear_map R (λ _ : ι, M) N') : (g.comp_multilinear_map f).alternatization = g.comp_alternating_map (f.alternatization) := by { ext, simp [multilinear_map.alternatization_def] } end linear_map section coprod open_locale big_operators open_locale tensor_product variables {ιa ιb : Type*} [decidable_eq ιa] [decidable_eq ιb] [fintype ιa] [fintype ιb] variables {R' : Type*} {Mᵢ N₁ N₂ : Type*} [comm_semiring R'] [add_comm_group N₁] [module R' N₁] [add_comm_group N₂] [module R' N₂] [add_comm_monoid Mᵢ] [module R' Mᵢ] namespace equiv.perm /-- Elements which are considered equivalent if they differ only by swaps within α or β -/ abbreviation mod_sum_congr (α β : Type*) := quotient_group.quotient (equiv.perm.sum_congr_hom α β).range lemma mod_sum_congr.swap_smul_involutive {α β : Type*} [decidable_eq (α ⊕ β)] (i j : α ⊕ β) : function.involutive (has_scalar.smul (equiv.swap i j) : mod_sum_congr α β → mod_sum_congr α β) := λ σ, begin apply σ.induction_on' (λ σ, _), exact _root_.congr_arg quotient.mk' (equiv.swap_mul_involutive i j σ) end end equiv.perm namespace alternating_map open equiv /-- summand used in `alternating_map.dom_coprod` -/ def dom_coprod.summand (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗[R'] N₂) := quotient.lift_on' σ (λ σ, σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ) (λ σ₁ σ₂ ⟨⟨sl, sr⟩, h⟩, begin ext v, simp only [multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, coe_multilinear_map, multilinear_map.smul_apply], replace h := inv_mul_eq_iff_eq_mul.mp h.symm, have : (σ₁ * perm.sum_congr_hom _ _ (sl, sr)).sign = σ₁.sign * (sl.sign * sr.sign) := by simp, rw [h, this, mul_smul, mul_smul, smul_left_cancel_iff, ←tensor_product.tmul_smul, tensor_product.smul_tmul'], simp only [sum.map_inr, perm.sum_congr_hom_apply, perm.sum_congr_apply, sum.map_inl, function.comp_app, perm.coe_mul], rw [←a.map_congr_perm (λ i, v (σ₁ _)), ←b.map_congr_perm (λ i, v (σ₁ _))], end) lemma dom_coprod.summand_mk' (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : equiv.perm (ιa ⊕ ιb)) : dom_coprod.summand a b (quotient.mk' σ) = σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ := rfl /-- Swapping elements in `σ` with equal values in `v` results in an addition that cancels -/ lemma dom_coprod.summand_add_swap_smul_eq_zero (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : dom_coprod.summand a b σ v + dom_coprod.summand a b (swap i j • σ) v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', mul_action.quotient.smul_mk, dom_coprod.summand], rw [perm.sign_mul, perm.sign_swap hij], simp only [one_mul, units.neg_mul, function.comp_app, units.neg_smul, perm.coe_mul, units.coe_neg, multilinear_map.smul_apply, multilinear_map.neg_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply], convert add_right_neg _; { ext k, rw equiv.apply_swap_eq_self hv }, end /-- Swapping elements in `σ` with equal values in `v` result in zero if the swap has no effect on the quotient. -/ lemma dom_coprod.summand_eq_zero_of_smul_invariant (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : swap i j • σ = σ → dom_coprod.summand a b σ v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', multilinear_map.smul_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, dom_coprod.summand], intro hσ, with_cases { cases hi : σ⁻¹ i; cases hj : σ⁻¹ j; rw perm.inv_eq_iff_eq at hi hj; substs hi hj, }, case [sum.inl sum.inr : i' j', sum.inr sum.inl : i' j'] { -- the term pairs with and cancels another term all_goals { obtain ⟨⟨sl, sr⟩, hσ⟩ := quotient.exact' hσ, }, work_on_goal 0 { replace hσ := equiv.congr_fun hσ (sum.inl i'), }, work_on_goal 1 { replace hσ := equiv.congr_fun hσ (sum.inr i'), }, all_goals { rw [←equiv.mul_swap_eq_swap_mul, mul_inv_rev, equiv.swap_inv, inv_mul_cancel_right] at hσ, simpa using hσ, }, }, case [sum.inr sum.inr : i' j', sum.inl sum.inl : i' j'] { -- the term does not pair but is zero all_goals { convert smul_zero _, }, work_on_goal 0 { convert tensor_product.tmul_zero _ _, }, work_on_goal 1 { convert tensor_product.zero_tmul _ _, }, all_goals { exact alternating_map.map_eq_zero_of_eq _ _ hv (λ hij', hij (hij' ▸ rfl)), } }, end /-- Like `multilinear_map.dom_coprod`, but ensures the result is also alternating. Note that this is usually defined (for instance, as used in Proposition 22.24 in [Gallier2011Notes]) over integer indices `ιa = fin n` and `ιb = fin m`, as $$ (f \wedge g)(u_1, \ldots, u_{m+n}) = \sum_{\operatorname{shuffle}(m, n)} \operatorname{sign}(\sigma) f(u_{\sigma(1)}, \ldots, u_{\sigma(m)}) g(u_{\sigma(m+1)}, \ldots, u_{\sigma(m+n)}), $$ where $\operatorname{shuffle}(m, n)$ consists of all permutations of $[1, m+n]$ such that $\sigma(1) < \cdots < \sigma(m)$ and $\sigma(m+1) < \cdots < \sigma(m+n)$. Here, we generalize this by replacing: * the product in the sum with a tensor product * the filtering of $[1, m+n]$ to shuffles with an isomorphic quotient * the additions in the subscripts of $\sigma$ with an index of type `sum` The specialized version can be obtained by combining this definition with `fin_sum_fin_equiv` and `algebra.lmul'`. -/ @[simps] def dom_coprod (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := { to_fun := λ v, ⇑(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) v, map_eq_zero_of_eq' := λ v i j hv hij, begin dsimp only, rw multilinear_map.sum_apply, exact finset.sum_involution (λ σ _, equiv.swap i j • σ) (λ σ _, dom_coprod.summand_add_swap_smul_eq_zero a b σ hv hij) (λ σ _, mt $ dom_coprod.summand_eq_zero_of_smul_invariant a b σ hv hij) (λ σ _, finset.mem_univ _) (λ σ _, equiv.perm.mod_sum_congr.swap_smul_involutive i j σ), end, ..(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) } lemma dom_coprod_coe (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (↑(a.dom_coprod b) : multilinear_map R' (λ _, Mᵢ) _) = ∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ := multilinear_map.ext $ λ _, rfl /-- A more bundled version of `alternating_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : (alternating_map R' Mᵢ N₁ ιa ⊗[R'] alternating_map R' Mᵢ N₂ ιb) →ₗ[R'] alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := tensor_product.lift $ by refine linear_map.mk₂ R' (dom_coprod) (λ m₁ m₂ n, _) (λ c m n, _) (λ m n₁ n₂, _) (λ c m n, _); { ext, simp only [dom_coprod_apply, add_apply, smul_apply, ←finset.sum_add_distrib, finset.smul_sum, multilinear_map.sum_apply, dom_coprod.summand], congr, ext σ, apply σ.induction_on' (λ σ, _), simp only [quotient.lift_on'_mk', coe_add, coe_smul, multilinear_map.smul_apply, ←multilinear_map.dom_coprod'_apply], simp only [tensor_product.add_tmul, ←tensor_product.smul_tmul', tensor_product.tmul_add, tensor_product.tmul_smul, linear_map.map_add, linear_map.map_smul], rw ←smul_add <|> rw smul_comm, congr } @[simp] lemma dom_coprod'_apply (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : dom_coprod' (a ⊗ₜ[R'] b) = dom_coprod a b := by simp only [dom_coprod', tensor_product.lift.tmul, linear_map.mk₂_apply] end alternating_map open equiv /-- A helper lemma for `multilinear_map.dom_coprod_alternization`. -/ lemma multilinear_map.dom_coprod_alternization_coe (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : multilinear_map.dom_coprod ↑a.alternatization ↑b.alternatization = ∑ (σa : perm ιa) (σb : perm ιb), σa.sign • σb.sign • multilinear_map.dom_coprod (a.dom_dom_congr σa) (b.dom_dom_congr σb) := begin simp_rw [←multilinear_map.dom_coprod'_apply, multilinear_map.alternatization_coe], simp_rw [tensor_product.sum_tmul, tensor_product.tmul_sum, linear_map.map_sum, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower], end open alternating_map /-- Computing the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` is the same as computing the `alternating_map.dom_coprod` of the `multilinear_map.alternatization`s. -/ lemma multilinear_map.dom_coprod_alternization (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : (multilinear_map.dom_coprod a b).alternatization = a.alternatization.dom_coprod b.alternatization := begin apply coe_multilinear_map_injective, rw [dom_coprod_coe, multilinear_map.alternatization_coe, finset.sum_partition (quotient_group.left_rel (perm.sum_congr_hom ιa ιb).range)], congr' 1, ext1 σ, apply σ.induction_on' (λ σ, _), -- unfold the quotient mess left by `finset.sum_partition` conv in (_ = quotient.mk' _) { change quotient.mk' _ = quotient.mk' _, rw quotient.eq', rw [quotient_group.left_rel], dsimp only [setoid.r] }, -- eliminate a multiplication have : @finset.univ (perm (ιa ⊕ ιb)) _ = finset.univ.image ((*) σ) := (finset.eq_univ_iff_forall.mpr $ λ a, let ⟨a', ha'⟩ := mul_left_surjective σ a in finset.mem_image.mpr ⟨a', finset.mem_univ _, ha'⟩).symm, rw [this, finset.image_filter], simp only [function.comp, mul_inv_rev, inv_mul_cancel_right, subgroup.inv_mem_iff], simp only [monoid_hom.mem_range], -- needs to be separate from the above `simp only` rw [finset.filter_congr_decidable, finset.univ_filter_exists (perm.sum_congr_hom ιa ιb), finset.sum_image (λ x _ y _ (h : _ = _), mul_right_injective _ h), finset.sum_image (λ x _ y _ (h : _ = _), perm.sum_congr_hom_injective h)], dsimp only, -- now we're ready to clean up the RHS, pulling out the summation rw [dom_coprod.summand_mk', multilinear_map.dom_coprod_alternization_coe, ←finset.sum_product', finset.univ_product_univ, ←multilinear_map.dom_dom_congr_equiv_apply, add_equiv.map_sum, finset.smul_sum], congr' 1, ext1 ⟨al, ar⟩, dsimp only, -- pull out the pair of smuls on the RHS, by rewriting to `_ →ₗ[ℤ] _` and back rw [←add_equiv.coe_to_add_monoid_hom, ←add_monoid_hom.coe_to_int_linear_map, linear_map.map_smul_of_tower, linear_map.map_smul_of_tower, add_monoid_hom.coe_to_int_linear_map, add_equiv.coe_to_add_monoid_hom, multilinear_map.dom_dom_congr_equiv_apply], -- pick up the pieces rw [multilinear_map.dom_dom_congr_mul, perm.sign_mul, perm.sum_congr_hom_apply, multilinear_map.dom_coprod_dom_dom_congr_sum_congr, perm.sign_sum_congr, mul_smul, mul_smul], end /-- Taking the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` of two `alternating_map`s gives a scaled version of the `alternating_map.coprod` of those maps. -/ lemma multilinear_map.dom_coprod_alternization_eq (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (multilinear_map.dom_coprod a b : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗ N₂)) .alternatization = ((fintype.card ιa).factorial * (fintype.card ιb).factorial) • a.dom_coprod b := begin rw [multilinear_map.dom_coprod_alternization, coe_alternatization, coe_alternatization, mul_smul, ←dom_coprod'_apply, ←dom_coprod'_apply, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower dom_coprod', linear_map.map_smul_of_tower dom_coprod'], -- typeclass resolution is a little confused here apply_instance, apply_instance, end end coprod
b77bc7dae8c2dacc969c9f77047cc0cd85ad5f44
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/sheaves/stalks.lean
4c6458ba50c01410b8abf1b9b47294709bfdf36d
[ "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
16,062
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.limits.types import tactic.elementwise /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the following functor (nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ ⥤ C where the functor on the left is the inclusion of categories and the functor on the right is `F`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. In `is_iso_iff_stalk_functor_map_iso`, we prove that a map `f : F ⟶ G` between `Type`-valued sheaves is an isomorphism if and only if all the maps `F.stalk x ⟶ G.stalk x` (given by the stalk functor on `f`) are isomorphisms. For a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) /-- For a `Type` valued presheaf, every point in a stalk is a germ. -/ lemma germ_exist (F : X.presheaf (Type v)) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective _ (colimit.is_colimit _) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf (Type v)) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin erw types.filtered_colimit.colimit_eq_iff at h, rcases h with ⟨W, iU, iV, e⟩, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end @[simp] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op @[simp] lemma germ_res_apply (F : X.presheaf (Type v)) {U V : opens X} (i : U ⟶ V) (x : U) (f : F.obj (op V)) : germ F x (F.map i.op f) = germ F (i x : V) f := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f /-- A variant when the open sets are written in `(opens X)ᵒᵖ`. -/ @[simp] lemma germ_res_apply' (F : X.presheaf (Type v)) {U V : (opens X)ᵒᵖ} (i : V ⟶ U) (x : unop U) (f : F.obj V) : germ F x (F.map i f) = germ F (i.unop x : unop V) f := let i' : (⟨unop U, x.2⟩ : open_nhds x.1) ⟶ ⟨unop V, (i.unop x : unop V).2⟩ := i.unop in congr_fun (colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op) f section local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext {D : Type u} [category.{v} D] [concrete_category D] [has_colimits D] (F : X.presheaf D) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] end lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { op_induction U, cases U with U hxU, exact ih U hxU } /-- If two sections agree on all stalks, they must be equal -/ lemma section_ext (F : sheaf (Type v) X) (U : opens X) (s t : F.presheaf.obj (op U)) (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, dsimp, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end @[simp, reassoc] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) @[simp] lemma stalk_functor_map_germ_apply (U : opens X) (x : U) {F G : X.presheaf (Type v)} (f : F ⟶ G) (s : F.obj (op U)) : (stalk_functor (Type v) x.1).map f (germ F x s) = germ G x (f.app (op U) s) := congr_fun (stalk_functor_map_germ U x f) s open function lemma stalk_functor_map_injective_of_app_injective {F G : presheaf (Type v) X} (f : F ⟶ G) (h : ∀ U : opens X, injective (f.app (op U))) (x : X) : injective ((stalk_functor (Type v) x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← functor_to_types.naturality, ← functor_to_types.naturality] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) (h : ∀ x : X, injective ((stalk_functor (Type v) x).map f)) (U : opens X) : injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x.1 $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf (Type v) X} {G : presheaf (Type v) X} (f : F.presheaf ⟶ G) : (∀ x : X, injective ((stalk_functor (Type v) x).map f)) ↔ (∀ U : opens X, injective (f.app (op U))) := ⟨app_injective_of_stalk_functor_map_injective f, stalk_functor_map_injective_of_app_injective f⟩ lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf (Type v) X} (f : F ⟶ G) (h : ∀ x : X, bijective ((stalk_functor (Type v) x).map f)) (U : opens X) : surjective (f.app (op U)) := begin intro t, -- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. -- We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct -- a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` -- agree on `V`. suffices : ∀ x : U, ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.presheaf.obj (op V)), f.app (op V) s = G.presheaf.map iVU.op t, { -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using this, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [subtype.val_eq_coe, opens.mem_coe, opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, dsimp at ⊢ s_spec, rw [← functor_to_types.naturality, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (h z).1, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], dsimp, rw [functor_to_types.naturality, functor_to_types.naturality, heq, heq, ← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], refl } }, intro x, -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.presheaf.map iV₂V₁.op s₁], rw [functor_to_types.naturality, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf (Type v) X} (f : F ⟶ G) (h : ∀ x : X, bijective ((stalk_functor (Type v) x).map f)) (U : opens X) : bijective (f.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f (λ x, (h x).1) U, app_surjective_of_stalk_functor_map_bijective f h U⟩ /-- If all the stalk maps of map `f : F ⟶ G` of `Type`-valued sheaves are isomorphisms, then `f` is an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf (Type v) X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor (Type v) x).map f)] : is_iso f := begin -- Rather annoyingly, an isomorphism of presheaves isn't quite the same as an isomorphism of -- sheaves. We have to use that the induced functor from sheaves to presheaves is fully faithful haveI : is_iso ((induced_functor sheaf.presheaf).map f) := @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.presheaf G.presheaf f (by { intro U, op_induction U, rw is_iso_iff_bijective, exact app_bijective_of_stalk_functor_map_bijective f (λ x, (is_iso_iff_bijective _).mp (_inst_3 x)) U, }), exact is_iso_of_fully_faithful (induced_functor sheaf.presheaf) f, end /-- A morphism of `Type`-valued sheaves `f : F ⟶ G` is an isomorphism if and only if all the stalk maps are isomorphisms -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf (Type v) X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor (Type v) x).map f) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor (Type v) x) f ((induced_functor sheaf.presheaf).map_is_iso f) }, { intro h, resetI, exact is_iso_of_stalk_functor_map_iso f } end variables (C) def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', cases j, cases j_val, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, op_induction U, cases U, cases U_val, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end end stalk_pushforward end Top.presheaf
c16747774f00500f3238c10a7c5e5a80c2315dd4
bdb33f8b7ea65f7705fc342a178508e2722eb851
/tactic/rcases.lean
52202692c285b17c5f01404fc6aac76411358cf4
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
3,793
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.dlist tactic.basic open lean lean.parser namespace tactic inductive rcases_patt : Type | one : name → rcases_patt | many : list (list rcases_patt) → rcases_patt instance rcases_patt.inhabited : inhabited rcases_patt := ⟨rcases_patt.one `_⟩ def rcases_patt.name : rcases_patt → name | (rcases_patt.one n) := n | _ := `_ meta instance rcases_patt.has_reflect : has_reflect rcases_patt | (rcases_patt.one n) := `(_) | (rcases_patt.many l) := `(λ l, rcases_patt.many l).subst $ begin have := rcases_patt.has_reflect, tactic.reset_instance_cache, -- this combo will be `haveI` later exact list.reflect l end meta def rcases.process_constructor : nat → list rcases_patt → list name × list rcases_patt | 0 ids := ([], []) | 1 [] := ([`_], [default _]) | 1 [id] := ([id.name], [id]) | 1 ids := ([`_], [rcases_patt.many [ids]]) | (n+1) ids := let (ns, ps) := rcases.process_constructor n ids.tail, p := ids.head in (p.name :: ns, p :: ps) meta def rcases.process_constructors (params : nat) : list name → list (list rcases_patt) → tactic (dlist name × list (name × list rcases_patt)) | [] ids := pure (dlist.empty, []) | (c::cs) ids := do fn ← mk_const c, n ← get_arity fn, let (h, t) := by from match cs, ids.tail with | [], _::_ := ([rcases_patt.many ids], []) | _, _ := (ids.head, ids.tail) end, let (ns, ps) := rcases.process_constructor (n - params) h, (l, r) ← rcases.process_constructors cs t, pure (dlist.of_list ns ++ l, (c, ps) :: r) private def align {α β} (p : α → β → Prop) [∀ a b, decidable (p a b)] : list α → list β → list (α × β) | (a::as) (b::bs) := if p a b then (a, b) :: align as bs else align as (b::bs) | _ _ := [] private meta def get_local_and_type (e : expr) : tactic (expr × expr) := (do t ← infer_type e, pure (t, e)) <|> (do e ← get_local e.local_pp_name, t ← infer_type e, pure (t, e)) meta def rcases.continue (rcases_core : list (list rcases_patt) → expr → tactic (list expr)) (n : nat) : list (rcases_patt × expr) → tactic (list expr) | [] := intron n >> get_goals | ((rcases_patt.many ids, e) :: l) := do gs ← rcases_core ids e, list.join <$> gs.mmap (λ g, set_goals [g] >> rcases.continue l) | ((rcases_patt.one `rfl, e) :: l) := do (t, e) ← get_local_and_type e, subst e, rcases.continue l | (_ :: l) := rcases.continue l meta def rcases_core (n : nat) : list (list rcases_patt) → expr → tactic (list expr) | ids e := do (t, e) ← get_local_and_type e, t ← whnf t, env ← get_env, let I := t.get_app_fn.const_name, when (¬env.is_inductive I) $ fail format!"rcases tactic failed, {e} is not an inductive datatype", let params := env.inductive_num_params I, let c := env.constructors_of I, (ids, r) ← rcases.process_constructors params c ids, l ← cases_core e ids.to_list, gs ← get_goals, list.join <$> (align (λ (a : _ × _) (b : _ × _ × _), a.1 = b.2.1) r (gs.zip l)).mmap (λ⟨⟨_, ps⟩, g, _, hs, _⟩, set_goals [g] >> rcases.continue rcases_core n (ps.zip hs)) meta def rcases (p : pexpr) (ids : list (list rcases_patt)) : tactic unit := do e ← i_to_expr p, if e.is_local_constant then focus1 (rcases_core 0 ids e >>= set_goals) else do x ← mk_fresh_name, n ← revert_kdependencies e semireducible, (tactic.generalize e x) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (rcases_core 0 ids h >>= set_goals) end tactic
6737279739bbc5fd2346ce993202da8266c617f1
6f1049e897f569e5c47237de40321e62f0181948
/src/exercises/02_iff_if_and.lean
0c4c79824f83f2fc49882205be0b9bef3059d68b
[ "Apache-2.0" ]
permissive
anrddh/tutorials
f654a0807b9523608544836d9a81939f8e1dceb8
3ba43804e7b632201c494cdaa8da5406f1a255f9
refs/heads/master
1,655,542,921,827
1,588,846,595,000
1,588,846,595,000
262,330,134
0
0
null
1,588,944,346,000
1,588,944,345,000
null
UTF-8
Lean
false
false
13,534
lean
import data.real.basic /- In the previous file, we saw how to rewrite using equalities. The analogue operation with mathematical statements is rewriting using equivalences. This is also done using the rw tactic. Lean uses ↔ to denote equivalence instead of ⇔. In the following exercises we will use the lemma: sub_nonneg {x y : ℝ} : 0 ≤ y - x ↔ x ≤ y The curly braces around x and y instead of parentheses mean Lean will always try to figure out what are x and y from context, unless we really insist on telling it (we'll see how to insist much later). Let's not worry about that for now. In order to announce an intermediate statement we use: have my_name : my statement, This triggers the apparition of a new goal: proving the statement. After this is done, the statement becomes available under the name my_name. We can focus on the current goal by typing tactics between curly braces. -/ example {a b c : ℝ} (hab : a ≤ b) : c + a ≤ c + b := begin rw ← sub_nonneg, have key : (c + b) - (c + a) = b - a, -- Here we introduce an intermediate statement named key { ring, }, -- and prove it between curly braces rw key, -- we can now use the key statement rw sub_nonneg, exact hab, end /- Of course the previous lemma is already in the core library, named add_le_add_left, so we can use it below. Let's prove a variation (without invoking commutativity of addition since this would spoil our fun). -/ -- 0009 example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c := begin sorry end /- Let's see how we could use this a lemma. It is already in the core library, under the name add_le_add_right: add_le_add_right {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c This can be read as: "add_le_add_right is a function that will take as input real numbers a and b, an assumption hab claiming a ≤ b and a real number c, and will output a proof of a + c ≤ b + c". In addition, recall that curly braces around a b mean Lean will figure out those arguments unless we insist to help. This is because they can be deduced from the next argument hab. So it will be sufficient to feed hab and c to this function. -/ example {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : by exact add_le_add_right ha b, end /- In the second line of the above proof, we need to prove 0 + b ≤ a + b. The proof after the colon says: this is exactly lemma add_le_add_right applied to ha and b. Actually the calc block expect proof terms, and the `by` keyword is used to tell Lean we will use tactics to build such a proof term. But since the only tactic used in this block is `exact`, we can skip tactics entirely, and write: -/ example (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : add_le_add_right ha b, end /- Let's do a variant. -/ -- 0010 example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin sorry end /- The two preceding examples are in the core library : le_add_of_nonneg_left {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b le_add_of_nonneg_right {a b : ℝ} (hb : 0 ≤ b) : a ≤ a + b Again, there won't be any need to memorize those names, we will soon see how to get rid of such goals automatically. But we can already try to understand how their names are built: "le_add" describe the conclusion "less or equal than some addition" It comes first because we are focussed on proving stuff, and auto-completion works by looking at the beginning of words. "of" introduces assumptions. "nonneg" is Lean's abbreviation for non-negative. "left" or "right" disambiguates between the two variations. Let's use those lemmas by hand for now. -/ -- 0011 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin sorry end /- And let's combine with our earlier lemmas. -/ -- 0012 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin sorry end /- In the above examples, we prepared proofs of assumptions of our lemmas beforehand, so that we could feed them to the lemmas. This is called forward reasonning. The calc proofs also belong to this category. We can also announce the use of a lemma, and provide proofs after the fact, using the `apply` tactic. This is called backward reasonning because we get the conclusion first, and provide proofs later. Using rw on the goal (rather than on an assumption from the local context) is also backward reasonning. Let's do that using the lemma mul_nonneg' {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : 0 ≤ x*y -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, have key : b*c - a*c = (b - a)*c, { ring }, rw key, apply mul_nonneg', -- Here we don't provide proofs for the lemma's assumptions -- Now we need to provide the proofs. { rw sub_nonneg, exact hab }, { exact hc }, end /- Let's prove the same statement using only forward reasonning: announcing stuff, proving them by working with know facts, moving forward. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rw ← sub_nonneg at hab, exact hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rw h₂ at h₁, exact h₁, }, rw sub_nonneg at h₃, exact h₃, end /- One reason why the backward reasonning proof is shorter is because Lean can infer of lot of things by comparing the goal and the lemma statement. Indeed in the `apply mul_nonneg'` line, we didn't need to tell Lean that x = b - a and y = c in the lemma. It was infered by "unification" between the lemma statement and the goal. To be fair to the forward reasonning version, we should introduce a convenient variation on `rw`. The `rwa` tactic performs rewrite and then looks for an assumption matching the goal. We can use it to rewrite our latest proof as: -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rwa ← sub_nonneg at hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg' hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rwa h₂ at h₁, }, rwa sub_nonneg at h₃, end /- Let's now combine forward and backward reasonning, to get our most efficient proof of this statement. Note in particular how unification is used to know what to prove inside the parentheses in the mul_nonneg' arguments. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, calc 0 ≤ (b - a)*c : mul_nonneg' (by rwa sub_nonneg) hc ... = b*c - a*c : by ring, end /- Let's now practice all three styles using: mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b sub_nonpos {a b : α} : a - b ≤ 0 ↔ a ≤ b -/ /- First using mostly backward reasonning -/ -- 0013 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin sorry end /- Using forward reasonning -/ -- 0014 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin sorry end /-- Using a combination of both, with a calc block -/ -- 0015 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin sorry end /- Let's now move to proving implications. Lean denotes implications using a simple arrow →, the same it uses for functions (say denoting the type of functions from ℕ to ℕ by ℕ → ℕ). This is because it sees a proof of P ⇒ Q as a function turning a proof of P into a proof Q. Many examples that we met are secretely implications. For instance we proved le_add_of_nonneg_left (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b But this can be rephrased as le_add_of_nonneg_left (a b : ℝ) : 0 ≤ a → b ≤ a + b In order to prove P → Q, we use the tactic intros, followed by an assumption name. The creates an assumption with that name asserting that P holds, and turns the goal into Q. Let's check we can go from our old version of le_add_of_nonneg_left to the new one. -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := begin intros ha, exact le_add_of_nonneg_left ha, end /- Actually Lean doesn't make any difference between those two versions. It is also happy with -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := le_add_of_nonneg_left /- No tactic state is shown in the above line because we don't even need to enter tactic mode using begin or by. Let's practise using intros. -/ -- 0016 example (a b : ℝ): 0 ≤ b → a ≤ a + b := begin sorry end /- What about lemmas having more than one assumptions? For instance add_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b A natural idea is to use the conjunction operator (logical AND), which Lean denotes by ∧. Assumptions built using this operator can be decomposed using the cases tactic, which is a very general assumption decomposing tactic. -/ example {a b : ℝ} : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b := begin intros hyp, cases hyp with ha hb, exact add_nonneg ha hb, end /- Needing that intermediate line invoking cases shows this formaluation is not what is used by Lean. It rather sees add_nonneg as two nested implication: if a is non-negative then if b is non-negative then a+b is non-negative. It reads funny, but it is much more convenient to use in practice. -/ example {a b : ℝ} : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := add_nonneg /- The above pattern is so common that implication are defined as right-associative operators, hence parentheses are not needed above. Let's prove the naive conjunction version implies the funny Lean version. For this we need to know how to prove a conjunction. The split tactic tactic creates two goals from a conjunction goal. It can also be used to create two implication goals from an equivalence goal. -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha, intros hb, apply H, split, exact ha, exact hb, end /- Let's practice cases and split. In the next exercise, P, Q and R denote unspecified mathematical statements. -/ -- 0017 example (P Q R : Prop) : P ∧ Q → Q ∧ P := begin sorry end /- Of course using split only to be able to use exact twice in a row feels silly. One can also use the anonymous constructor syntax: ⟨ ⟩ Beware those are not parentheses but angle brackets. This is a generic way of providing compound objects to Lean when Lean already has a very clear idea of what it is waiting for. So we could have replaced the last three lines by: exact ⟨hQ, hP⟩ We can also combine the intros steps. We can now compress our earlier proof to: -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha hb, exact H ⟨ha, hb⟩, end /- The anonymous contructor trick actually also work in intros provided we use its recursive version rintros. So we can replace intro h, cases h with h₁ h₂ by rintros ⟨h₁, h₂⟩, Now redo the previous exercise using all those compressing techniques, in exactly two lines. -/ -- 0018 example (P Q R : Prop): P ∧ Q → Q ∧ P := begin sorry end /- We are ready to come back to the equivalence between the different formulations of lemmas having two assumptions. Remember the split tactic can be used to split an equivalence into two implications. -/ -- 0019 example (P Q R : Prop) : (P ∧ Q → R) ↔ (P → (Q → R)) := begin sorry end /- If you used more that five lines in the above exercise then try to compress things (without simply removing line ends). One last compression technique: given a proof h of a conjunction P ∧ Q, one can get a proof of P using h.left and a proof of Q using h.right, without using cases. One can also use the more generic (but less legible) names h.1 and h.2. Similarly, given a proof h of P ↔ Q, one can get a proof of P → Q using h.mp and a proof of Q → P using h.mpr (or the generic h.1 and h.2 that are even less legible in this case). Before the final exercise in this file, let's make sure we'll be able to leave without learning 10 lemma names. The linarith tactic will prove any equality or inequality or contradiction that follows by linear combinations of assumptions from the context (with constant coefficients). -/ example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin linarith, end /- Now let's enjoy this for a while. -/ -- 0020 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin sorry end /- And let's combine with our earlier lemmas. -/ -- 0021 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin sorry end /- Final exercise In the last exercise of this file, we will use the divisibility relation on ℕ, denoted by ∣ (beware this is a unicode divisibility bar, not the ASCII pipe character), and the gcd function. The definitions are the usual one, but our goal is to avoid using these definitions and only use the following three lemmas: dvd_refl (a : ℕ) : a ∣ a dvd_antisym {a b : ℕ} : a ∣ b → b ∣ a → a = b := dvd_gcd_iff {a b c : ℕ} : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b -/ -- All functions and lemma below are about natural numbers. open nat -- 0022 example (a b : ℕ) : a ∣ b ↔ gcd a b = a := begin sorry end
7664cced180866d02fb5b48d67053ad1a469c834
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/real/ennreal.lean
e22f28bdd19616a244dacb3b564ba60f7ba3defc
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
55,686
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov -/ import data.real.nnreal import data.set.intervals /-! # Extended non-negative reals We define `ennreal := with_no ℝ≥0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `measure_theory.measure`, and of the extended distance `edist` in a `emetric_space`. In this file we define some algebraic operations and a linear order on `ennreal` and prove basic properties of these operations, order, and conversions to/from `ℝ`, `ℝ≥0`, and `ℕ`. ## Main definitions * `ennreal`: the extended nonnegative real numbers `[0, ∞]`; defined as `with_top ℝ≥0`; it is equipped with the following structures: - coercion from `ℝ≥0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≤ ↑q ↔ p ≤ q` and `∀ a, a ≤ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝ≥0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝ≥0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a ≠ 0`; - `a - b` is defined as the minimal `d` such that `a ≤ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; - `a⁻¹` is defined as `Inf {b | 1 ≤ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝ≥0`, `p ≠ 0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ennreal` into a canonically ordered commutative semiring of characteristic zero. * Coercions to/from other types: - coercion `ℝ≥0 → ennreal` is defined as `has_coe`, so one can use `(p : ℝ≥0)` in a context that expects `a : ennreal`, and Lean will apply `coe` automatically; - `ennreal.to_nnreal` sends `↑p` to `p` and `∞` to `0`; - `ennreal.to_real := coe ∘ ennreal.to_nnreal` sends `↑p`, `p : ℝ≥0` to `(↑p : ℝ)` and `∞` to `0`; - `ennreal.of_real := coe ∘ nnreal.of_real` sends `x : ℝ` to `↑⟨max x 0, _⟩` - `ennreal.ne_top_equiv_nnreal` is an equivalence between `{a : ennreal // a ≠ 0}` and `ℝ≥0`. ## Implementation notes We define a `can_lift ennreal ℝ≥0` instance, so one of the ways to prove theorems about an `ennreal` number `a` is to consider the cases `a = ∞` and `a ≠ ∞`, and use the tactic `lift a to ℝ≥0 using ha` in the second case. This instance is even more useful if one already has `ha : a ≠ ∞` in the context, or if we have `(f : α → ennreal) (hf : ∀ x, f x ≠ ∞)`. ## Notations * `ℝ≥0`: type of nonnegative real numbers `[0, ∞)`; defined in `data.real.nnreal`; * `∞`: a localized notation in `ennreal` for `⊤ : ennreal`. -/ noncomputable theory open classical set open_locale classical big_operators nnreal variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered, derive nontrivial] def ennreal := with_top ℝ≥0 localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : ℝ≥0} instance : inhabited ennreal := ⟨0⟩ instance : has_coe ℝ≥0 ennreal := ⟨ option.some ⟩ instance : can_lift ennreal ℝ≥0 := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = ∞ := rfl @[simp] lemma some_eq_coe (a : ℝ≥0) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → ℝ≥0 | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : ℝ} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma to_real_of_real' {r : ℝ} : ennreal.to_real (ennreal.of_real r) = max r 0 := rfl lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : ℝ≥0) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : ℝ} (h : 0 ≤ x) : ennreal.of_real x = @coe ℝ≥0 ennreal _ (⟨x, h⟩ : ℝ≥0) := by { rw [coe_nnreal_eq], refl } @[simp] lemma of_real_coe_nnreal : ennreal.of_real p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] lemma coe_zero : ↑(0 : ℝ≥0) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : ℝ≥0) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : ℝ≥0) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:ℝ≥0, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma forall_ne_top {p : ennreal → Prop} : (∀ a ≠ ∞, p a) ↔ ∀ r : ℝ≥0, p r := option.ball_ne_none lemma exists_ne_top {p : ennreal → Prop} : (∃ a ≠ ∞, p a) ↔ ∃ r : ℝ≥0, p r := option.bex_ne_none lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ∞ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:ℝ≥0) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ∞ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma of_real_lt_top {r : ℝ} : ennreal.of_real r < ∞ := lt_top_iff_ne_top.2 of_real_ne_top @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : ℝ≥0 → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:ℝ≥0) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1 : ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast (@one_lt_two ℕ _ _) @[simp] lemma zero_lt_two : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := (ne_of_lt zero_lt_two).symm lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top /-- The set of `ennreal` numbers that are not equal to `∞` is equivalent to `ℝ≥0`. -/ def ne_top_equiv_nnreal : {a | a ≠ ∞} ≃ ℝ≥0 := { to_fun := λ x, ennreal.to_nnreal x, inv_fun := λ x, ⟨x, coe_ne_top⟩, left_inv := λ ⟨x, hx⟩, subtype.eq $ coe_to_nnreal hx, right_inv := λ x, to_nnreal_coe } lemma cinfi_ne_top [has_Inf α] (f : ennreal → α) : (⨅ x : {x // x ≠ ∞}, f x) = ⨅ x : ℝ≥0, f x := eq.symm $ infi_congr _ ne_top_equiv_nnreal.symm.surjective $ λ x, rfl lemma infi_ne_top [complete_lattice α] (f : ennreal → α) : (⨅ x ≠ ∞, f x) = ⨅ x : ℝ≥0, f x := by rw [infi_subtype', cinfi_ne_top] lemma csupr_ne_top [has_Sup α] (f : ennreal → α) : (⨆ x : {x // x ≠ ∞}, f x) = ⨆ x : ℝ≥0, f x := @cinfi_ne_top (order_dual α) _ _ lemma supr_ne_top [complete_lattice α] (f : ennreal → α) : (⨆ x ≠ ∞, f x) = ⨆ x : ℝ≥0, f x := @infi_ne_top (order_dual α) _ _ lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅ n, f n) = (⨅ n : ℝ≥0, f n) ⊓ f ∞ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) lemma supr_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨆ n, f n) = (⨆ n : ℝ≥0, f n) ⊔ f ∞ := @infi_ennreal (order_dual α) _ _ @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : ℝ≥0 →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ennreal) = s.indicator (λ x, f x) a := (of_nnreal_hom : ℝ≥0 →+ ennreal).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n @[simp] lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top @[simp] lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ∞) (h₂ : r₂ < ∞) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ∞, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma not_lt_top {x : ennreal} : ¬ x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, not_not] lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top : a * b = ∞ ↔ (a ≠ 0 ∧ b = ∞) ∨ (a = ∞ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_lt_top : a < ∞ → b < ∞ → a * b < ∞ := with_top.mul_lt_top lemma mul_ne_top : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using mul_lt_top lemma ne_top_of_mul_ne_top_left (h : a * b ≠ ∞) (hb : b ≠ 0) : a ≠ ∞ := by { simp [mul_eq_top, hb, not_or_distrib] at h ⊢, exact h.2 } lemma ne_top_of_mul_ne_top_right (h : a * b ≠ ∞) (ha : a ≠ 0) : b ≠ ∞ := ne_top_of_mul_ne_top_left (by rwa [mul_comm]) ha lemma lt_top_of_mul_lt_top_left (h : a * b < ∞) (hb : b ≠ 0) : a < ∞ := by { rw [ennreal.lt_top_iff_ne_top] at h ⊢, exact ne_top_of_mul_ne_top_left h hb } lemma lt_top_of_mul_lt_top_right (h : a * b < ∞) (ha : a ≠ 0) : b < ∞ := lt_top_of_mul_lt_top_left (by rwa [mul_comm]) ha lemma mul_lt_top_iff {a b : ennreal} : a * b < ∞ ↔ (a < ∞ ∧ b < ∞) ∨ a = 0 ∨ b = 0 := begin split, { intro h, rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right], intros hb ha, exact ⟨lt_top_of_mul_lt_top_left h hb, lt_top_of_mul_lt_top_right h ha⟩ }, { rintro (⟨ha, hb⟩|rfl|rfl); [exact mul_lt_top ha hb, simp, simp] } end @[simp] lemma mul_pos : 0 < a * b ↔ 0 < a ∧ 0 < b := by simp only [pos_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib] lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ ∞ ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : ℝ≥0) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ∞ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : ∞ ≠ n := with_top.top_ne_nat n @[simp] lemma one_lt_top : 1 < ∞ := coe_lt_top lemma le_coe_iff : a ≤ ↑r ↔ (∃p:ℝ≥0, a = p ∧ p ≤ r) := with_top.le_coe_iff lemma coe_le_iff : ↑r ≤ a ↔ (∀p:ℝ≥0, a = p → r ≤ p) := with_top.coe_le_iff lemma lt_iff_exists_coe : a < b ↔ (∃p:ℝ≥0, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe @[simp, norm_cast] lemma coe_finset_sup {s : finset α} {f : α → ℝ≥0} : ↑(s.sup f) = s.sup (λ x, (f x : ennreal)) := finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [nonpos_iff_eq_zero.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [pos_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ∞ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ∞ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ∞) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:ℝ≥0, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have ∞ ≤ ↑a + ↑(1:ℝ≥0), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases exists_between h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:ℝ≥0, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : ℝ≥0, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : ℝ≥0 := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ∞) : ∃n:ℕ, r < n := begin lift r to ℝ≥0 using h, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin lift a to ℝ≥0 using ne_top_of_lt ac, lift b to ℝ≥0 using ne_top_of_lt bd, cases c, { simp }, cases d, { simp }, simp only [← coe_add, some_eq_coe, coe_lt_coe] at *, exact add_lt_add ac bd end @[norm_cast] lemma coe_min : ((min r p:ℝ≥0):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:ℝ≥0):ennreal) = max r p := coe_mono.map_max lemma le_of_top_imp_top_of_to_nnreal_le {a b : ennreal} (h : a = ⊤ → b = ⊤) (h_nnreal : a ≠ ⊤ → b ≠ ⊤ → a.to_nnreal ≤ b.to_nnreal) : a ≤ b := begin by_cases ha : a = ⊤, { rw h ha, exact le_top, }, by_cases hb : b = ⊤, { rw hb, exact le_top, }, rw [←coe_to_nnreal hb, ←coe_to_nnreal ha, coe_le_coe], exact h_nnreal ha hb, end end order section complete_lattice lemma coe_Sup {s : set ℝ≥0} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set ℝ≥0} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set ℝ≥0} : ↑r ∈ upper_bounds ((coe : ℝ≥0 → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := begin rcases lt_iff_exists_nnreal_btwn.1 ac with ⟨a', aa', a'c⟩, lift a to ℝ≥0 using ne_top_of_lt aa', rcases lt_iff_exists_nnreal_btwn.1 bd with ⟨b', bb', b'd⟩, lift b to ℝ≥0 using ne_top_of_lt bb', norm_cast at *, calc ↑(a * b) < ↑(a' * b') : coe_lt_coe.2 (mul_lt_mul' aa'.le bb' (zero_le _) ((zero_le a).trans_lt aa')) ... = ↑a' * ↑b' : coe_mul ... ≤ c * d : mul_le_mul a'c.le b'd.le end lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ∞ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ∞ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (pos_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ∞ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le $ 0 + a) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right h _) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ∞ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, pos_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact pos_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_right (le_refl a) @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left le_sub_add_self _ ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ∞) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top {s : finset α} {f : α → ennreal} (h : ∀a∈s, f a < ∞) : (∏ a in s, f a) < ∞ := with_top.prod_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ∞) → ∑ a in s, f a < ∞ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ∞ ↔ (∀a∈s, f a < ∞) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ∞ ↔ (∃a∈s, f a = ∞) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `ℝ≥0` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, exact (coe_to_nnreal (hf x hx).ne).symm }, { exact (sum_lt_top hf).ne } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ∞) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ∞ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ∞ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : ∞⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:ℝ≥0):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt _root_.zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← pos_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_lt_top {x : ennreal} : x⁻¹ < ∞ ↔ 0 < x := by { simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] } lemma div_lt_top {x y : ennreal} (h1 : x < ∞) (h2 : 0 < y) : x / y < ∞ := mul_lt_top h1 (inv_lt_top.mpr h2) @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := pos_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [pos_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma top_div_coe : ∞ / p = ∞ := by simp [div_def, top_mul] lemma top_div_of_ne_top (h : a ≠ ∞) : ∞ / a = ∞ := by { lift a to ℝ≥0 using h, exact top_div_coe } lemma top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [top_div_of_ne_top, *] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ∞ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ∞ ∧ b ≠ ∞) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ∞ = ∞, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ∞, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ∞) (hbt : b ≠ ∞ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ∞, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ∞ ∨ c ≠ ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ∞ → a ≠ 0) → (a = ∞ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a * a⁻¹ = 1 := begin lift a to ℝ≥0 using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ∞) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_nnreal_lt {x y : ennreal} (h : ∀ r : ℝ≥0, ↑r < x → ↑r ≤ y) : x ≤ y := begin refine le_of_forall_ge_of_dense (λ r hr, _), lift r to ℝ≥0 using ne_top_of_lt hr, exact h r hr end lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ∞ := by simp [pos_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ∞) : a / 2 < a := begin lift a to ℝ≥0 using ht, have h : (2 : ennreal) = ((2 : ℝ≥0) : ennreal), from rfl, have h' : (2 : ℝ≥0) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to ℝ≥0 using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_pos_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n > 0, b < (n : ℕ) * a := begin have : b / a ≠ ∞, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), have : 0 < (n : ennreal), from (zero_le _).trans_lt hn, refine ⟨coe_nat_lt_coe_nat.1 this, _⟩, rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ∞) : ∃ n : ℕ, b < n * a := (exists_nat_pos_mul_gt ha hb).imp $ λ n, Exists.snd lemma exists_nat_pos_inv_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ((n : ℕ) : ennreal)⁻¹ * a < b := begin rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩, have : (n : ennreal) ≠ 0 := nat.cast_ne_zero.2 npos.lt.ne', use [n, npos], rwa [← one_mul b, ← inv_mul_cancel this coe_nat_ne_top, mul_assoc, mul_lt_mul_left (inv_ne_zero.2 coe_nat_ne_top) (inv_ne_top.2 this)] end lemma exists_nnreal_pos_mul_lt (ha : a ≠ ∞) (hb : b ≠ 0) : ∃ n > 0, ↑(n : ℝ≥0) * a < b := begin rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩, use (n : ℝ≥0)⁻¹, simp [*, npos.ne', zero_lt_one] end end inv section real lemma to_real_add (ha : a ≠ ∞) (hb : b ≠ ∞) : (a+b).to_real = a.to_real + b.to_real := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ∞ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] lemma of_real_add_le {p q : ℝ} : ennreal.of_real (p + q) ≤ ennreal.of_real p + ennreal.of_real q := coe_le_coe.2 nnreal.of_real_add_le @[simp] lemma to_real_le_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ∞) (hb : b ≠ ∞) : a.to_real < b.to_real ↔ a < b := begin lift a to ℝ≥0 using ha, lift b to ℝ≥0 using hb, norm_cast end lemma to_real_max (hr : a ≠ ∞) (hp : b ≠ ∞) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] lemma of_real_le_of_le_to_real {a : ℝ} {b : ennreal} (h : a ≤ ennreal.to_real b) : ennreal.of_real a ≤ b := (of_real_le_of_real h).trans of_real_to_real_le @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ∞) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ∞) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to ℝ≥0 using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ∞) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ∞, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ∞) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to ℝ≥0 using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma of_real_inv_of_pos {x : ℝ} (hx : 0 < x) : (ennreal.of_real x)⁻¹ = ennreal.of_real x⁻¹ := by rw [ennreal.of_real, ennreal.of_real, ←@coe_inv (nnreal.of_real x) (by simp [hx]), coe_eq_coe, nnreal.of_real_inv.symm] lemma of_real_div_of_pos {x y : ℝ} (hy : 0 < y) : ennreal.of_real (x / y) = ennreal.of_real x / ennreal.of_real y := by rw [div_def, of_real_inv_of_pos hy, mul_comm, ←of_real_mul (inv_nonneg.mpr (le_of_lt hy)), div_eq_mul_inv, mul_comm] lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_nnreal_mul_top (a : ennreal) : ennreal.to_nnreal (a * ∞) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_nnreal] }, { rw [mul_top, if_neg h, top_to_nnreal] } end @[simp] lemma to_nnreal_top_mul (a : ennreal) : ennreal.to_nnreal (∞ * a) = 0 := by rw [mul_comm, to_nnreal_mul_top] @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ∞) = 0 := by rw [ennreal.to_real, to_nnreal_mul_top, nnreal.coe_zero] @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (∞ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real (ha : a < ∞) (hb : b < ∞) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin lift a to ℝ≥0 using ha.ne, lift b to ℝ≥0 using hb.ne, simp only [coe_eq_coe, nnreal.coe_eq, coe_to_real], end /-- `ennreal.to_nnreal` as a `monoid_hom`. -/ def to_nnreal_hom : ennreal →* ℝ≥0 := { to_fun := ennreal.to_nnreal, map_one' := to_nnreal_coe, map_mul' := by rintro (_|x) (_|y); simp only [← coe_mul, none_eq_top, some_eq_coe, to_nnreal_top_mul, to_nnreal_mul_top, top_to_nnreal, mul_zero, zero_mul, to_nnreal_coe] } lemma to_nnreal_mul {a b : ennreal}: (a * b).to_nnreal = a.to_nnreal * b.to_nnreal := to_nnreal_hom.map_mul a b lemma to_nnreal_pow (a : ennreal) (n : ℕ) : (a ^ n).to_nnreal = a.to_nnreal ^ n := to_nnreal_hom.map_pow a n lemma to_nnreal_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_nnreal = ∏ i in s, (f i).to_nnreal := to_nnreal_hom.map_prod _ _ /-- `ennreal.to_real` as a `monoid_hom`. -/ def to_real_hom : ennreal →* ℝ := (nnreal.to_real_hom : ℝ≥0 →* ℝ).comp to_nnreal_hom lemma to_real_mul : (a * b).to_real = a.to_real * b.to_real := to_real_hom.map_mul a b lemma to_real_pow (a : ennreal) (n : ℕ) : (a ^ n).to_real = a.to_real ^ n := to_real_hom.map_pow a n lemma to_real_prod {ι : Type*} {s : finset ι} {f : ι → ennreal} : (∏ i in s, f i).to_real = ∏ i in s, (f i).to_real := to_real_hom.map_prod _ _ end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] lemma infi_mul {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : infi f * x = ⨅i, f i * x := begin by_cases h2 : x = 0, simp only [h2, mul_zero, infi_const], refine le_antisymm (le_infi $ λ i, mul_right_mono $ infi_le _ _) ((div_le_iff_le_mul (or.inl h2) $ or.inl h).mp $ le_infi $ λ i, (div_le_iff_le_mul (or.inl h2) $ or.inl h).mpr $ infi_le _ _) end lemma mul_infi {ι} [nonempty ι] {f : ι → ennreal} {x : ennreal} (h : x ≠ ∞) : x * infi f = ⨅i, x * f i := by { rw [mul_comm, infi_mul h], simp only [mul_comm], assumption } /-! `supr_mul`, `mul_supr` and variants are in `topology.instances.ennreal`. -/ end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ∞ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr /-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`, but it holds in `ennreal` with the additional assumption that `a < ∞`. -/ lemma le_of_add_le_add_left {a b c : ennreal} : a < ∞ → a + b ≤ a + c → b ≤ c := by cases a; cases b; cases c; simp [← ennreal.coe_add, ennreal.coe_le_coe] end ennreal
a9f01b90d5034de34491c269a3a94503d234fc2d
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/continued_fractions/default.lean
6355a0bead4ef2860fbd11329b029568de98a525
[ "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
354
lean
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.basic import algebra.continued_fractions.translations import algebra.continued_fractions.continuants_recurrence /-! # Default Exports for Continued Fractions -/
3982365ccd022ee49a32034d8756a7c0bc83d6ae
367134ba5a65885e863bdc4507601606690974c1
/src/data/list/sections.lean
74326e1a4bb2afe4a82be78c962f56c469fda84f
[ "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
1,283
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.forall2 universes u v open nat function variables {α : Type u} {β : Type v} namespace list /- sections -/ theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forall₂_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) end list
0de1c6f0b1fc2c817930cf54eae73c10788e5370
c3de33d4701e6113627153fe1103b255e752ed7d
/tools/auto/finish.lean
e6a2a42a1ef148f7f1a14d2ea64c21d6e64cc8ca
[]
no_license
jroesch/library_dev
77d2b246ff47ab05d55cb9706a37d3de97038388
4faa0a45c6aa7eee6e661113c2072b8840bff79b
refs/heads/master
1,611,281,606,352
1,495,661,644,000
1,495,661,644,000
92,340,430
0
0
null
1,495,663,344,000
1,495,663,344,000
null
UTF-8
Lean
false
false
13,683
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. (For more substantial automation, I will experiment with a procedure that does similar things but says within a single smt state, uses e-matching to chain forward with new facts, and splits only as a last resort.) 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 can take a 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 ..tactic.simp_tactic ...logic.basic open tactic expr -- TODO(Jeremy): move these theorem implies_and_iff (p q r : Prop) : (p → q ∧ r) ↔ (p → q) ∧ (p → r) := iff.intro (λ h, ⟨λ hp, (h hp).left, λ hp, (h hp).right⟩) (λ h hp, ⟨h.left hp, h.right hp⟩) theorem curry_iff (p q r : Prop) : (p ∧ q → r) ↔ (p → q → r) := iff.intro (λ h hp hq, h ⟨hp, hq⟩) (λ h ⟨hp, hq⟩, h hp hq) theorem iff_def (p q : Prop) : (p ↔ q) ↔ (p → q) ∧ (q → p) := ⟨ λh, ⟨h.1, h.2⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩ ⟩ theorem {u} bexists_def {α : Type u} (p q : α → Prop) : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ -- theorem {u} forall_def {α : Type u} (p q : α → Prop) : (∀ x (h : p x), q x) ↔ ∀ x, p x → q x := -- iff.refl _ namespace auto /- Utilities -/ meta def whnf_reducible (e : expr) : tactic expr := whnf e reducible -- stolen from interactive.lean private 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 /- 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. TODO (Jeremy): using the simplifier this way is inefficient. In particular, negations should be eliminated from the top down. Use ext_simplify_core instead. -/ def logic_eval_simps : list name := [ ``not_true, ``not_false, ``or_true, ``or_false, ``true_or, ``false_or, ``true_and, ``and_true, ``false_and, ``and_false, ``true_implies_iff, ``false_implies_iff, ``implies_true_iff, ``implies_false_iff] -- note: with current normalization procedure, or distribs cause exponential blowup def common_normalize_lemma_names : list name := logic_eval_simps ++ [``and_assoc, ``or_assoc, -- unfold bounded quantifiers ``bexists_def, -- negations ``not_or_iff, ``not_exists_iff_forall_not, -- bring out conjunctions ``or_implies_distrib, -- ((a ∨ b) → c) ↔ ((a → c) ∧ (b → c)) ``implies_and_iff, -- (a → b ∧ c) ↔ (a → b) ∧ (a → c)) -- ``or_distrib, -- ``or_distrib_right, ``forall_and_distrib, -- bring out universal quantifiers ``exists_implies_distrib, -- good for intuitionistic logic ``curry_iff] def classical_normalize_lemma_names : list name := common_normalize_lemma_names ++ [ -- negations ``classical.not_not_iff, ``classical.not_and_iff, ``classical.not_forall_iff_exists_not, -- implication ``classical.implies_iff_not_or] meta def normalize_hyp (simps : simp_lemmas) (h : expr) : tactic expr := do htype ← infer_type h, mcond (is_prop htype) ((do (new_htype, heq) ← simplify simps htype, newh ← assert' (expr.local_pp_name h) new_htype, mk_eq_mp heq h >>= exact, try $ clear h, return newh) <|> return h) (return 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 simps) /- Eliminate existential quantifiers. -/ -- eliminate an existential quantifier if there is one meta def eelim : tactic unit := do ctx ← local_context, first $ ctx.for $ λ h, do t ← infer_type h >>= whnf_reducible, guard (is_app_of t ``Exists), to_expr ``(exists.elim %%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.for $ λ 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 := do ctx ← local_context, mcond (split_hyps_aux ctx) skip failed /- Use each hypothesis to simplify the others. For example, given a and a → b, we get b, and given a ∨ b ∨ c and ¬ b we get a ∨ c. TODO(Jeremy): use a version of simp_at_using_hs that takes simp lemmas -/ meta def self_simplify_hyps_aux : tactic unit := do ctx ← local_context, extra_simps ← mmap mk_const logic_eval_simps, first $ ctx.for $ λ h, do t ← infer_type h, mcond (is_prop t) (simp_at_using_hs h extra_simps) failed meta def self_simplify_hyps : tactic unit := self_simplify_hyps_aux >> repeat self_simplify_hyps_aux /- 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 simplifier again. - 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 extra theorems for ematching? -/ meta def mk_hinst_lemmas : list expr → smt_tactic hinst_lemmas | [] := return hinst_lemmas.mk | (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 (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := do /- if cfg^.use_simp then simp_all s else skip, -/ contradiction <|> (solve1 $ (do revert_all, using_smt (do smt_tactic.intros, ctx ← local_context, hs ← mk_hinst_lemmas ctx, smt_tactic.repeat (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) (cfg : auto_config) : case_option → tactic unit := λ co, do if cfg^.use_simp then simp_all s else skip, preprocess_hyps cfg, done s cfg <|> (mcond (case_some_hyp co safe_core) skip (match co with | case_option.force := done s cfg | case_option.at_most_one := try (done s cfg) | case_option.accept := try (done s cfg) end)) meta def clarify (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.at_most_one meta def safe (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.accept meta def finish (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := safe_core s cfg case_option.force meta def iclarify (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := clarify s {cfg with classical := false} meta def isafe (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := safe s {cfg with classical := false} meta def ifinish (s : simp_lemmas) (cfg : auto_config := {}) : tactic unit := finish s {cfg with classical := false} end auto 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 opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.clarify s cfg meta def safe (hs : parse opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.safe s cfg meta def finish (hs : parse opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.finish s cfg meta def iclarify (hs : parse opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.iclarify s cfg meta def isafe (hs : parse opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.isafe s cfg meta def ifinish (hs : parse opt_qexpr_list) (cfg : auto_config := {}) : tactic unit := do s ← mk_simp_set [] hs [], auto.ifinish s cfg end interactive end tactic
0ed9578a5a59c1f3fe790b528f1e085dd8646c0c
e1da55f4222dac91b940ca052928eaace09762da
/src/increment.lean
54d5ff577e85c6ea9997e431e0dffa96f65d6ad4
[]
no_license
b-mehta/regularity-lemma
c5826e22c280d0b073a4e62dba731f4dd3d1b69f
cf26082b0c88fa54276e6fdc3338c15e607c52c6
refs/heads/master
1,658,209,524,267
1,644,406,456,000
1,644,406,456,000
457,327,371
1
0
null
null
null
null
UTF-8
Lean
false
false
8,483
lean
/- Copyright (c) 2021 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 .chunk import .energy /-! # Increment -/ universes u v open finset fintype simple_graph open_locale big_operators classical variables {α : Type*} [fintype α] {P : finpartition (univ : finset α)} (hP : P.is_equipartition) (G : simple_graph α) (ε : ℝ) local notation `m` := (card α/exp_bound P.parts.card : ℕ) namespace finpartition /-- The work-horse of SRL. This says that if we have an equipartition which is *not* uniform, then we can make a (much bigger) equipartition with a slightly higher energy. This is helpful since the energy is bounded by a constant (see `energy_le_one`), so this process eventually terminates and yields a not-too-big uniform equipartition. -/ noncomputable def is_equipartition.increment : finpartition (univ : finset α) := P.bind (λ U, hP.chunk_increment G ε) open finpartition finpartition.is_equipartition variables {hP G ε} lemma card_increment (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPG : ¬P.is_uniform G ε) : (hP.increment G ε).parts.card = exp_bound P.parts.card := begin have hPα' : exp_bound P.parts.card ≤ card α := (nat.mul_le_mul_of_nonneg_left $ nat.pow_le_pow_of_le_left (by norm_num) _).trans hPα, have hPpos : 0 < exp_bound P.parts.card := exp_bound_pos.2 (nonempty_of_not_uniform hPG).card_pos, rw [is_equipartition, finset.equitable_on_iff] at hP, rw [increment, card_bind], simp_rw [finpartition.is_equipartition.chunk_increment, apply_dite finpartition.parts, apply_dite card], rw [sum_dite, sum_const_nat, sum_const_nat, card_attach, card_attach], rotate, exact λ x hx, finpartition.equitabilise.parts_card (nat.div_pos hPα' hPpos) _, exact λ x hx, finpartition.equitabilise.parts_card (nat.div_pos hPα' hPpos) _, rw [nat.sub_add_cancel a_add_one_le_four_pow_parts_card, nat.sub_add_cancel ((nat.le_succ _).trans a_add_one_le_four_pow_parts_card), ←add_mul], congr, rw [filter_card_add_filter_neg_card_eq_card, card_attach], end lemma increment_is_equipartition (hP : P.is_equipartition) (G : simple_graph α) (ε : ℝ) : (hP.increment G ε).is_equipartition := begin rw [is_equipartition, set.equitable_on_iff_exists_eq_eq_add_one], refine ⟨m, λ A hA, _⟩, rw [mem_coe, increment, mem_bind] at hA, obtain ⟨U, hU, hA⟩ := hA, exact card_eq_of_mem_parts_chunk_increment hA, end lemma distinct_pairs_increment : P.parts.off_diag.attach.bUnion (λ UV, (hP.chunk_increment G ε ((mem_off_diag _ _).1 UV.2).1).parts.product (hP.chunk_increment G ε ((mem_off_diag _ _).1 UV.2).2.1).parts) ⊆ (hP.increment G ε).parts.off_diag := begin rintro ⟨Ui, Vj⟩, simp only [finpartition.is_equipartition.increment, mem_off_diag, bind_parts, mem_bUnion, prod.exists, exists_and_distrib_left, exists_prop, mem_product, mem_attach, true_and, subtype.exists, and_imp, mem_off_diag, forall_exists_index, bex_imp_distrib, ne.def], rintro U V hUV hUi hVj, refine ⟨⟨_, hUV.1, hUi⟩, ⟨_, hUV.2.1, hVj⟩, _⟩, rintro rfl, obtain ⟨i, hi⟩ := nonempty_of_mem_parts _ hUi, apply hUV.2.2 (P.disjoint.elim_finset hUV.1 hUV.2.1 i (finpartition.le _ hUi hi) (finpartition.le _ hVj hi)), end /-- The contribution to `energy` of a pair of distinct parts of a finpartition. -/ noncomputable def pair_contrib (G : simple_graph α) (ε : ℝ) (hP : P.is_equipartition) (x : {x // x ∈ P.parts.off_diag}) := (∑ i in (hP.chunk_increment G ε ((mem_off_diag _ _).1 x.2).1).parts.product (hP.chunk_increment G ε ((mem_off_diag _ _).1 x.2).2.1).parts, G.edge_density i.fst i.snd ^ 2) lemma off_diag_pairs_le_increment_energy : ∑ x in P.parts.off_diag.attach, pair_contrib G ε hP x / (hP.increment G ε).parts.card ^ 2 ≤ (hP.increment G ε).energy G := begin simp_rw [pair_contrib, ←sum_div], refine div_le_div_of_le_of_nonneg _ (sq_nonneg _), rw ←sum_bUnion, { exact sum_le_sum_of_subset_of_nonneg distinct_pairs_increment (λ i _ _, sq_nonneg _) }, rintro ⟨⟨s₁, s₂⟩, hs⟩ _ ⟨⟨t₁, t₂⟩, ht⟩ _ hst ⟨u, v⟩ huv, simp only [inf_eq_inter, mem_inter, mem_product] at huv, rw mem_off_diag at hs ht, obtain ⟨a, ha⟩ := finpartition.nonempty_of_mem_parts _ huv.1.1, obtain ⟨b, hb⟩ := finpartition.nonempty_of_mem_parts _ huv.1.2, exact hst (subtype.ext_val $ prod.ext (P.disjoint.elim_finset hs.1 ht.1 a (finpartition.le _ huv.1.1 ha) (finpartition.le _ huv.2.1 ha)) (P.disjoint.elim_finset hs.2.1 ht.2.1 b (finpartition.le _ huv.1.2 hb) (finpartition.le _ huv.2.2 hb))), end lemma pair_contrib_lower_bound [nonempty α] (x : {i // i ∈ P.parts.off_diag}) (hε₁ : ε ≤ 1) (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPε : 100 ≤ 4^P.parts.card * ε^5) : G.edge_density x.1.1 x.1.2^2 - ε^5/25 + (if G.is_uniform ε x.1.1 x.1.2 then 0 else ε^4/3) ≤ pair_contrib G ε hP x / (16^P.parts.card) := begin split_ifs, { rw add_zero, exact sq_density_sub_eps_le_sum_sq_density_div_card hPα hPε _ _ }, { apply sq_density_sub_eps_le_sum_sq_density_div_card_of_nonuniform hPα hPε hε₁ _ h, exact ((mem_off_diag _ _).1 x.2).2.2 } end lemma uniform_add_nonuniform_eq_off_diag_pairs [nonempty α] (hε₁ : ε ≤ 1) (hP₇ : 7 ≤ P.parts.card) (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPε : 100 ≤ 4^P.parts.card * ε^5) (hPG : ¬P.is_uniform G ε) : (∑ x in P.parts.off_diag, G.edge_density x.1 x.2 ^ 2 + P.parts.card^2 * (ε ^ 5 / 4)) / P.parts.card ^ 2 ≤ ∑ x in P.parts.off_diag.attach, pair_contrib G ε hP x / (hP.increment G ε).parts.card ^ 2 := begin conv_rhs { rw [←sum_div, card_increment hPα hPG, exp_bound, ←nat.cast_pow, mul_pow, pow_right_comm, nat.cast_mul, mul_comm, ←div_div_eq_div_mul, (show 4^2 = 16, by norm_num), sum_div] }, rw [←nat.cast_pow, nat.cast_pow 16], refine div_le_div_of_le_of_nonneg _ (nat.cast_nonneg _), norm_num, suffices : _ ≤ ∑ x in P.parts.off_diag.attach, (G.edge_density x.1.1 x.1.2^2 - ε^5/25 + if G.is_uniform ε x.1.1 x.1.2 then 0 else ε^4/3), { apply le_trans this (sum_le_sum (λ i hi, pair_contrib_lower_bound i hε₁ hPα hPε)) }, have : ∑ x in P.parts.off_diag.attach, (G.edge_density x.1.1 x.1.2^2 - ε^5/25 + if G.is_uniform ε x.1.1 x.1.2 then 0 else ε^4/3) = ∑ x in P.parts.off_diag, (G.edge_density x.1 x.2^2 - ε^5/25 + if G.is_uniform ε x.1 x.2 then 0 else ε^4/3), { convert sum_attach, refl }, rw [this, sum_add_distrib, sum_sub_distrib, sum_const, nsmul_eq_mul, sum_ite, sum_const_zero, zero_add, sum_const, nsmul_eq_mul, ←finpartition.non_uniform_pairs], rw finpartition.is_uniform at hPG, simp only [not_le] at hPG, apply le_trans _ (add_le_add_left (mul_le_mul_of_nonneg_right hPG.le _) _), { conv_rhs { congr, congr, skip, rw [off_diag_card], congr, congr, conv { congr, skip, rw ←mul_one P.parts.card }, rw ←nat.mul_sub_left_distrib }, simp_rw [mul_assoc, sub_add_eq_add_sub, add_sub_assoc, ←mul_sub_left_distrib, mul_div_assoc' ε, ←pow_succ, div_eq_mul_one_div (ε^5), ←mul_sub_left_distrib], rw [mul_left_comm, mul_left_comm _ (ε^5), sq, mul_assoc, nat.cast_mul, mul_assoc], apply add_le_add_left, apply mul_le_mul_of_nonneg_left _ (eps_pow_five_pos hPε).le, apply mul_le_mul_of_nonneg_left _ (nat.cast_nonneg _), rw [nat.cast_sub (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos, mul_sub_right_distrib, nat.cast_one, one_mul, le_sub, ←mul_sub_left_distrib, ←div_le_iff (show (0:ℝ) < 1/3 - 1/25 - 1/4, by norm_num)], refine le_trans (show _ ≤ (7:ℝ), by norm_num) (by exact_mod_cast hP₇) }, exact div_nonneg (pow_bit0_nonneg _ _) (by norm_num), end lemma energy_increment [nonempty α] (hP : P.is_equipartition) (hP₇ : 7 ≤ P.parts.card) (hε : 100 < 4^P.parts.card * ε^5) (hPα : P.parts.card * 16^P.parts.card ≤ card α) (hPG : ¬P.is_uniform G ε) (hε₁ : ε ≤ 1) : P.energy G + ε^5 / 4 ≤ (hP.increment G ε).energy G := begin have h := uniform_add_nonuniform_eq_off_diag_pairs hε₁ hP₇ hPα hε.le hPG, rw [add_div, mul_div_cancel_left] at h, exact h.trans off_diag_pairs_le_increment_energy, refine (sq_pos_of_ne_zero _ $ _).ne', norm_cast, linarith, end end finpartition
4edefc31560d460303441f9bcbe622b59746b6ae
92b1c7f0343a6a5cd36bc0f623a7490da3f1e0f3
/src/stump/sample_complexity.lean
5bdc705147da0798864d079df4d1de746faa5e49
[ "Apache-2.0" ]
permissive
jtristan/stump-learnable
717453eb590af16e60c7d3806cc9e66492fab091
aa3c089f41602efa08d31ef6b41e549456186d57
refs/heads/master
1,625,630,634,360
1,607,552,106,000
1,607,552,106,000
218,629,406
15
2
null
null
null
null
UTF-8
Lean
false
false
1,698
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import analysis.complex.exponential import ..lib.util open real noncomputable def complexity (ε: ℝ) (δ: ℝ) : ℝ := (log(δ) / log(1 - ε)) - (1: nat) lemma complexity_enough: ∀ ε: nnreal, ∀ δ: nnreal, ∀ n: ℕ, ε > (0: nnreal) → ε < (1: nnreal) → δ > (0: nnreal) → δ < (1: nnreal) → (n: ℝ) > (complexity ε δ) → ((1 - ε)^(n+1)) ≤ δ := begin unfold complexity, intros, have h0: ((1: nnreal) - ε) > 0, by change (0 < 1 - ε);rwa[nnreal.coe_pos, nnreal.coe_sub _ _ (le_of_lt (a_1)), sub_pos,←nnreal.coe_lt], rw log_le_log_nnreal ; try {assumption} ; try {exact pow_pos h0 (n + 1)}, have h2:= log_pow_nnreal (1 - ε) h0 (n+1), unfold_coes at *, rw ← pow_coe, rw h2, apply mul_le_of_div_le_of_neg, { rw ←exp_lt_exp, simp, rw exp_log _, { rw sub_nnreal, cases ε, exact sub_lt_self 1 a, apply le_of_lt, assumption, }, { rw sub_nnreal, cases ε, exact sub_pos.mpr a_1, apply le_of_lt, assumption, }, }, { apply le_of_lt, clear h2, have nat_cast_1: ∀ x: ℕ, (nat.cast x) + (1:ℝ) = nat.cast(x + 1), exact nat.cast_succ, rw ← nat_cast_1, have minus_nnreal: ∀ x: nnreal, x < 1 → (1 - x).val = 1 - x.val, assume x h, exact nnreal.coe_sub _ _ (le_of_lt h), rw minus_nnreal, swap, assumption, rw gt_from_lt at a_4, have plus_1:= add_lt_add_right a_4 1, simp at plus_1, simp, conv_rhs { rw add_comm, skip,}, have one_coe: (1: ℝ) = nat.cast 1, by unfold nat.cast; simp, conv_rhs {rw one_coe, skip,}, assumption, }, end
e0266a5e343d7c165a6f8e99df095d88c06f7b8a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/protected_test.lean
1288abb6c48a9cf16654c5c10af3983eb0347f32
[ "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
279
lean
namespace nat #check induction_on -- ERROR #check rec_on -- ERROR #check less_than_or_equal.rec_on -- OK #check nat.less_than_or_equal.rec_on namespace le #check rec_on -- ERROR #check less_than_or_equal.rec_on end le end nat
73ba06ef1394d92919dec88ce1435da77dfd78f3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/pi.lean
1b4e1f3e1ac5cba460af38bf7ebb32379d29083b
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
2,379
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.group.pi import algebra.order.group import tactic.pi_instances /-! # Pi instances for ordered groups and monoids This file defines instances for ordered group, monoid, and related structures on Pi types. -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi /-- The product of a family of ordered commutative monoids is an ordered commutative monoid. -/ @[to_additive "The product of a family of ordered additive commutative monoids is an ordered additive commutative monoid."] instance ordered_comm_monoid {ι : Type*} {Z : ι → Type*} [∀ i, ordered_comm_monoid (Z i)] : ordered_comm_monoid (Π i, Z i) := { mul_le_mul_left := λ f g w h i, mul_le_mul_left' (w i) _, ..pi.partial_order, ..pi.comm_monoid, } @[to_additive] instance {ι : Type*} {α : ι → Type*} [Π i, has_le (α i)] [Π i, has_mul (α i)] [Π i, has_exists_mul_of_le (α i)] : has_exists_mul_of_le (Π i, α i) := ⟨λ a b h, ⟨λ i, (exists_mul_of_le $ h i).some, funext $ λ i, (exists_mul_of_le $ h i).some_spec⟩⟩ /-- The product of a family of canonically ordered monoids is a canonically ordered monoid. -/ @[to_additive "The product of a family of canonically ordered additive monoids is a canonically ordered additive monoid."] instance {ι : Type*} {Z : ι → Type*} [∀ i, canonically_ordered_monoid (Z i)] : canonically_ordered_monoid (Π i, Z i) := { le_self_mul := λ f g i, le_self_mul, ..pi.order_bot, ..pi.ordered_comm_monoid, ..pi.has_exists_mul_of_le } @[to_additive] instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), npow := monoid.npow, .. pi.partial_order, .. pi.monoid }; tactic.pi_instance_derive_field @[to_additive] instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) := { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), npow := monoid.npow, ..pi.comm_group, ..pi.ordered_comm_monoid, } end pi
00b7ef3ab9e56926729b3e8e28484f0caa1bcf47
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world8/level3.lean
33c1cc4c397fdaf8095e833a211ba50259ca7fa4
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
637
lean
import mynat.definition -- hide import mynat.add -- hide import game.world8.level2 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 3: `succ_eq_succ_of_eq`. -/ /- We are going to prove something completely obvious: if $a=b$ then $succ(a)=succ(b)$. This is *not* `succ_inj`! This is trivial -- we can just rewrite our proof of `a=b`. But how do we get to that proof? Use the `intro` tactic. -/ /- Theorem For all naturals $a$ and $b$, $a=b\implies succ(a)=succ(b)$. -/ theorem succ_eq_succ_of_eq {a b : mynat} : a = b → succ(a) = succ(b) := begin [less_leaky] intro h, rw h, refl, end end mynat -- hide
ec16dbc7942f638e093d3b9794413a131f580fe2
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/congr_imp_bug.lean
50ce6df7c6c337b13789c89a60ea2f471bc86c29
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,140
lean
---------------------------------------------------------------------------------------------------- --- Copyright (c) 2014 Microsoft Corporation. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad ---------------------------------------------------------------------------------------------------- import algebra.function open function namespace congr inductive struc [class] {T1 : Type} {T2 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (f : T1 → T2) : Prop := mk : (∀x y : T1, R1 x y → R2 (f x) (f y)) → struc R1 R2 f definition app {T1 : Type} {T2 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {f : T1 → T2} (C : struc R1 R2 f) {x y : T1} : R1 x y → R2 (f x) (f y) := struc.rec id C x y inductive struc2 {T1 : Type} {T2 : Type} {T3 : Type} (R1 : T1 → T1 → Prop) (R2 : T2 → T2 → Prop) (R3 : T3 → T3 → Prop) (f : T1 → T2 → T3) : Prop := mk2 : (∀(x1 y1 : T1) (x2 y2 : T2), R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2)) → struc2 R1 R2 R3 f definition app2 {T1 : Type} {T2 : Type} {T3 : Type} {R1 : T1 → T1 → Prop} {R2 : T2 → T2 → Prop} {R3 : T3 → T3 → Prop} {f : T1 → T2 → T3} (C : struc2 R1 R2 R3 f) {x1 y1 : T1} {x2 y2 : T2} : R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2) := struc2.rec id C x1 y1 x2 y2 theorem compose21 {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {T4 : Type} {R4 : T4 → T4 → Prop} {g : T2 → T3 → T4} (C3 : congr.struc2 R2 R3 R4 g) ⦃T1 : Type⦄ -- nice! {R1 : T1 → T1 → Prop} {f1 : T1 → T2} (C1 : congr.struc R1 R2 f1) {f2 : T1 → T3} (C2 : congr.struc R1 R3 f2) : congr.struc R1 R4 (λx, g (f1 x) (f2 x)) := struc.mk (take x1 x2 H, app2 C3 (app C1 H) (app C2 H)) theorem congr_and : congr.struc2 iff iff iff and := sorry theorem congr_and_comp [instance] {T : Type} {R : T → T → Prop} {f1 f2 : T → Prop} (C1 : struc R iff f1) (C2 : struc R iff f2) : congr.struc R iff (λx, f1 x ∧ f2 x) := congr.compose21 congr_and C1 C2 end congr
c0212be667097ff4e512077cc18445f4978c6eb3
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/ideal_operations.lean
b20f495c825e71b4aa4fe44b64f8d776e7c04e44
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
35,121
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau More operations on modules and ideals. -/ import data.nat.choose import data.equiv.ring import ring_theory.algebra_operations import ring_theory.ideals universes u v w x open_locale big_operators namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := begin refine quotient.lift (⨅ i, f i) _ _, { convert @@pi.ring_hom (λ i, quotient (f i)) (λ i, ring.to_semiring) ring.to_semiring (λ i, quotient.mk (f i)) }, { intros r hr, rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) } end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} [comm_ring R] variables {I J K L: ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, ideal.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, ideal.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right hri, J.mul_mem_left hsj⟩ theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right $ I.mul_mem_left $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right hyni) (λ hmc, I.mul_mem_right $ I.mul_mem_right $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, show (r * s)^n ∈ I, from (mul_pow r s n).symm ▸ I.mul_mem_left hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right hrm, (pow_add r m n).symm ▸ J.mul_mem_left hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, classical.or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right hpm) (m.add_mem (m.mul_mem_left hfm) (m.mul_mem_left hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr instance : comm_semiring (ideal R) := submodule.comm_semiring @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : radical_mul _ _ ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK theorem is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem (mul_mem_mul hri hsj)) variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [comm_ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [comm_ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem hrni⟩ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def order_iso_of_surjective : ((≤) : ideal S → ideal S → Prop) ≃o ((≤) : { p : ideal R // comap f ⊥ ≤ p } → { p : ideal R // comap f ⊥ ≤ p } → Prop) := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, ord' := λ I1 I2, ⟨comap_mono, λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H⟩ } def le_order_embedding_of_surjective : ((≤) : ideal S → ideal S → Prop) ≼o ((≤) : ideal R → ideal R → Prop) := (order_iso_of_surjective f hf).to_order_embedding.trans (subtype.order_embedding _ _) def lt_order_embedding_of_surjective : ((<) : ideal S → ideal S → Prop) ≼o ((<) : ideal R → ideal R → Prop) := (le_order_embedding_of_surjective f hf).lt_embedding_of_le_embedding theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine classical.or_iff_not_imp_left.2 (λ ne_top, ⟨λ h, ne_top h, λ J hJ, _⟩), { refine (order_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.right (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end end surjective lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def order_iso_of_bijective : ((≤) : ideal S → ideal S → Prop) ≃o ((≤) : ideal R → ideal R → Prop):= { to_fun := comap f, inv_fun := map f, left_inv := (order_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((order_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), ord' := (order_iso_of_surjective f hf.right).ord' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((order_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine classical.or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.left _); calc I = comap f (map f I) : ((order_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top theorem comap.is_maximal (H : is_maximal K) : is_maximal (comap f K) := begin refine ⟨λ h, H.left _, λ J hJ, _⟩, { have : map f (comap f K) = ⊤ := eq.trans (congr_arg (map f) h) (map_top _), rwa ← (order_iso_of_bijective f hf).left_inv K }, { refine (order_iso_of_bijective f hf).symm.injective (eq.trans (H.right (map f J) (lt_of_le_of_ne _ _)) (map_top f).symm), { exact (comap_le_iff_le_map f hf).1 (le_of_lt hJ) }, { exact λ h, hJ.right ((map_le_iff_le_comap).1 (le_of_eq h.symm)) } } end end bijective end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.2 hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} [comm_ring R] section comm_ring variables [comm_ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.injective_iff_trivial_ker f lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by rw [submodule.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal.-/ lemma ker_is_prime [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ end ring_hom namespace ideal variables {R : Type*} {S : Type*} [comm_ring R] [comm_ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, rw ← hx, refine mem_map_of_mem _, rw Inf_eq_infi at ⊢ hy, simp at ⊢ hy, intros J hJ, have : y ∈ map f J := hy (map f J) J hJ rfl, cases (mem_map_iff_of_surjective f hf).1 this with x' hx', have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, hx'.right], exact sub_self y }, have := J.add_mem this hx'.left, rwa [sub_add, sub_self, sub_zero] at this } end end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- It is even a semialgebra. But those aren't in mathlib yet. instance semimodule_submodule : semimodule (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule
e61e4659e7628c2a64415bd6399288049150fe54
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/ring.lean
dc597798e193136164e6bcdac250d9047c6e6557
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
38,314
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.group.hom import algebra.group.units import algebra.group_with_zero /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : (mul_right r : R → R) a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp, norm_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →+ β) = f := rfl namespace ring_hom variables [rα : semiring α] [rβ : semiring β] section include rα rβ @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl variables (f : α →+* β) {x y : α} {rα rβ} theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, coe_inj $ show ((f : α →+ β) : α → β) = (g : α →+ β), from congr_arg coe_fn h theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, coe_inj $ show ((f : α →* β) : α → β) = (g : α →* β), from congr_arg coe_fn h /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} instance comm_semiring.comm_monoid_with_zero : comm_monoid_with_zero α := { .. (‹_› : comm_semiring α) } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [add_mul, mul_add, mul_comm, add_assoc] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two instance comm_semiring_has_dvd : has_dvd α := has_dvd.mk (λ a b, ∃ c, b = a * c) -- TODO: this used to not have c explicit, but that seems to be important -- for use with tactics, similar to exist.intro theorem dvd.intro (c : α) (h : a * c = b) : a ∣ b := exists.intro c h^.symm alias dvd.intro ← dvd_of_mul_right_eq theorem dvd.intro_left (c : α) (h : c * a = b) : a ∣ b := dvd.intro _ (begin rewrite mul_comm at h, apply h end) alias dvd.intro_left ← dvd_of_mul_left_eq theorem exists_eq_mul_right_of_dvd (h : a ∣ b) : ∃ c, b = a * c := h theorem dvd.elim {P : Prop} {a b : α} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd (h : a ∣ b) : ∃ c, b = c * a := dvd.elim h (assume c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c))) theorem dvd.elim_left {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd h₁) (assume c, assume h₃ : b = c * a, h₂ c h₃) @[refl, simp] theorem dvd_refl (a : α) : a ∣ a := dvd.intro 1 (by simp) local attribute [simp] mul_assoc mul_comm mul_left_comm @[trans] theorem dvd_trans (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄]⟩ end alias dvd_trans ← dvd.trans theorem eq_zero_of_zero_dvd (h : 0 ∣ a) : a = 0 := dvd.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (zero_mul c)) /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ @[simp] theorem dvd_zero (a : α) : a ∣ 0 := dvd.intro 0 (by simp) @[simp] theorem one_dvd (a : α) : 1 ∣ a := dvd.intro a (by simp) @[simp] theorem dvd_mul_right (a b : α) : a ∣ a * b := dvd.intro b rfl @[simp] theorem dvd_mul_left (a b : α) : a ∣ b * a := dvd.intro b (by simp) theorem dvd_mul_of_dvd_left (h : a ∣ b) (c : α) : a ∣ b * c := dvd.elim h (λ d h', begin rw [h', mul_assoc], apply dvd_mul_right end) theorem dvd_mul_of_dvd_right (h : a ∣ b) (c : α) : a ∣ c * b := begin rw mul_comm, exact dvd_mul_of_dvd_left h _ end theorem mul_dvd_mul : ∀ {a b c d : α}, a ∣ b → c ∣ d → a * c ∣ b * d | a ._ c ._ ⟨e, rfl⟩ ⟨f, rfl⟩ := ⟨e * f, by simp⟩ theorem mul_dvd_mul_left (a : α) {b c : α} (h : b ∣ c) : a * b ∣ a * c := mul_dvd_mul (dvd_refl a) h theorem mul_dvd_mul_right (h : a ∣ b) (c : α) : a * c ∣ b * c := mul_dvd_mul h (dvd_refl c) theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) theorem dvd_of_mul_right_dvd (h : a * b ∣ c) : a ∣ c := dvd.elim h (begin intros d h₁, rw [h₁, mul_assoc], apply dvd_mul_right end) theorem dvd_of_mul_left_dvd (h : a * b ∣ c) : b ∣ c := dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq])) lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ attribute [instance, priority 200] ring.to_semiring /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp [sub_eq_add_neg] alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp [sub_eq_add_neg] alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [ring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib, sub_eq_add_neg] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self_eq, mul_one] theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {α : Type*} [comm_ring α] {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {R : Type*} [comm_ring R] {a b c : R} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by { convert h, simp }))) /-- An element of the unit group of a nonzero semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [semiring α] [nontrivial α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, mul_right_inj' ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, mul_left_inj' hc] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } end integral_domain /-! ### Units in various rings -/ namespace units section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring end units namespace is_unit section comm_semiring variables [comm_semiring R] lemma mul_right_dvd_of_dvd {a b c : R} (hb : is_unit b) (h : a ∣ c) : a * b ∣ c := begin rcases hb with ⟨b, rfl⟩, rcases h with ⟨c', rfl⟩, use (b⁻¹ : units R) * c', rw [mul_assoc, units.mul_inv_cancel_left] end lemma mul_left_dvd_of_dvd {a b c : R} (hb : is_unit b) (h : a ∣ c) : b * a ∣ c := begin rcases hb with ⟨b, rfl⟩, rcases h with ⟨c', rfl⟩, use (b⁻¹ : units R) * c', rw [mul_comm (b : R) a, mul_assoc, units.mul_inv_cancel_left] end end comm_semiring end is_unit /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
5a139a71fbf0b28b46f5a9c0efef3179a0084290
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/spectrum_of_a_ring/structure_sheaf_condition.lean
bcad7fef7dfbefd3f0a7ce3fc9a3b6f047fbbe7f
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,774
lean
/- If (fᵢ) = R, the sequene R → Π R[1/fᵢ] → Π R[1/fᵢfⱼ] is exact. https://stacks.math.columbia.edu/tag/00EJ TODO : Factor out all the finset sum lemmas and clean up the main proof. -/ import ring_theory.localization import algebra.pi_instances import linear_algebra.linear_combination import to_mathlib.localization.localization_alt import to_mathlib.finset_range import to_mathlib.ring_hom import spectrum_of_a_ring.structure_presheaf_res universes u v w local attribute [instance] classical.prop_decidable open localization_alt open finset lemma finset.sum_of_mem_span {α : Type u} {β : Type v} [comm_ring α] [add_comm_group β] [module α β] {S : finset β} {x : β} : x ∈ submodule.span α S.to_set → ∃ r : β → α, x = finset.sum S (λ y, r y • y) := begin intros Hx, rw mem_span_iff_lc at Hx, rcases Hx with ⟨l, Hls, Hlt⟩, rw lc.total_apply at Hlt, rw lc.mem_supported at Hls, rw ←Hlt, simp [finsupp.sum], use (λ x, if x ∈ S then l.to_fun x else 0), apply finset.sum_bij_ne_zero (λ x _ _, x), { intros a H₁ H₂, exact Hls H₁, }, { intros a₁ a₂ H₁₁ H₁₂ H₂₁ H₂₂ H, exact H, }, { intros b HbS Hb, use b, erw (if_pos HbS) at Hb, have Hlbnz : l.to_fun b ≠ 0, intros HC, rw HC at Hb, rw zero_smul at Hb, exact (Hb rfl), use [(finsupp.mem_support_iff.2 Hlbnz), Hb], }, { intros a H₁ H₂, have HaS : a ∈ S := Hls H₁, rw (if_pos HaS), refl, }, end lemma finset.image_sum_of_mem_span {α : Type u} {β : Type v} [comm_ring α] [comm_ring β] [module α β] {γ : Type w} {S : finset γ} {f : γ → β} {x : β} : x ∈ submodule.span α (finset.image f S).to_set → ∃ r : γ → α, x = finset.sum S (λ b, r b • f b) := begin intros Hx, rcases (finset.sum_of_mem_span Hx) with ⟨r, Hr⟩, have Hz : ∀ y ∈ S, ∃ z ∈ S, f z = f y := λ y hy, ⟨y, hy, rfl⟩, use (λ y, if ∃ Hy : y ∈ S, y = classical.some (Hz y Hy) then r (f y) else 0), rw Hr, apply finset.sum_bij_ne_zero (λ a Ha _, classical.some (finset.mem_image.1 Ha)), { intros a H₁ H₂, rcases (classical.some_spec (finset.mem_image.1 H₁)) with ⟨Ha, Hf⟩, exact Ha, }, { intros a₁ a₂ H₁₁ H₁₂ H₂₁ H₂₂ H, rcases (classical.some_spec (finset.mem_image.1 H₁₁)) with ⟨Ha₁, Hf₁⟩, rcases (classical.some_spec (finset.mem_image.1 H₂₁)) with ⟨Ha₂, Hf₂⟩, rw [←Hf₁, ←Hf₂], congr, exact H, }, { intros b HbS Hb, have Hfb : f b ∈ finset.image f S := finset.mem_image.2 ⟨b, HbS, rfl⟩, have Hbeq : b = classical.some (finset.mem_image.1 Hfb), apply classical.by_contradiction, intros HC, replace HC := not_exists.2 (λ Hy : b ∈ S, HC), rw if_neg HC at Hb, rw zero_smul at Hb, exact (Hb rfl), have Hbex : ∃ (Hy : b ∈ S), b = classical.some _ := ⟨HbS, Hbeq⟩, rw if_pos Hbex at Hb, use [f b, Hfb, Hb], exact Hbeq, }, { intros a H₁ H₂, rcases (classical.some_spec (finset.mem_image.1 H₁)) with ⟨Ha, Hf⟩, rw [if_pos, Hf], use Ha, simp only [Hf], } end lemma sum_pow_mem_span_pow {α : Type u} {β : Type v} [comm_ring α] (f r : β → α) (n : β → ℕ) {S : finset β} : (S.sum (λ a, r a • f a)) ^ ((S.sum n) + 1) ∈ submodule.span α (↑(S.image (λ a, f a ^ n a)) : set α) := begin apply finset.induction_on S, { simp, }, { intros a T HanT IH, repeat { rw finset.sum_insert HanT, }, rw [finset.image_insert, finset.coe_insert, submodule.mem_span_insert], have H := add_pow_sum (r a * f a) (sum T (λ a, r a • f a)) (n a) (sum T n + 1), rcases H with ⟨x, y, H⟩, have Hx := @submodule.smul_mem _ _ _ _ _ _ _ x IH, use [y * (r a) ^ (n a), x • sum T (λ (a : β), r a • f a) ^ (sum T n + 1), Hx], repeat { rw smul_eq_mul, }, rw [add_assoc, H, add_comm, mul_pow, mul_assoc], } end lemma one_mem_span_pow_of_mem_span {α : Type u} {β : Type v} [comm_ring α] (f : β → α) (n : β → ℕ) {S : finset β} (Hx : (1 : α) ∈ submodule.span α (↑(S.image f) : set α)) : (1 : α) ∈ submodule.span α (↑(S.image (λ x, f x ^ n x)) : set α) := begin rcases (finset.image_sum_of_mem_span Hx) with ⟨r, Hr⟩, rw [←one_pow ((S.sum n) + 1), Hr], apply sum_pow_mem_span_pow, end section exact_sequence -- Ring R. parameters (R : Type u) [comm_ring R] -- f1, ..., fn parameters {γ : Type v} [fintype γ] {f : γ → R} -- R[1/f1], ..., R[1/fn] parameters {Rfi : γ → Type w} [Π i, comm_ring (Rfi i)] -- α1 : R → R[1/f1], ...., αn → R[1/fn] parameters {αi : Π i, R → (Rfi i)} [Π i, is_ring_hom (αi i)] parameters (Hlocα : Π i, is_localization (powers (f i)) (αi i)) parameters (Hlocα' : Π i, is_localization_data (powers (f i)) (αi i)) def α : R → Π i, Rfi i := λ r i, (αi i) r section alpha_injective instance PRfs.comm_ring : comm_ring (Π i, Rfi i) := pi.comm_ring instance α.is_ring_hom : is_ring_hom α := pi.is_ring_hom_pi αi -- First part of the lemma. include Hlocα' lemma standard_covering₁ (H : (1 : R) ∈ ideal.span (set.range f)) : function.injective α := begin rw ←@is_ring_hom.inj_iff_trivial_ker _ _ _ _ α (α.is_ring_hom), intros x Hx, replace Hx := congr_fun Hx, have Hn : ∀ i, ∃ n : ℕ, f i ^ n * x = 0, intros i, replace Hx : x ∈ ker (αi i) := Hx i, replace Hloc := Hlocα' i, rcases Hloc with ⟨Hinv, Hden, Hker⟩, replace Hx := Hker Hx, rcases Hx with ⟨⟨⟨u, ⟨fn, ⟨n, Hfn⟩⟩⟩, Hufn⟩, Hx⟩, existsi n, rw [Hfn, ←Hx, mul_comm], exact Hufn, let e : γ → ℕ := λ i, classical.some (Hn i), have He : ∀ i, f i ^ e i * x = 0 := λ i, classical.some_spec (Hn i), rw ←one_mul x, -- Σ ai * (f i) = 1 rw finset.coe_image_univ at H, cases finset.image_sum_of_mem_span (one_mem_span_pow_of_mem_span f e H) with r Hone, rw [Hone, finset.sum_mul, ←@finset.sum_const_zero γ _ finset.univ], apply finset.sum_congr rfl (λ i _, _), rw [smul_eq_mul, mul_assoc, He i, mul_zero], end end alpha_injective section beta_kernel_image_alpha -- R[1/f1f1], ..., R[1/fnfn] parameters {Rfij : γ → γ → Type w} [Π i j, comm_ring (Rfij i j)] parameters {φij : Π i j, R → (Rfij i j)} [Π i j, is_ring_hom (φij i j)] parameters (Hlocφ : Π i j, is_localization (powers ((f i)*(f j))) (φij i j)) parameters (Hlocφ' : Π i j, is_localization_data (powers ((f i)*(f j))) (φij i j)) include Hlocφ' -- fj is invertible in R[1/fifj]. noncomputable def inverts_powers1 : Π i j, inverts_data (powers (f j)) (φij i j) := λ i j r, begin rcases r with ⟨r, Hr⟩, rcases (classical.indefinite_description _ Hr) with ⟨n, Hn⟩, rcases ((Hlocφ' i j).inverts ⟨((f i)*(f j))^n, ⟨n , by simp⟩⟩) with ⟨w, Hw⟩, use ((φij i j ((f i)^n)) * w), simp, simp at Hw, rw [←Hn, ←mul_assoc, ←is_ring_hom.map_mul (φij i j), ←mul_pow, mul_comm (f j)], exact Hw, end -- fi is invertible in R[1/fifj]. noncomputable def inverts_powers2 : Π i j, inverts_data (powers (f i)) (φij i j) := λ i j r, begin cases r with r Hr, cases (classical.indefinite_description _ Hr) with n Hn, cases ((Hlocφ' i j).inverts ⟨((f i)*(f j))^n, ⟨n , by simp⟩⟩) with w Hw, use ((φij i j ((f j)^n)) * w), simp, simp at Hw, rw [←Hn, ←mul_assoc, ←is_ring_hom.map_mul (φij i j), ←mul_pow], exact Hw, end noncomputable def β1 : (Π i, Rfi i) → (Π i j, Rfij i j) := λ ri i j, (is_localization_initial (powers (f j)) (αi j) (Hlocα' j) (φij i j) (inverts_powers1 i j)) (ri j) noncomputable def β2 : (Π i, Rfi i) → (Π i j, Rfij i j) := λ ri i j, (is_localization_initial (powers (f i)) (αi i) (Hlocα' i) (φij i j) (inverts_powers2 i j)) (ri i) noncomputable def β : (Π i, Rfi i) → (Π i j, Rfij i j) := λ r, (β1 r) - (β2 r) lemma standard_covering₂.aux (s : Π i, Rfi i) : ∀ i j, (β1 s i j = β2 s i j → ∃ n : ℕ, (((Hlocα' j).has_denom (s j)).1.2 * ((Hlocα' i).has_denom (s i)).1.1 - ((Hlocα' i).has_denom (s i)).1.2 * ((Hlocα' j).has_denom (s j)).1.1) * ((f i) * (f j))^n = 0) := begin intros i j, simp [β1, β2, is_localization_initial], rcases ((Hlocα' i).has_denom (s i)) with ⟨⟨q1, p1⟩, Hp1q1⟩, rcases ((Hlocα' j).has_denom (s j)) with ⟨⟨q2, p2⟩, Hp2q2⟩, simp at Hp1q1, simp at Hp2q2, dsimp [subtype.coe_mk], rcases ((Hlocα' i).inverts q1) with ⟨w1, Hw1⟩, rcases ((Hlocα' j).inverts q2) with ⟨w2, Hw2⟩, rcases (inverts_powers2 i j q1) with ⟨v1, Hv1⟩, rcases (inverts_powers1 i j q2) with ⟨v2, Hv2⟩, dsimp [subtype.coe_mk], intros H, have Hker : φij i j (p2 * q1 - p1 * q2) = 0, rw is_ring_hom.map_sub (φij i j), iterate 2 { rw is_ring_hom.map_mul (φij i j), }, rw [sub_eq_zero, ←one_mul (_ * _), ←Hv2, ←mul_assoc, mul_assoc _ v2 _, mul_comm v2], rw [H, ←mul_assoc, mul_assoc _ v1 _, mul_comm v1], rw [Hv1, mul_one, mul_comm], replace Hker : _ ∈ ker (φij i j) := Hker, replace Hker := (Hlocφ' i j).ker_le Hker, rcases Hker with ⟨⟨⟨u, v⟩, Huv⟩, Hzer⟩, dsimp at Huv, dsimp only [subtype.coe_mk] at Hzer, rw Hzer at Huv, rcases v with ⟨v, ⟨n, Hn⟩⟩, dsimp only [subtype.coe_mk] at Huv, rw ←Hn at Huv, use n, exact Huv, end lemma standard_covering₂.aux₂ (s : Π i, Rfi i) : (∀ i j, β1 s i j = β2 s i j) → ∃ N : ℕ, ∀ i j, (((Hlocα' j).has_denom (s j)).1.2 * ((Hlocα' i).has_denom (s i)).1.1 - ((Hlocα' i).has_denom (s i)).1.2 * ((Hlocα' j).has_denom (s j)).1.1) * ((f i) * (f j))^N = 0 := begin intros Hs, let n : γ × γ → ℕ := λ ij, classical.some (standard_covering₂.aux s ij.1 ij.2 (Hs ij.1 ij.2)), let N := finset.sum (@finset.univ (γ × γ) _) n, use N, intros i j, have Hn : ∀ i j, n (i, j) ≤ N, intros i j, exact finset.single_le_sum (λ _ _, nat.zero_le _) (finset.mem_univ (i, j)), rw [←nat.sub_add_cancel (Hn i j), add_comm, pow_add, ←mul_assoc], rw [classical.some_spec (standard_covering₂.aux s i j (Hs i j)), zero_mul], end lemma standard_covering₂.aux₃ (s : Π i, Rfi i) : (∀ i j, β1 s i j = β2 s i j) → ∃ N : ℕ, ∀ i j, (((Hlocα' j).has_denom (s j)).1.2 * (f j)^N * ((Hlocα' i).has_denom (s i)).1.1 * (f i)^N = ((Hlocα' i).has_denom (s i)).1.2 * (f i)^N * ((Hlocα' j).has_denom (s j)).1.1 * (f j)^N) := begin intros H, rcases (standard_covering₂.aux₂ s H) with ⟨N, HN⟩, existsi N, intros i j, replace HN := HN i j, rw [sub_mul, sub_eq_zero] at HN, rw [mul_assoc _ (f i ^ N) _, mul_assoc _ (f j ^ N) _], rw [mul_comm (f i ^ N), mul_comm (f j ^ N), ←mul_assoc, ←mul_assoc], rw [mul_assoc _ _ (f i ^ N), ←mul_pow, mul_comm (f j)], rw [mul_assoc _ _ (f j ^ N), ←mul_pow], exact HN, end lemma standard_covering₂ (Hone : (1:R) ∈ ideal.span (set.range f)) (s : Π i, Rfi i) : β s = 0 ↔ ∃ r : R, α r = s := begin rw finset.coe_image_univ at Hone, split, { intros H, suffices Hsuff : ∃ (r : R), ∀ i, α r i = s i, rcases Hsuff with ⟨r, Hr⟩, use r, apply funext, exact Hr, simp [α], -- Setting up. replace H := sub_eq_zero.1 H, replace H := congr_fun H, replace H := λ i j, (congr_fun (H i)) j, rcases (standard_covering₂.aux₃ s H) with ⟨N, HN⟩, let r := λ i, classical.some ((Hlocα' i).has_denom (s i)).1.1.2, have Hfiri : ∀ i, ((Hlocα' i).has_denom (s i)).1.1.1 = (f i)^(r i), intros i, simp [classical.some_spec ((Hlocα' i).has_denom (s i)).1.1.2], let t := λ i, ((Hlocα' i).has_denom (s i)).1.2, replace HN : ∀ i j, (t j) * (f j)^N * (f i)^(r i + N) = (t i) * (f i)^N * (f j)^(r j + N), intros i j, iterate 2 { rw pow_add, rw ←mul_assoc, }, rw [←Hfiri i, ←Hfiri j], exact (HN i j), -- We use the fact that if (ti) = R then (ti') = R. replace Hone := (one_mem_span_pow_of_mem_span f (λ i, r i + N) Hone), rcases (finset.image_sum_of_mem_span Hone) with ⟨a, Ha⟩, dsimp at Ha, use [finset.univ.sum (λ i, a i * (t i) * (f i) ^ N)], intros i, -- Note that: si = ti / fi^ri. have Hsi : αi i ((f i)^(r i)) * (s i) = αi i (t i), rw ←Hfiri i, exact ((Hlocα' i).has_denom (s i)).2, -- Multiply the sum by fi^(ri + N) / fi^(ri + N). rcases (Hlocα' i).inverts ⟨(f i)^(r i + N), ⟨r i + N, rfl⟩⟩ with ⟨w, Hw⟩, dsimp only [subtype.coe_mk] at Hw, rw ←mul_one (αi i _ ), rw ←Hw, rw ←mul_assoc, rw ←is_ring_hom.map_mul (αi i), rw finset.sum_mul, -- Key part : Σ ax tx' fi' = Σ ax fx' ti'. have Hsum : (λ x, a x * t x * f x ^ N * f i ^ (r i + N)) = (λ x, a x * f x ^ (r x + N) * (t i * f i ^ N)), apply funext, intros j, iterate 3 { rw mul_assoc (a j) }, rw (HN i j), symmetry, rw mul_comm (_ * _), -- Rewrite sum and use the fact that it is one. rw Hsum, rw ←finset.sum_mul, rw is_ring_hom.map_mul (αi i), rw ←Ha, rw is_ring_hom.map_one (αi i), rw one_mul, rw ←mul_one (s i), -- Kill it. rw ←Hw, rw pow_add, rw is_ring_hom.map_mul (αi i), rw is_ring_hom.map_mul (αi i), rw ←mul_assoc, rw ←mul_assoc, rw mul_comm (s i), rw Hsi, }, { rintros ⟨r, Hr⟩, rw ←Hr, erw sub_eq_zero, apply funext, intros i, apply funext, intros j, simp [β, α, β1, β2], iterate 2 { rw is_localization_initial_comp, }, } end end beta_kernel_image_alpha end exact_sequence
699ac60212b0d64c954138ce14a7be844999718d
d1bbf1801b3dcb214451d48214589f511061da63
/src/group_theory/subgroup.lean
7665077f035a16e1a30480a7f1268f062968d988
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
50,896
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl -- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, div := (/), div_eq_mul_inv := λ x y, subtype.eq $ div_eq_mul_inv x y, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin split, { intros h x x_in, rwa [h, mem_bot] at x_in }, { intros h, ext x, rw mem_bot, exact ⟨h x, by { rintros rfl, exact H.one_mem }⟩ }, end @[to_additive] lemma eq_top_of_card_eq [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin change fintype.card H.carrier = _ at h, cases H with S hS1 hS2 hS3, have : S = set.univ, { suffices : S.to_finset = finset.univ, { rwa [←set.to_finset_univ, set.to_finset_inj] at this, }, apply finset.eq_univ_of_card, rwa set.to_finset_card }, change (⟨_, _, _, _⟩ : subgroup G) = ⟨_, _, _, _⟩, congr', end @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := begin split, { introI h, rcases exists_ne (1 : H) with ⟨⟨h, h_in⟩, h_ne⟩, use [h, h_in], intro hyp, apply h_ne, simpa [hyp] }, { rintros ⟨x, x_in, hx⟩, apply nontrivial_of_ne (⟨x, x_in⟩ : H) 1, intro hyp, apply hx, simpa [has_one.one] using hyp }, end /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[to_additive] lemma subsingleton_iff : subsingleton G ↔ subsingleton (subgroup G) := ⟨ λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩, λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩⟩ @[to_additive] lemma nontrivial_iff : nontrivial G ↔ nontrivial (subgroup G) := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : subsingleton (subgroup G) := subsingleton_iff.mp ‹_› @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mp ‹_› /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[to_additive] lemma map_eq_bot_iff {G' : Type*} [group G'] {f : G →* G'} (hf : function.injective f) (H : subgroup G) : H.map f = ⊥ ↔ H = ⊥ := begin split, { rw [eq_bot_iff_forall, eq_bot_iff_forall], intros h x hx, have hfx : f x = 1 := h (f x) ⟨x, hx, rfl⟩, exact hf (show f x = f 1, by simp only [hfx, monoid_hom.map_one]), }, { intros h, rw [h, map_bot], }, end /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (λ x, x ∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) /-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] noncomputable def lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (classical.some (hf b)), map_one' := hg (classical.some_spec (hf 1)), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [classical.some_spec (hf _)], end } @[simp, to_additive] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_surjective hf g hg) (f x) = g x := begin dsimp [lift_of_surjective], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [classical.some_spec (hf _)], end @[simp, to_additive] lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } @[to_additive] lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ?
ebcbfe28afcab9a5f346a0f12699b543f86ba4cc
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/topology/metric_space/basic.lean
d2e08ae0782f33b5b3fb56e1ec197ba50745a22c
[ "Apache-2.0" ]
permissive
FredericLeRoux/mathlib
e8f696421dd3e4edc8c7edb3369421c8463d7bac
3645bf8fb426757e0a20af110d1fdded281d286e
refs/heads/master
1,607,062,870,732
1,578,513,186,000
1,578,513,186,000
231,653,181
0
0
Apache-2.0
1,578,080,327,000
1,578,080,326,000
null
UTF-8
Lean
false
false
68,125
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered open lattice set filter classical topological_space noncomputable theory open_locale uniformity open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) section prio set_option default_priority 100 -- see Note [default priority] /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. When one instantiates a metric space structure, for instance a product structure, this makes it possible to use a uniform structure and an edistance that are exactly the ones for the uniform spaces product and the emetric spaces products, thereby ensuring that everything in defeq in diamonds.-/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ennreal := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) end prio variables [metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α @[priority 200] -- see Note [lower instance priority] instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩ @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := metric_space.edist_dist _ x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4 lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4 /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, dist (f i) (f (i + 1))) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ (finset.range n).sum (λ i, dist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /-- Distance as a nonnegative real number. -/ def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] } /--In a metric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) := by rw [dist_nndist, nnreal.of_real_coe] /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist] /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : 𝓤 α = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : 𝓤 α = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', mem_infi], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_iff [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin classical, by_cases hs : s = ∅, { rw hs, exact totally_bounded_empty }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq : 𝓝 x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq, mem_infi], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (≥)] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) @[nolint] theorem mem_nhds_within_iff {t : set α} : s ∈ nhds_within x t ↔ ∃ε>0, ball x ε ∩ t ⊆ s := begin rw [mem_nhds_within_iff_exists_mem_nhds_inter], split, { rintros ⟨u, hu, H⟩, rcases mem_nhds_iff.1 hu with ⟨ε, ε_pos, hε⟩, exact ⟨ε, ε_pos, subset.trans (inter_subset_inter_left _ hε) H⟩ }, { rintros ⟨ε, ε_pos, H⟩, exact ⟨ball x ε, ball_mem_nhds x ε_pos, H⟩ } end @[nolint] theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (nhds_within a s) (nhds_within b t) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := begin split, { assume H ε ε_pos, have : ball b ε ∩ t ∈ nhds_within b t, by { rw mem_nhds_within_iff, exact ⟨ε, ε_pos, subset.refl _⟩ }, rcases mem_nhds_within_iff.1 (H this) with ⟨δ, δ_pos, hδ⟩, exact ⟨δ, δ_pos, λx xs dx, ⟨(hδ ⟨dx, xs⟩).2, (hδ ⟨dx, xs⟩).1⟩⟩ }, { assume H u hu, rcases mem_nhds_within_iff.1 hu with ⟨ε, ε_pos, hε⟩, rcases H ε ε_pos with ⟨δ, δ_pos, hδ⟩, rw [mem_map, mem_nhds_within_iff], exact ⟨δ, δ_pos, λx hx, hε ⟨(hδ hx.2 hx.1).2, (hδ hx.2 hx.1).1⟩⟩ } end @[nolint] theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} : tendsto f (nhds_within a s) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ, tendsto_nhds_within_nhds_within], simp } @[nolint] theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ, ← nhds_within_univ, tendsto_nhds_within_nhds_within], simp } theorem continuous_iff [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε : ℝ} (hf : continuous f) (hε : ε > 0) (b : α) : ∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε := let ⟨δ, δ_pos, hδ⟩ := continuous_iff.1 hf b ε hε in ⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, dist (u x) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_principal, mem_ball]; exact forall_congr (assume ε, forall_congr (assume hε, exists_sets_subset_iff.symm)) theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∃ n ∈ 𝓝 a, ∀b ∈ n, dist (f b) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_at_top_principal]; refl end metric open metric @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-Instantiate a metric space as an emetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma metric.mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { refine ⟨ennreal.of_real ε, _, λ a b, _⟩, { rwa [gt, ennreal.of_real_pos] }, { rw [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε } }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end protected theorem metric.uniformity_edist' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [metric.mem_uniformity_edist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ } end theorem uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := by simpa [infi_subtype] using @metric.uniformity_edist' α _ /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space α := { edist := edist, edist_self := by simp [edist_dist], eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := uniformity_edist, ..‹metric_space α› } /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin classical, by_cases h : 0 < ε, { ext y, by simp [edist_dist, ennreal.of_real_lt_of_real_iff h] }, { have h' : ε ≤ 0, by simpa using h, have A : ball x ε = ∅, by simpa [ball_eq_empty_iff_nonpos.symm], have B : emetric.ball x (ennreal.of_real ε) = ∅, by simp [ennreal.of_real_eq_zero.2 h', emetric.ball_eq_empty_iff], rwa [A, B] } end /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans (metric_space.uniformity_dist α) } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := let m : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in metric_space.replace_uniformity m (by rw [uniformity_edist, uniformity_edist']; refl) /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] instance : orderable_topology ℝ := orderable_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0; simp [*]; exact filter.univ_mem_sets end theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := begin simp only [uniformity_dist', nhds_eq, comap_infi, comap_principal], congr, funext ε, rw [principal_eq_iff_eq], ext ⟨a, b⟩, simp [real.dist_0_eq_abs] end lemma cauchy_seq_iff_tendsto_dist_at_top_0 [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_prod_map, metric.uniformity_eq_comap_nhds_zero, ← map_le_iff_le_comap, filter.map_map, tendsto, prod.map_def] end real section cauchy_seq variables [inhabited β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := begin unfold cauchy_seq, rw metric.cauchy_iff, simp only [true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq], split, { intros H ε εpos, rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩, exact ⟨N, λm n hm hn, ht _ _ (hN _ hm) (hN _ hn)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ hx (le_refl N)⟩ }, { exact λx y hx hy, calc dist x y ≤ dist x (u N) + dist y (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add hx hy ... = ε : add_halves _ } } end /-- A variation around the metric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := begin rw metric.cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ hn (le_refl N)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc dist (u m) (u n) ≤ dist (u m) (u N) + dist (u n) (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add (hN _ hm) (hN _ hn) ... = ε : add_halves _⟩ } end /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) := λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, real.le_Sup _ (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist x.1 y.1 := rfl section nnreal instance : metric_space nnreal := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : nnreal) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs, neg_sub], apply max_eq_right, linarith [nnreal.coe_le.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, this.map_max.symm] end, uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl end prod theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist'.comp (hf.prod_mk hg) theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist'.comp (hf.prod_mk hg) theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (𝓝 (a, b)) (𝓝 (dist a b)), from continuous_iff_continuous_at.mp continuous_dist' (a, b), tendsto.comp (by rw [nhds_prod_eq] at this; exact this) (hf.prod_mk hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (𝓝 a) (𝓝 (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_comap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist' _ lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist'.continuous lemma continuous_nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist'.comp (hf.prod_mk hg) lemma tendsto_nndist' (a b :α) : tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (𝓝 a) (𝓝 b)) (𝓝 (nndist a b)) := by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _ namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const /-- ε-characterization of the closure in metric spaces-/ theorem mem_closure_iff' {α : Type u} [metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := ⟨begin intros ha ε hε, have A : ball a ε ∩ s ≠ ∅ := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with b hb, simp, exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho ao, rcases is_open_iff.1 ho a ao with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨b, ⟨bs, bdist⟩⟩, have B : b ∈ o ∩ s := ⟨hε (by simpa [dist_comm]), bs⟩, apply ne_empty_of_mem B end⟩ lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := iff.intro ( assume ha ε hε, let ⟨b, ⟨hb, hab⟩⟩ := metric.mem_closure_iff'.1 ha ε hε in let ⟨k, hk⟩ := mem_range.1 hb in ⟨k, by { rw hk, exact hab }⟩ ) ( assume h, metric.mem_closure_iff'.2 (assume ε hε, let ⟨k, hk⟩ := h ε hε in ⟨e k, ⟨mem_range.2 ⟨k, rfl⟩, hk⟩⟩) ) lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := ⟨assume ha n, mem_closure_range_iff.1 ha (1 / ((n : ℝ) + 1)) nat.one_div_pos_of_nat, assume h, mem_closure_range_iff.2 $ assume ε hε, let ⟨n, hn⟩ := exists_nat_one_div_lt hε in let ⟨k, hk⟩ := h n in ⟨k, calc dist a (e k) < 1 / ((n : ℝ) + 1) : hk ... < ε : hn⟩⟩ theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff' _ _ s a end metric section pi open finset lattice variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine emetric_space.to_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top, simp [edist, this], assume b, rw lt_top_iff_ne_top, exact edist_ne_top (x b) (y b) }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))), { simp [edist_nndist], refine eq.symm (comp_sup_eq_sup_comp _ _ _), exact (assume x y h, ennreal.coe_le_coe.2 h), refl }, rw this, refl } end lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to nnreal using le_of_lt hr, rw_mod_cast [dist_pi_def, finset.sup_lt_iff], { simp [nndist], refl }, { exact hr } end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to nnreal using hr, rw_mod_cast [dist_pi_def, finset.sup_le_iff], simp [nndist], refl end /-- An open ball in a product space is a product of open balls. The assumption `0 < r` is necessary for the case of the empty product. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = { y | ∀b, y b ∈ ball (x b) r } := by { ext p, simp [dist_pi_lt_iff hr] } /-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r` is necessary for the case of the empty product. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } := by { ext p, simp [dist_pi_le_iff hr] } end pi section compact /-- Any compact set in a metric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α} (hs : compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← compact.finite_cover_balls end compact section proper_space open metric /-- A metric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, compact (closed_ball x r)) /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact metric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩, have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this, rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, _, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set α) ≠ ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := begin /- When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction. -/ assume non_empty, rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩, choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t), from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:ℕ, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have T₂ : closure t ⊆ univ := by simp, have T₃ : univ ⊆ closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩ end, haveI : separable_space α := ⟨by_cases A B⟩, apply emetric.second_countable_of_separable, end /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply compact_pi_infinite (λb, _), apply (h b).compact_ball end end proper_space namespace metric section second_countable open topological_space /-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin choose T T_dense using H, have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 := λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)), have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n), let t := ⋃n:ℕ, T (n+1)⁻¹ (I n), have count_t : countable t := by finish [countable_Union], have clos_t : closure t = univ, { refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff'.2 (λε εpos, _)), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one), have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this, rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩, have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))), exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ }, haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩, exact emetric.second_countable_of_separable α end /-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin classical, by_cases hs : (univ : set α) = ∅, { haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a metric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, begin classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact H x hx } end⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A compact set is bounded -/ lemma bounded_of_compact {s : set α} (h : compact s) : bounded s := -- We cover the compact set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball alias bounded_of_compact ← compact.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.compact.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.subset (subset_univ _) /-- In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨closed_of_compact _ h, h.bounded⟩, begin rintro ⟨hc, hb⟩, classical, by_cases s = ∅, {simp [h, compact_empty]}, rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ /-- The image of a proper space under an expanding onto map is proper. -/ lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β) (f_cont : continuous f) (hf : range f = univ) (C : ℝ) (hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) (is_closed_ball), have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc dist x y ≤ C * dist (f x) (f y) : hC x y ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg) ... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) : mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _) ... ≤ max C 0 * (r + r) : begin simp only [mem_closed_ball, mem_preimage] at hx hy, exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _) end⟩, have : compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, have C : compact (f '' K) := this.image f_cont, have : f '' K = closed_ball x₀ r, by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ }, rwa this at C end end bounded section diam variables {s : set α} {x y : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := by simp [diam] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_diam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := begin classical, by_cases hs : s = ∅, { simp [hs] }, { rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩, split, { assume bs, rcases (bounded_iff_subset_ball x).1 bs with ⟨r, hr⟩, have r0 : 0 ≤ r := by simpa [closed_ball] using hr hx, have : emetric.diam s < ⊤ := calc emetric.diam s ≤ emetric.diam (emetric.closed_ball x (ennreal.of_real r)) : by rw emetric_closed_ball r0; exact emetric.diam_mono hr ... ≤ 2 * (ennreal.of_real r) : emetric.diam_closed_ball ... < ⊤ : begin apply ennreal.lt_top_iff_ne_top.2, simp [ennreal.mul_eq_top], end, exact ennreal.lt_top_iff_ne_top.1 this }, { assume ds, have : s ⊆ closed_ball x (ennreal.to_real (emetric.diam s)), { rw [← emetric_closed_ball ennreal.to_real_nonneg, ennreal.of_real_to_real ds], exact λy hy, emetric.edist_le_diam_of_mem hy hx }, exact bounded.subset this (bounded_closed_ball) }} end /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := begin simp only [bounded_iff_diam_ne_top, not_not, ne.def] at h, simp [diam, h] end /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded_iff_diam_ne_top.1 (bounded.subset h ht)) (bounded_iff_diam_ne_top.1 ht), exact emetric.diam_mono h end /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) (bounded_iff_diam_ne_top.1 h), exact emetric.edist_le_diam_of_mem hx hy end /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {d : real} (hd : d ≥ 0) (h : ∀x y ∈ s, dist x y ≤ d) : diam s ≤ d := begin have I : emetric.diam s ≤ ennreal.of_real d, { refine emetric.diam_le_of_forall_edist_le (λx y hx hy, _), rw [edist_dist], exact ennreal.of_real_le_of_real (h x y hx hy) }, have A : emetric.diam s ≠ ⊤ := ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt I (ennreal.lt_top_iff_ne_top.2 (by simp))), rw [← ennreal.to_real_of_real hd, diam, ennreal.to_real_le_to_real A], { exact I }, { simp } end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := have I1 : ¬(bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, calc diam (s ∪ t) = 0 + 0 + 0 : by simp [diam_eq_zero_of_unbounded h] ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, have I2 : (bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, begin have : bounded s := bounded.subset (subset_union_left _ _) h, have : bounded t := bounded.subset (subset_union_right _ _) h, have A : ∀a ∈ s, ∀b ∈ t, dist a b ≤ diam s + dist x y + diam t := λa ha b hb, calc dist a b ≤ dist a x + dist x y + dist y b : dist_triangle4 _ _ _ _ ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add (dist_le_diam_of_mem ‹bounded s› ha xs) (le_refl _)) (dist_le_diam_of_mem ‹bounded t› yt hb), have B : ∀a b ∈ s ∪ t, dist a b ≤ diam s + dist x y + diam t := λa b ha hb, begin cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc dist a b ≤ diam s : dist_le_diam_of_mem ‹bounded s› h'a h'b ... = diam s + (0 + 0) : by simp ... ≤ diam s + (dist x y + diam t) : add_le_add (le_refl _) (add_le_add dist_nonneg diam_nonneg) ... = diam s + dist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [dist_comm] at Z }, { calc dist a b ≤ diam t : dist_le_diam_of_mem ‹bounded t› h'a h'b ... = (0 + 0) + diam t : by simp ... ≤ (diam s + dist x y) + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) (le_refl _) } end, have C : 0 ≤ diam s + dist x y + diam t := calc 0 = 0 + 0 + 0 : by simp ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, exact diam_le_of_forall_dist_le C B end, classical.by_cases I2 I1 /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := begin rcases ne_empty_iff_exists_mem.1 h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (by norm_num) h) $ λa b ha hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric
0d96850712a124cefd597016a973f77850a69460
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/limits/seq_limitZeroProd.lean
90e30ab70fc29f552fddc4610901a2f80c11e649
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,353
lean
import game.limits.L01defs import game.limits.seq_limitLinear open real namespace xena -- hide notation `|` x `|` := abs x -- hide /- Use previous results to obtain the limit of a product if individual limits for the factors are both zero. -/ /- Lemma If $\lim_{n \to \infty} a_n = 0$ and $\lim_{n \to \infty} b_n = 0$, then $\lim_{n \to \infty} ( a_n * b_n) = 0$ -/ lemma lim_zero_prod (a : ℕ → ℝ) (b : ℕ → ℝ) (ha : is_limit a 0) (hb : is_limit b 0) : is_limit ( λ n, (a n) * (b n) ) 0 := begin unfold is_limit, intros ε hε, set sε := sqrt ε with hsε, have h1 : 0 < sε, from real.sqrt_pos.mpr hε, have Ha := ha sε h1, have Hb := hb sε h1, cases Ha with Na hNa, cases Hb with Nb hNb, set N := max Na Nb with hN, use N, intros n hn, have Ha := hNa n (le_of_max_le_left hn), have Hb := hNb n (le_of_max_le_right hn), rw sub_zero at *, rw abs_mul, have g1 := mul_lt_mul_of_pos_right Hb h1, have g2 : sε ^ 2 = ε, exact sqr_sqrt( le_of_lt hε), have g3 : sε * sε = sε ^2, ring, rw g3 at g1, rw g2 at g1, rw mul_comm at g1, have hbn : 0 ≤ |b n|, exact is_absolute_value.abv_nonneg abs (b n), have G := mul_le_mul_of_nonneg_right (le_of_lt Ha) hbn, exact lt_of_le_of_lt G g1, -- linarith fails! done end end xena -- hide
b935780b8197cbcfee156a243fdfb933c94cc158
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finite/basic.lean
d38068956d901f82ae63bb3184feaa249da85b9a
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,039
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.fintype.powerset import data.fintype.prod import data.fintype.sigma import data.fintype.sum import data.fintype.vector /-! # Finite types In this file we prove some theorems about `finite` and provide some instances. This typeclass is a `Prop`-valued counterpart of the typeclass `fintype`. See more details in the file where `finite` is defined. ## Main definitions * `fintype.finite`, `finite.of_fintype` creates a `finite` instance from a `fintype` instance. The former lemma takes `fintype α` as an explicit argument while the latter takes it as an instance argument. * `fintype.of_finite` noncomputably creates a `fintype` instance from a `finite` instance. ## Implementation notes There is an apparent duplication of many `fintype` instances in this module, however they follow a pattern: if a `fintype` instance depends on `decidable` instances or other `fintype` instances, then we need to "lower" the instance to be a `finite` instance by removing the `decidable` instances and switching the `fintype` instances to `finite` instances. These are precisely the ones that cannot be inferred using `finite.of_fintype`. (However, when using `open_locale classical` or the `classical` tactic the instances relying only on `decidable` instances will give `finite` instances.) In the future we might consider writing automation to create these "lowered" instances. ## Tags finiteness, finite types -/ noncomputable theory open_locale classical variables {α β γ : Type*} namespace finite @[priority 100] -- see Note [lower instance priority] instance of_subsingleton {α : Sort*} [subsingleton α] : finite α := of_injective (function.const α ()) $ function.injective_of_subsingleton _ @[nolint instance_priority] -- Higher priority for `Prop`s instance prop (p : Prop) : finite p := finite.of_subsingleton instance [finite α] [finite β] : finite (α × β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } instance {α β : Sort*} [finite α] [finite β] : finite (pprod α β) := of_equiv _ equiv.pprod_equiv_prod_plift.symm lemma prod_left (β) [finite (α × β)] [nonempty β] : finite α := of_surjective (prod.fst : α × β → α) prod.fst_surjective lemma prod_right (α) [finite (α × β)] [nonempty α] : finite β := of_surjective (prod.snd : α × β → β) prod.snd_surjective instance [finite α] [finite β] : finite (α ⊕ β) := by { haveI := fintype.of_finite α, haveI := fintype.of_finite β, apply_instance } lemma sum_left (β) [finite (α ⊕ β)] : finite α := of_injective (sum.inl : α → α ⊕ β) sum.inl_injective lemma sum_right (α) [finite (α ⊕ β)] : finite β := of_injective (sum.inr : β → α ⊕ β) sum.inr_injective instance {β : α → Type*} [finite α] [Π a, finite (β a)] : finite (Σ a, β a) := by { letI := fintype.of_finite α, letI := λ a, fintype.of_finite (β a), apply_instance } instance {ι : Sort*} {π : ι → Sort*} [finite ι] [Π i, finite (π i)] : finite (Σ' i, π i) := of_equiv _ (equiv.psigma_equiv_sigma_plift π).symm instance [finite α] : finite (set α) := by { casesI nonempty_fintype α, apply_instance } end finite /-- This instance also provides `[finite s]` for `s : set α`. -/ instance subtype.finite {α : Sort*} [finite α] {p : α → Prop} : finite {x // p x} := finite.of_injective coe subtype.coe_injective instance pi.finite {α : Sort*} {β : α → Sort*} [finite α] [∀ a, finite (β a)] : finite (Π a, β a) := begin haveI := fintype.of_finite (plift α), haveI := λ a, fintype.of_finite (plift (β a)), exact finite.of_equiv (Π (a : plift α), plift (β (equiv.plift a))) (equiv.Pi_congr equiv.plift (λ _, equiv.plift)), end instance vector.finite {α : Type*} [finite α] {n : ℕ} : finite (vector α n) := by { haveI := fintype.of_finite α, apply_instance } instance quot.finite {α : Sort*} [finite α] (r : α → α → Prop) : finite (quot r) := finite.of_surjective _ (surjective_quot_mk r) instance quotient.finite {α : Sort*} [finite α] (s : setoid α) : finite (quotient s) := quot.finite _ instance function.embedding.finite {α β : Sort*} [finite β] : finite (α ↪ β) := begin casesI is_empty_or_nonempty (α ↪ β) with _ h, { apply_instance, }, { refine h.elim (λ f, _), haveI : finite α := finite.of_injective _ f.injective, exact finite.of_injective _ fun_like.coe_injective }, end instance equiv.finite_right {α β : Sort*} [finite β] : finite (α ≃ β) := finite.of_injective equiv.to_embedding $ λ e₁ e₂ h, equiv.ext $ by convert fun_like.congr_fun h instance equiv.finite_left {α β : Sort*} [finite α] : finite (α ≃ β) := finite.of_equiv _ ⟨equiv.symm, equiv.symm, equiv.symm_symm, equiv.symm_symm⟩ instance [finite α] {n : ℕ} : finite (sym α n) := by { haveI := fintype.of_finite α, apply_instance }
c2f07ada0753c3a46fe4812b54e20b6de178a55c
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/tactic29.lean
0f12a64c8a401d023645f07828b21c867841e028
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
323
lean
import standard using tactic section set_option pp.universes true set_option pp.implicit true parameter {A : Type} parameters {a b : A} parameter H : a = b parameters H1 H2 : b = a check H1 check H check H2 theorem test : a = b ∧ a = a := by apply and_intro; apply H; apply refl end check @test
66ec10bce772774af9b7bc0d73320976d9d0ac11
92e157ec9825b5e4597a6d715a8928703bc8e3b2
/src/mywork/practice_2.lean
dc4af590c86680b55b416d5a6004c1184ce63480
[]
no_license
exb3dg/cs2120f21
9e566bc508762573c023d3e70f83cb839c199ec8
319b8bf0d63bf96437bf17970ce0198d0b3525cd
refs/heads/main
1,692,970,909,568
1,634,584,540,000
1,634,584,540,000
399,947,025
0
0
null
null
null
null
UTF-8
Lean
false
false
6,002
lean
/- chameleon exb3dg; https://github.com/exb3dg/cs2120f21.git -/ /- Prove the following simple logical conjectures. Give a formal and an English proof of each one. Your English language proofs should be complete in the sense that they identify all the axioms and/or theorems that you use. -/ /- true as defined in lean is true.intro -/ example : true := true.intro -- no proof because it is false, there can't proofs of it or it would be "true" example : false := _ -- trick question? why? /- Assuming that P ∨ P exists and both P and P exist by the reflective property of if and only if, P ∨ P implies P if and only if P also implies P ∨ P. Meaninng P implies P if and only if P also implies P. -/ example : ∀ (P : Prop), P ∨ P ↔ P := begin assume P : Prop, apply iff.intro _ _, -- forward direction assume porp, apply or.elim porp, -- left disjunct Is true assume p, exact p, -- right disjunct is true assume p, exact p, -- backward direction assume p, exact or.intro_right P p, end /- Assuming that P ∧ P and P exist by the reflective property of if and only if, P ∧ P implies P if and only if P also implies P ∧ P. -/ example : ∀ (P : Prop), P ∧ P ↔ P := begin assume P : Prop, apply iff.intro _ _, assume pandp, apply and.elim_left pandp, assume p, apply and.intro p p, end /- Assuming that P ∨ Q and P and Q exist by the reflective property of if and only if, P ∨ Q implies Q ∨ P if and only if Q ∨ P also implies P ∨ Q. -/ example : ∀ (P Q : Prop), P ∨ Q ↔ Q ∨ P := begin assume P Q : Prop, apply iff.intro _ _, assume porq, apply or.elim porq, assume p, apply or.swap porq, assume q, apply or.symm porq, assume qorp, apply or.symm qorp, end /- Assuming that P ∧ Q and P and Q exist by the reflective property of if and only if, P ∧ Q implies Q ∧ P if and only if Q ∧ P also implies P ∧ Q. -/ example : ∀ (P Q : Prop), P ∧ Q ↔ Q ∧ P := begin assume P Q : Prop, apply iff.intro _ _, assume pandq, apply and.elim pandq, assume p q, apply and.symm pandq, assume qandp, apply and.symm qandp, end /- Assuming that P ∧ (Q ∨ P) and P, Q, R exist by the distributive property of ∧ P ∧ (Q ∨ R) = (P ∧ Q) ∨ (P ∧ R). By the reflective property of if and only if P ∧ (Q ∨ R) implies (P ∧ Q) ∨ (P ∧ R) only if (P ∧ Q) ∨ (P ∧ R) also implies P P ∧ (Q ∨ R) -/ example : ∀ (P Q R : Prop), P ∧ (Q ∨ R) ↔ (P ∧ Q) ∨ (P ∧ R) := begin assume P Q R : Prop, apply iff.intro _ _, assume Pqr, apply and.elim Pqr, assume p qorr, apply or.intro_right, --apply or.elim qorr, --assume q, --apply and.intro p, --***incomplete*** end /- Assuming that P ∨ (Q ∧ R) and P, Q, R exist by the distributive property of ∨ P ∨ (Q ∧ R) = (P ∨ Q) ∧ (P ∨ R). By the reflective property of if and only if P ∨ (Q ∧ R) implies (P ∨ Q) ∧ (P ∨ R), (P ∨ Q) ∧ (P ∨ R) also implies P ∨ (Q ∧ R) -/ example : ∀ (P Q R : Prop), P ∨ (Q ∧ R) ↔ (P ∨ Q) ∧ (P ∨ R) := begin assume P Q R, apply iff.intro _ _, assume Pqr, apply or.elim Pqr, assume p, apply or.elim (or.swap Pqr), assume qandr, apply and.elim qandr, assume q r, sorry, assume p, sorry, sorry, sorry, end /- Assuming that P ∧ (P ∨ Q) and P and Q exist by the reflective property of if and only if P ∧ (P ∨ Q) implies P, P also implies P ∧ (P ∨ Q) -/ example : ∀ (P Q : Prop), P ∧ (P ∨ Q) ↔ P := begin assume P Q : Prop, apply iff.intro _ _, assume Ppq, apply and.elim Ppq, assume p, assume porq, apply or.elim porq, assume p, apply and.elim_left Ppq, assume q, exact p, assume p, apply and.intro p, apply or.intro_left, exact p, end /- Assuming that P ∨ (P ∧ Q) and P and Q exist by the reflective property of if and only if P ∨ (P ∧ Q) implies P, P also implies P ∨ (P ∧ Q) -/ example : ∀ (P Q : Prop), P ∨ (P ∧ Q) ↔ P := begin assume P Q, apply iff.intro _ _, assume Ppq, apply or.elim Ppq, assume p, exact p, assume pandq, apply and.elim_left pandq, assume p, apply or.intro_left, exact p, end /- Assuming that P ∨ true and P and true exist by the reflective property of if and only if P ∨ true implies true then true must also implie P ∨ true -/ example : ∀ (P : Prop), P ∨ true ↔ true := begin assume P, apply iff.intro _ _, assume port, apply or.elim port, assume p, exact true.intro, assume t, exact true.intro, assume t, exact or.intro_right P t, end /- Assuming that P ∨ false and P and false exist by the reflective property of if and only if P ∨ false implies P then P must also implies P ∨ false -/ example : ∀ (P : Prop), P ∨ false ↔ P := begin assume P, apply iff.intro _ _, assume porf, apply or.elim porf, assume p, exact p, assume f, exact false.elim f, assume P, apply or.intro_left, exact P, end /- Assuming that P ∧ true and P and true exist by the reflective property of if and only if P ∧ true implies P then P must also implies P ∧ true -/ example : ∀ (P : Prop), P ∧ true ↔ P := begin assume P, apply iff.intro _ _, assume pandt, apply and.elim pandt, assume p, assume t, exact p, assume P, apply and.intro P true.intro, end /- Assuming that P ∧ false and P and false exist by the reflective property of if and only if P ∧ false implies false then false must also implies P ∧ false -/ example : ∀ (P : Prop), P ∧ false ↔ false := begin assume P : Prop, apply iff.intro _ _, assume pandf, apply and.elim pandf, assume p, assume f, exact f, assume f, apply and.intro, exact false.elim f, exact f, end
6e9036f4ac94eb304c8484a63cdeae7c01be7cc3
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/ty2.lean
da1d2c0073643856631fd1b6ca28288c0232d2d9
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
121
lean
definition B : Type := Bool definition T : (Type 1) := Type variable N : T variable x : N variable a : B axiom H : a
8dee143116f323b53fb06991a01cef84d46974cc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/locally_constant/algebra.lean
007c2f047bd8bc3a6105d92d8bd255eaefe78977
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,594
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.algebra.pi import topology.locally_constant.basic /-! # Algebraic structure on locally constant functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file puts algebraic structure (`add_group`, etc) on the type of locally constant functions. -/ namespace locally_constant variables {X Y : Type*} [topological_space X] @[to_additive] instance [has_one Y] : has_one (locally_constant X Y) := { one := const X 1 } @[simp, to_additive] lemma coe_one [has_one Y] : ⇑(1 : locally_constant X Y) = (1 : X → Y) := rfl @[to_additive] lemma one_apply [has_one Y] (x : X) : (1 : locally_constant X Y) x = 1 := rfl @[to_additive] instance [has_inv Y] : has_inv (locally_constant X Y) := { inv := λ f, ⟨f⁻¹ , f.is_locally_constant.inv⟩ } @[simp, to_additive] lemma coe_inv [has_inv Y] (f : locally_constant X Y) : ⇑(f⁻¹) = f⁻¹ := rfl @[to_additive] lemma inv_apply [has_inv Y] (f : locally_constant X Y) (x : X) : f⁻¹ x = (f x)⁻¹ := rfl @[to_additive] instance [has_mul Y] : has_mul (locally_constant X Y) := { mul := λ f g, ⟨f * g, f.is_locally_constant.mul g.is_locally_constant⟩ } @[simp, to_additive] lemma coe_mul [has_mul Y] (f g : locally_constant X Y) : ⇑(f * g) = f * g := rfl @[to_additive] lemma mul_apply [has_mul Y] (f g : locally_constant X Y) (x : X) : (f * g) x = f x * g x := rfl @[to_additive] instance [mul_one_class Y] : mul_one_class (locally_constant X Y) := { one_mul := by { intros, ext, simp only [mul_apply, one_apply, one_mul] }, mul_one := by { intros, ext, simp only [mul_apply, one_apply, mul_one] }, .. locally_constant.has_one, .. locally_constant.has_mul } /-- `coe_fn` is a `monoid_hom`. -/ @[to_additive "`coe_fn` is an `add_monoid_hom`.", simps] def coe_fn_monoid_hom [mul_one_class Y] : locally_constant X Y →* (X → Y) := { to_fun := coe_fn, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The constant-function embedding, as a multiplicative monoid hom. -/ @[to_additive "The constant-function embedding, as an additive monoid hom.", simps] def const_monoid_hom [mul_one_class Y] : Y →* locally_constant X Y := { to_fun := const X, map_one' := rfl, map_mul' := λ _ _, rfl, } instance [mul_zero_class Y] : mul_zero_class (locally_constant X Y) := { zero_mul := by { intros, ext, simp only [mul_apply, zero_apply, zero_mul] }, mul_zero := by { intros, ext, simp only [mul_apply, zero_apply, mul_zero] }, .. locally_constant.has_zero, .. locally_constant.has_mul } instance [mul_zero_one_class Y] : mul_zero_one_class (locally_constant X Y) := { .. locally_constant.mul_zero_class, .. locally_constant.mul_one_class } section char_fn variables (Y) [mul_zero_one_class Y] {U V : set X} /-- Characteristic functions are locally constant functions taking `x : X` to `1` if `x ∈ U`, where `U` is a clopen set, and `0` otherwise. -/ noncomputable def char_fn (hU : is_clopen U) : locally_constant X Y := indicator 1 hU lemma coe_char_fn (hU : is_clopen U) : (char_fn Y hU : X → Y) = set.indicator U 1 := rfl lemma char_fn_eq_one [nontrivial Y] (x : X) (hU : is_clopen U) : char_fn Y hU x = (1 : Y) ↔ x ∈ U := set.indicator_eq_one_iff_mem _ lemma char_fn_eq_zero [nontrivial Y] (x : X) (hU : is_clopen U) : char_fn Y hU x = (0 : Y) ↔ x ∉ U := set.indicator_eq_zero_iff_not_mem _ lemma char_fn_inj [nontrivial Y] (hU : is_clopen U) (hV : is_clopen V) (h : char_fn Y hU = char_fn Y hV) : U = V := set.indicator_one_inj Y $ coe_inj.mpr h end char_fn @[to_additive] instance [has_div Y] : has_div (locally_constant X Y) := { div := λ f g, ⟨f / g, f.is_locally_constant.div g.is_locally_constant⟩ } @[to_additive] lemma coe_div [has_div Y] (f g : locally_constant X Y) : ⇑(f / g) = f / g := rfl @[to_additive] lemma div_apply [has_div Y] (f g : locally_constant X Y) (x : X) : (f / g) x = f x / g x := rfl @[to_additive] instance [semigroup Y] : semigroup (locally_constant X Y) := { mul_assoc := by { intros, ext, simp only [mul_apply, mul_assoc] }, .. locally_constant.has_mul } instance [semigroup_with_zero Y] : semigroup_with_zero (locally_constant X Y) := { .. locally_constant.mul_zero_class, .. locally_constant.semigroup } @[to_additive] instance [comm_semigroup Y] : comm_semigroup (locally_constant X Y) := { mul_comm := by { intros, ext, simp only [mul_apply, mul_comm] }, .. locally_constant.semigroup } @[to_additive] instance [monoid Y] : monoid (locally_constant X Y) := { mul := (*), .. locally_constant.semigroup, .. locally_constant.mul_one_class } instance [add_monoid_with_one Y] : add_monoid_with_one (locally_constant X Y) := { nat_cast := λ n, const X n, nat_cast_zero := by ext; simp [nat.cast], nat_cast_succ := λ _, by ext; simp [nat.cast], .. locally_constant.add_monoid, .. locally_constant.has_one } @[to_additive] instance [comm_monoid Y] : comm_monoid (locally_constant X Y) := { .. locally_constant.comm_semigroup, .. locally_constant.monoid } @[to_additive] instance [group Y] : group (locally_constant X Y) := { mul_left_inv := by { intros, ext, simp only [mul_apply, inv_apply, one_apply, mul_left_inv] }, div_eq_mul_inv := by { intros, ext, simp only [mul_apply, inv_apply, div_apply, div_eq_mul_inv] }, .. locally_constant.monoid, .. locally_constant.has_inv, .. locally_constant.has_div } @[to_additive] instance [comm_group Y] : comm_group (locally_constant X Y) := { .. locally_constant.comm_monoid, .. locally_constant.group } instance [distrib Y] : distrib (locally_constant X Y) := { left_distrib := by { intros, ext, simp only [mul_apply, add_apply, mul_add] }, right_distrib := by { intros, ext, simp only [mul_apply, add_apply, add_mul] }, .. locally_constant.has_add, .. locally_constant.has_mul } instance [non_unital_non_assoc_semiring Y] : non_unital_non_assoc_semiring (locally_constant X Y) := { .. locally_constant.add_comm_monoid, .. locally_constant.has_mul, .. locally_constant.distrib, .. locally_constant.mul_zero_class } instance [non_unital_semiring Y] : non_unital_semiring (locally_constant X Y) := { .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_semiring } instance [non_assoc_semiring Y] : non_assoc_semiring (locally_constant X Y) := { .. locally_constant.mul_one_class, .. locally_constant.add_monoid_with_one, .. locally_constant.non_unital_non_assoc_semiring } /-- The constant-function embedding, as a ring hom. -/ @[simps] def const_ring_hom [non_assoc_semiring Y] : Y →+* locally_constant X Y := { to_fun := const X, .. const_monoid_hom, .. const_add_monoid_hom, } instance [semiring Y] : semiring (locally_constant X Y) := { .. locally_constant.non_assoc_semiring, .. locally_constant.monoid } instance [non_unital_comm_semiring Y] : non_unital_comm_semiring (locally_constant X Y) := { .. locally_constant.non_unital_semiring, .. locally_constant.comm_semigroup } instance [comm_semiring Y] : comm_semiring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.comm_monoid } instance [non_unital_non_assoc_ring Y] : non_unital_non_assoc_ring (locally_constant X Y) := { .. locally_constant.add_comm_group, .. locally_constant.has_mul, .. locally_constant.distrib, .. locally_constant.mul_zero_class } instance [non_unital_ring Y] : non_unital_ring (locally_constant X Y) := { .. locally_constant.semigroup, .. locally_constant.non_unital_non_assoc_ring } instance [non_assoc_ring Y] : non_assoc_ring (locally_constant X Y) := { .. locally_constant.mul_one_class, .. locally_constant.non_unital_non_assoc_ring } instance [ring Y] : ring (locally_constant X Y) := { .. locally_constant.semiring, .. locally_constant.add_comm_group } instance [non_unital_comm_ring Y] : non_unital_comm_ring (locally_constant X Y) := { .. locally_constant.non_unital_comm_semiring, .. locally_constant.non_unital_ring } instance [comm_ring Y] : comm_ring (locally_constant X Y) := { .. locally_constant.comm_semiring, .. locally_constant.ring } variables {R : Type*} instance [has_smul R Y] : has_smul R (locally_constant X Y) := { smul := λ r f, { to_fun := r • f, is_locally_constant := (f.is_locally_constant.comp ((•) r) : _), } } @[simp] lemma coe_smul [has_smul R Y] (r : R) (f : locally_constant X Y) : ⇑(r • f) = r • f := rfl lemma smul_apply [has_smul R Y] (r : R) (f : locally_constant X Y) (x : X) : (r • f) x = r • (f x) := rfl instance [monoid R] [mul_action R Y] : mul_action R (locally_constant X Y) := function.injective.mul_action _ coe_injective (λ _ _, rfl) instance [monoid R] [add_monoid Y] [distrib_mul_action R Y] : distrib_mul_action R (locally_constant X Y) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective (λ _ _, rfl) instance [semiring R] [add_comm_monoid Y] [module R Y] : module R (locally_constant X Y) := function.injective.module R coe_fn_add_monoid_hom coe_injective (λ _ _, rfl) section algebra variables [comm_semiring R] [semiring Y] [algebra R Y] instance : algebra R (locally_constant X Y) := { to_ring_hom := const_ring_hom.comp $ algebra_map R Y, commutes' := by { intros, ext, exact algebra.commutes' _ _, }, smul_def' := by { intros, ext, exact algebra.smul_def' _ _, }, } @[simp] lemma coe_algebra_map (r : R) : ⇑(algebra_map R (locally_constant X Y) r) = algebra_map R (X → Y) r := rfl end algebra end locally_constant
a5ae56b0a7548c70ed309814e40402e4120f7ebc
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/init/logic.hlean
bd1d19d3caadbf73cdcb0a79c6b5edfff6d26e98
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
24,230
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Floris van Doorn -/ prelude import init.reserved_notation open unit definition id [reducible] [unfold_full] {A : Type} (a : A) : A := a /- not -/ definition not [reducible] (a : Type) := a → empty prefix ¬ := not definition absurd {a b : Type} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) definition mt {a b : Type} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ definition not_empty : ¬empty := assume H : empty, H definition non_contradictory (a : Type) : Type := ¬¬a definition non_contradictory_intro {a : Type} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna definition not.intro {a : Type} (H : a → empty) : ¬a := H /- empty -/ definition empty.elim {c : Type} (H : empty) : c := empty.rec _ H /- eq -/ infix = := eq definition rfl {A : Type} {a : A} := eq.refl a /- These notions are here only to make porting from the standard library easier. They are defined again in init/path.hlean, and those definitions will be used throughout the HoTT-library. That's why the notation for eq below is only local. -/ namespace eq variables {A : Type} {a b c : A} definition subst [unfold 5] {P : A → Type} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ definition trans [unfold 5] (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm [unfold 4] (H : a = b) : b = a := subst H (refl a) definition mp {a b : Type} : (a = b) → a → b := eq.rec_on definition mpr {a b : Type} : (a = b) → b → a := assume H₁ H₂, eq.rec_on (eq.symm H₁) H₂ namespace ops end ops -- this is just to ensure that this namespace exists. There is nothing in it end eq local postfix ⁻¹ := eq.symm --input with \sy or \-1 or \inv local infixl ⬝ := eq.trans local infixr ▸ := eq.subst -- Auxiliary definition used by automation. It has the same type of eq.rec in the standard library definition eq.nrec.{l₁ l₂} {A : Type.{l₂}} {a : A} {C : A → Type.{l₁}} (H₁ : C a) (b : A) (H₂ : a = b) : C b := eq.rec H₁ H₂ definition congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst H₁ (eq.subst H₂ rfl) definition congr_fun {A : Type} {B : A → Type} {f g : Π x, B x} (H : f = g) (a : A) : f a = g a := eq.subst H (eq.refl (f a)) definition congr_arg {A B : Type} (a a' : A) (f : A → B) (Ha : a = a') : f a = f a' := eq.subst Ha rfl definition congr_arg2 {A B C : Type} (a a' : A) (b b' : B) (f : A → B → C) (Ha : a = a') (Hb : b = b') : f a b = f a' b' := eq.subst Ha (eq.subst Hb rfl) section variables {A : Type} {a b c: A} open eq.ops definition trans_rel_left (R : A → A → Type) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ definition trans_rel_right (R : A → A → Type) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] namespace lift definition down_up.{l₁ l₂} {A : Type.{l₁}} (a : A) : down (up.{l₁ l₂} a) = a := rfl definition up_down.{l₁ l₂} {A : Type.{l₁}} (a : lift.{l₁ l₂} A) : up (down a) = a := lift.rec_on a (λ d, rfl) end lift /- ne -/ definition ne [reducible] {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} definition intro (H : a = b → empty) : a ≠ b := H definition elim (H : a ≠ b) : a = b → empty := H definition irrefl (H : a ≠ a) : empty := H rfl definition symm (H : a ≠ b) : b ≠ a := assume (H₁ : b = a), H (H₁⁻¹) end ne definition empty_of_ne {A : Type} {a : A} : a ≠ a → empty := ne.irrefl section open eq.ops variables {p : Type₀} definition ne_empty_of_self : p → p ≠ empty := assume (Hp : p) (Heq : p = empty), Heq ▸ Hp definition ne_unit_of_not : ¬p → p ≠ unit := assume (Hnp : ¬p) (Heq : p = unit), (Heq ▸ Hnp) star definition unit_ne_empty : ¬unit = empty := ne_empty_of_self star end /- prod -/ abbreviation pair [constructor] := @prod.mk infixr × := prod variables {a b c d : Type} attribute prod.rec [elim] attribute prod.mk [intro!] protected definition prod.elim [unfold 4] (H₁ : a × b) (H₂ : a → b → c) : c := prod.rec H₂ H₁ definition prod.swap [unfold 3] : a × b → b × a := prod.rec (λHa Hb, prod.mk Hb Ha) /- sum -/ infixr ⊎ := sum infixr + := sum attribute sum.rec [elim] protected definition sum.elim [unfold 4] (H₁ : a ⊎ b) (H₂ : a → c) (H₃ : b → c) : c := sum.rec H₂ H₃ H₁ definition non_contradictory_em (a : Type) : ¬¬(a ⊎ ¬a) := assume not_em : ¬(a ⊎ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (sum.inl pos_a) not_em, absurd (sum.inr neg_a) not_em definition sum.swap : a ⊎ b → b ⊎ a := sum.rec sum.inr sum.inl /- iff -/ definition iff (a b : Type) := (a → b) × (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b definition iff.intro : (a → b) → (b → a) → (a ↔ b) := prod.mk attribute iff.intro [intro!] definition iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := prod.rec attribute iff.elim [recursor 5] [elim] definition iff.elim_left : (a ↔ b) → a → b := prod.pr1 definition iff.mp := @iff.elim_left definition iff.elim_right : (a ↔ b) → b → a := prod.pr2 definition iff.mpr := @iff.elim_right definition iff.refl [refl] (a : Type) : a ↔ a := iff.intro (assume H, H) (assume H, H) definition iff.rfl {a : Type} : a ↔ a := iff.refl a definition iff.trans [trans] (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := iff.intro (assume Ha, iff.mp H₂ (iff.mp H₁ Ha)) (assume Hc, iff.mpr H₁ (iff.mpr H₂ Hc)) definition iff.symm [symm] (H : a ↔ b) : b ↔ a := iff.intro (iff.elim_right H) (iff.elim_left H) definition iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm definition iff.of_eq {a b : Type} (H : a = b) : a ↔ b := eq.rec_on H iff.rfl definition not_iff_not_of_iff (H₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (Hna : ¬ a) (Hb : b), Hna (iff.elim_right H₁ Hb)) (assume (Hnb : ¬ b) (Ha : a), Hnb (iff.elim_left H₁ Ha)) definition of_iff_unit (H : a ↔ unit) : a := iff.mp (iff.symm H) star definition not_of_iff_empty : (a ↔ empty) → ¬a := iff.mp definition iff_unit_intro (H : a) : a ↔ unit := iff.intro (λ Hl, star) (λ Hr, H) definition iff_empty_intro (H : ¬a) : a ↔ empty := iff.intro H (empty.rec _) definition not_non_contradictory_iff_absurd (a : Type) : ¬¬¬a ↔ ¬a := iff.intro (λ (Hl : ¬¬¬a) (Ha : a), Hl (non_contradictory_intro Ha)) absurd definition imp_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λHab Hc, iff.mp H2 (Hab (iff.mpr H1 Hc))) (λHcd Ha, iff.mpr H2 (Hcd (iff.mp H1 Ha))) definition not_not_intro (Ha : a) : ¬¬a := assume Hna : ¬a, Hna Ha definition not_of_not_not_not (H : ¬¬¬a) : ¬a := λ Ha, absurd (not_not_intro Ha) H definition not_unit [simp] : (¬ unit) ↔ empty := iff_empty_intro (not_not_intro star) definition not_empty_iff [simp] : (¬ empty) ↔ unit := iff_unit_intro not_empty definition not_congr (H : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ H₁ H₂, H₁ (iff.mpr H H₂)) (λ H₁ H₂, H₁ (iff.mp H H₂)) definition ne_self_iff_empty [simp] {A : Type} (a : A) : (not (a = a)) ↔ empty := iff.intro empty_of_ne empty.elim definition eq_self_iff_unit [simp] {A : Type} (a : A) : (a = a) ↔ unit := iff_unit_intro rfl definition iff_not_self [simp] (a : Type) : (a ↔ ¬a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mp H Ha) Ha), H' (iff.mpr H H')) definition not_iff_self [simp] (a : Type) : (¬a ↔ a) ↔ empty := iff_empty_intro (λ H, have H' : ¬a, from (λ Ha, (iff.mpr H Ha) Ha), H' (iff.mp H H')) definition unit_iff_empty [simp] : (unit ↔ empty) ↔ empty := iff_empty_intro (λ H, iff.mp H star) definition empty_iff_unit [simp] : (empty ↔ unit) ↔ empty := iff_empty_intro (λ H, iff.mpr H star) definition empty_of_unit_iff_empty : (unit ↔ empty) → empty := assume H, iff.mp H star /- prod simp rules -/ definition prod.imp (H₂ : a → c) (H₃ : b → d) : a × b → c × d := prod.rec (λHa Hb, prod.mk (H₂ Ha) (H₃ Hb)) definition prod_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a × b) ↔ (c × d) := iff.intro (prod.imp (iff.mp H1) (iff.mp H2)) (prod.imp (iff.mpr H1) (iff.mpr H2)) definition prod.comm [simp] : a × b ↔ b × a := iff.intro prod.swap prod.swap definition prod.assoc [simp] : (a × b) × c ↔ a × (b × c) := iff.intro (prod.rec (λ H' Hc, prod.rec (λ Ha Hb, prod.mk Ha (prod.mk Hb Hc)) H')) (prod.rec (λ Ha, prod.rec (λ Hb Hc, prod.mk (prod.mk Ha Hb) Hc))) definition prod.pr1_comm [simp] : a × (b × c) ↔ b × (a × c) := iff.trans (iff.symm !prod.assoc) (iff.trans (prod_congr !prod.comm !iff.refl) !prod.assoc) definition prod_iff_left {a b : Type} (Hb : b) : (a × b) ↔ a := iff.intro prod.pr1 (λHa, prod.mk Ha Hb) definition prod_iff_right {a b : Type} (Ha : a) : (a × b) ↔ b := iff.intro prod.pr2 (prod.mk Ha) definition prod_unit [simp] (a : Type) : a × unit ↔ a := prod_iff_left star definition unit_prod [simp] (a : Type) : unit × a ↔ a := prod_iff_right star definition prod_empty [simp] (a : Type) : a × empty ↔ empty := iff_empty_intro prod.pr2 definition empty_prod [simp] (a : Type) : empty × a ↔ empty := iff_empty_intro prod.pr1 definition not_prod_self [simp] (a : Type) : (¬a × a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₂ H₁)) definition prod_not_self [simp] (a : Type) : (a × ¬a) ↔ empty := iff_empty_intro (λ H, prod.elim H (λ H₁ H₂, absurd H₁ H₂)) definition prod_self [simp] (a : Type) : a × a ↔ a := iff.intro prod.pr1 (assume H, prod.mk H H) /- sum simp rules -/ definition sum.imp (H₂ : a → c) (H₃ : b → d) : a ⊎ b → c ⊎ d := sum.rec (λ H, sum.inl (H₂ H)) (λ H, sum.inr (H₃ H)) definition sum.imp_left (H : a → b) : a ⊎ c → b ⊎ c := sum.imp H id definition sum.imp_right (H : a → b) : c ⊎ a → c ⊎ b := sum.imp id H definition sum_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ⊎ b) ↔ (c ⊎ d) := iff.intro (sum.imp (iff.mp H1) (iff.mp H2)) (sum.imp (iff.mpr H1) (iff.mpr H2)) definition sum.comm [simp] : a ⊎ b ↔ b ⊎ a := iff.intro sum.swap sum.swap definition sum.assoc [simp] : (a ⊎ b) ⊎ c ↔ a ⊎ (b ⊎ c) := iff.intro (sum.rec (sum.imp_right sum.inl) (λ H, sum.inr (sum.inr H))) (sum.rec (λ H, sum.inl (sum.inl H)) (sum.imp_left sum.inr)) definition sum.left_comm [simp] : a ⊎ (b ⊎ c) ↔ b ⊎ (a ⊎ c) := iff.trans (iff.symm !sum.assoc) (iff.trans (sum_congr !sum.comm !iff.refl) !sum.assoc) definition sum_unit [simp] (a : Type) : a ⊎ unit ↔ unit := iff_unit_intro (sum.inr star) definition unit_sum [simp] (a : Type) : unit ⊎ a ↔ unit := iff_unit_intro (sum.inl star) definition sum_empty [simp] (a : Type) : a ⊎ empty ↔ a := iff.intro (sum.rec id empty.elim) sum.inl definition empty_sum [simp] (a : Type) : empty ⊎ a ↔ a := iff.trans sum.comm !sum_empty definition sum_self [simp] (a : Type) : a ⊎ a ↔ a := iff.intro (sum.rec id id) sum.inl /- sum resolution rulse -/ definition sum.resolve_left {a b : Type} (H : a ⊎ b) (na : ¬ a) : b := sum.elim H (λ Ha, absurd Ha na) id definition sum.neg_resolve_left {a b : Type} (H : ¬ a ⊎ b) (Ha : a) : b := sum.elim H (λ na, absurd Ha na) id definition sum.resolve_right {a b : Type} (H : a ⊎ b) (nb : ¬ b) : a := sum.elim H id (λ Hb, absurd Hb nb) definition sum.neg_resolve_right {a b : Type} (H : a ⊎ ¬ b) (Hb : b) : a := sum.elim H id (λ nb, absurd Hb nb) /- iff simp rules -/ definition iff_unit [simp] (a : Type) : (a ↔ unit) ↔ a := iff.intro (assume H, iff.mpr H star) iff_unit_intro definition unit_iff [simp] (a : Type) : (unit ↔ a) ↔ a := iff.trans iff.comm !iff_unit definition iff_empty [simp] (a : Type) : (a ↔ empty) ↔ ¬ a := iff.intro prod.pr1 iff_empty_intro definition empty_iff [simp] (a : Type) : (empty ↔ a) ↔ ¬ a := iff.trans iff.comm !iff_empty definition iff_self [simp] (a : Type) : (a ↔ a) ↔ unit := iff_unit_intro iff.rfl definition iff_congr [congr] (H1 : a ↔ c) (H2 : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := prod_congr (imp_congr H1 H2) (imp_congr H2 H1) /- decidable -/ inductive decidable [class] (p : Type) : Type := | inl : p → decidable p | inr : ¬p → decidable p definition decidable_unit [instance] : decidable unit := decidable.inl star definition decidable_empty [instance] : decidable empty := decidable.inr not_empty -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Type) [H : decidable c] {A : Type} : (c → A) → (¬ c → A) → A := decidable.rec_on H /- if-then-else -/ definition ite (c : Type) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) namespace decidable variables {p q : Type} definition by_cases {q : Type} [C : decidable p] : (p → q) → (¬p → q) → q := !dite theorem em (p : Type) [H : decidable p] : p ⊎ ¬p := by_cases sum.inl sum.inr theorem by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := if H1 : p then H1 else empty.rec _ (H H1) end decidable section variables {p q : Type} open decidable definition decidable_of_decidable_of_iff (Hp : decidable p) (H : p ↔ q) : decidable q := if Hp : p then inl (iff.mp H Hp) else inr (iff.mp (not_iff_not_of_iff H) Hp) definition decidable_of_decidable_of_eq {p q : Type} (Hp : decidable p) (H : p = q) : decidable q := decidable_of_decidable_of_iff Hp (iff.of_eq H) protected definition sum.by_cases [Hp : decidable p] [Hq : decidable q] {A : Type} (h : p ⊎ q) (h₁ : p → A) (h₂ : q → A) : A := if hp : p then h₁ hp else if hq : q then h₂ hq else empty.rec _ (sum.elim h hp hq) end section variables {p q : Type} open decidable (rec_on inl inr) definition decidable_prod [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p × q) := if hp : p then if hq : q then inl (prod.mk hp hq) else inr (assume H : p × q, hq (prod.pr2 H)) else inr (assume H : p × q, hp (prod.pr1 H)) definition decidable_sum [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ⊎ q) := if hp : p then inl (sum.inl hp) else if hq : q then inl (sum.inr hq) else inr (sum.rec hp hq) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := if hp : p then inr (absurd hp) else inl hp definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := if hp : p then if hq : q then inl (assume H, hq) else inr (assume H : p → q, absurd (H hp) hq) else inl (assume Hp, absurd Hp hp) definition decidable_iff [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := decidable_prod end definition decidable_pred [reducible] {A : Type} (R : A → Type) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Type) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] (a b : A) : decidable (a ≠ b) := decidable_implies namespace bool theorem ff_ne_tt : ff = tt → empty | [none] end bool open bool definition is_dec_eq {A : Type} (p : A → A → bool) : Type := Π ⦃x y : A⦄, p x y = tt → x = y definition is_dec_refl {A : Type} (p : A → A → bool) : Type := Πx, p x x = tt open decidable protected definition bool.has_decidable_eq [instance] : Πa b : bool, decidable (a = b) | ff ff := inl rfl | ff tt := inr ff_ne_tt | tt ff := inr (ne.symm ff_ne_tt) | tt tt := inl rfl definition decidable_eq_of_bool_pred {A : Type} {p : A → A → bool} (H₁ : is_dec_eq p) (H₂ : is_dec_refl p) : decidable_eq A := take x y : A, if Hp : p x y = tt then inl (H₁ Hp) else inr (assume Hxy : x = y, (eq.subst Hxy Hp) (H₂ y)) /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A protected definition inhabited.value {A : Type} : inhabited A → A := inhabited.rec (λa, a) protected definition inhabited.destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition default (A : Type) [H : inhabited A] : A := inhabited.value H definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A := inhabited.value H definition Type.is_inhabited [instance] : inhabited Type := inhabited.mk (lift unit) definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.rec_on H (λb, inhabited.mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := inhabited.mk (λa, !default) protected definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk ff protected definition pos_num.is_inhabited [instance] : inhabited pos_num := inhabited.mk pos_num.one protected definition num.is_inhabited [instance] : inhabited num := inhabited.mk num.zero inductive nonempty [class] (A : Type) : Type := intro : A → nonempty A protected definition nonempty.elim {A : Type} {B : Type} (H1 : nonempty A) (H2 : A → B) : B := nonempty.rec H2 H1 theorem nonempty_of_inhabited [instance] {A : Type} [H : inhabited A] : nonempty A := nonempty.intro !default theorem nonempty_of_exists {A : Type} {P : A → Type} : (sigma P) → nonempty A := sigma.rec (λw H, nonempty.intro w) /- subsingleton -/ inductive subsingleton [class] (A : Type) : Type := intro : (Π a b : A, a = b) → subsingleton A protected definition subsingleton.elim {A : Type} [H : subsingleton A] : Π(a b : A), a = b := subsingleton.rec (λp, p) H protected theorem rec_subsingleton {p : Type} [H : decidable p] {H1 : p → Type} {H2 : ¬p → Type} [H3 : Π(h : p), subsingleton (H1 h)] [H4 : Π(h : ¬p), subsingleton (H2 h)] : subsingleton (decidable.rec_on H H1 H2) := decidable.rec_on H (λh, H3 h) (λh, H4 h) --this can be proven using dependent version of "by_cases" theorem if_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (ite c t e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H theorem if_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (ite c t e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H theorem if_t_t [simp] (c : Type) [H : decidable c] {A : Type} (t : A) : (ite c t t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H theorem implies_of_if_pos {c t e : Type} [H : decidable c] (h : ite c t e) : c → t := assume Hc, eq.rec_on (if_pos Hc) h theorem implies_of_if_neg {c t e : Type} [H : decidable c] (h : ite c t e) : ¬c → e := assume Hnc, eq.rec_on (if_neg Hnc) h theorem if_ctx_congr {A : Type} {b c : Type} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y = x : if_pos hp ... = u : h_t (iff.mp h_c hp) ... = ite c u v : if_pos (iff.mp h_c hp)) (λ hn : ¬b, calc ite b x y = y : if_neg hn ... = v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... = ite c u v : if_neg (iff.mp (not_iff_not_of_iff h_c) hn)) theorem if_congr [congr] {A : Type} {b c : Type} [dec_b : decidable b] [dec_c : decidable c] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr A b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr {A : Type} {b c : Type} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_congr A b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e theorem if_simp_congr [congr] {A : Type} {b c : Type} [dec_b : decidable b] {x y u v : A} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) A u v) := @if_ctx_simp_congr A b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) definition if_unit [simp] {A : Type} (t e : A) : (if unit then t else e) = t := if_pos star definition if_empty [simp] {A : Type} (t e : A) : (if empty then t else e) = e := if_neg not_empty theorem if_ctx_congr_prop {b c x y u v : Type} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := decidable.rec_on dec_b (λ hp : b, calc ite b x y ↔ x : iff.of_eq (if_pos hp) ... ↔ u : h_t (iff.mp h_c hp) ... ↔ ite c u v : iff.of_eq (if_pos (iff.mp h_c hp))) (λ hn : ¬b, calc ite b x y ↔ y : iff.of_eq (if_neg hn) ... ↔ v : h_e (iff.mp (not_iff_not_of_iff h_c) hn) ... ↔ ite c u v : iff.of_eq (if_neg (iff.mp (not_iff_not_of_iff h_c) hn))) theorem if_congr_prop [congr] {b c x y u v : Type} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) theorem if_ctx_simp_congr_prop {b c x y u v : Type} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Type u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e theorem if_simp_congr_prop [congr] {b c x y u v : Type} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Type u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. theorem dite_ite_eq (c : Type) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl definition is_unit (c : Type) [H : decidable c] : Type₀ := if c then unit else empty definition is_empty (c : Type) [H : decidable c] : Type₀ := if c then empty else unit definition of_is_unit {c : Type} [H₁ : decidable c] (H₂ : is_unit c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, empty.rec _ (if_neg Hnc ▸ H₂)) notation `dec_star` := of_is_unit star theorem not_of_not_is_unit {c : Type} [H₁ : decidable c] (H₂ : ¬ is_unit c) : ¬ c := if Hc : c then absurd star (if_pos Hc ▸ H₂) else Hc theorem not_of_is_empty {c : Type} [H₁ : decidable c] (H₂ : is_empty c) : ¬ c := if Hc : c then empty.rec _ (if_pos Hc ▸ H₂) else Hc theorem of_not_is_empty {c : Type} [H₁ : decidable c] (H₂ : ¬ is_empty c) : c := if Hc : c then Hc else absurd star (if_neg Hc ▸ H₂) -- The following symbols should not be considered in the pattern inference procedure used by -- heuristic instantiation. attribute prod sum not iff ite dite eq ne [no_pattern] -- namespace used to collect congruence rules for "contextual simplification" namespace contextual attribute if_ctx_simp_congr [congr] attribute if_ctx_simp_congr_prop [congr] end contextual
77a28735bc1bed635d886e4574c6ce3d54fe9643
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/vector/basic.lean
66bab293ae7152ea17f2153a90bef5e0b2a254ff
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,121
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.vector import data.list.nodup import data.list.of_fn import control.applicative /-! # Additional theorems and definitions about the `vector` type This file introduces the infix notation `::ᵥ` for `vector.cons`. -/ universes u variables {n : ℕ} namespace vector variables {α : Type*} infixr `::ᵥ`:67 := vector.cons attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective /-- Two `v w : vector α n` are equal iff they are equal at every single index. -/ @[ext] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) /-- The empty `vector` is a `subsingleton`. -/ instance zero_subsingleton : subsingleton (vector α 0) := ⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩ @[simp] theorem cons_val (a : α) : ∀ (v : vector α n), (a ::ᵥ v).val = a :: v.val | ⟨_, _⟩ := rfl @[simp] theorem cons_head (a : α) : ∀ (v : vector α n), (a ::ᵥ v).head = a | ⟨_, _⟩ := rfl @[simp] theorem cons_tail (a : α) : ∀ (v : vector α n), (a ::ᵥ v).tail = v | ⟨_, _⟩ := rfl @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl @[simp] lemma length_coe (v : vector α n) : ((coe : { l : list α // l.length = n } → list α) v).length = n := v.2 @[simp] lemma to_list_map {β : Type*} (v : vector α n) (f : α → β) : (v.map f).to_list = v.to_list.map f := by cases v; refl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] lemma nth_repeat (a : α) (i : fin n) : (vector.repeat a n).nth i = a := by apply list.nth_le_repeat @[simp] lemma nth_map {β : Type*} (v : vector α n) (f : α → β) (i : fin n) : (v.map f).nth i = f (v.nth i) := by simp [nth_eq_nth_le] @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simpa only [to_list_of_fn] using list.of_fn_nth_le _ end theorem nth_tail (x : vector α n) (i) : x.tail.nth i = x.nth ⟨i.1 + 1, lt_tsub_iff_right.mp i.2⟩ := by { rcases x with ⟨_|_, h⟩; refl, } @[simp] theorem nth_tail_succ : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_val : ∀ (v : vector α n.succ), v.tail.val = v.val.tail | ⟨a::l, e⟩ := rfl /-- The `tail` of a `nil` vector is `nil`. -/ @[simp] lemma tail_nil : (@nil α).tail = nil := rfl /-- The `tail` of a vector made up of one element is `nil`. -/ @[simp] lemma singleton_tail (v : vector α 1) : v.tail = vector.nil := by simp only [←cons_head_tail, eq_iff_true_of_subsingleton] @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by { congr, funext i, cases i, simp, } /-- The list that makes up a `vector` made up of a single element, retrieved via `to_list`, is equal to the list of that single element. -/ @[simp] lemma to_list_singleton (v : vector α 1) : v.to_list = [v.head] := begin rw ←v.cons_head_tail, simp only [to_list_cons, to_list_nil, cons_head, eq_self_iff_true, and_self, singleton_tail] end /-- Mapping under `id` does not change a vector. -/ @[simp] lemma map_id {n : ℕ} (v : vector α n) : vector.map id v = v := vector.eq _ _ (by simp only [list.map_id, vector.to_list_map]) lemma mem_iff_nth {a : α} {v : vector α n} : a ∈ v.to_list ↔ ∃ i, v.nth i = a := by simp only [list.mem_iff_nth_le, fin.exists_iff, vector.nth_eq_nth_le]; exact ⟨λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length at hi, h⟩, λ ⟨i, hi, h⟩, ⟨i, by rwa to_list_length, h⟩⟩ lemma nodup_iff_nth_inj {v : vector α n} : v.to_list.nodup ↔ function.injective v.nth := begin cases v with l hl, subst hl, simp only [list.nodup_iff_nth_le_inj], split, { intros h i j hij, cases i, cases j, ext, apply h, simpa }, { intros h i j hi hj hij, have := @h ⟨i, hi⟩ ⟨j, hj⟩, simp [nth_eq_nth_le] at *, tauto } end @[simp] lemma nth_mem (i : fin n) (v : vector α n) : v.nth i ∈ v.to_list := by rw [nth_eq_nth_le]; exact list.nth_le_mem _ _ _ theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl /-- Reverse a vector. -/ def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ /-- The `list` of a vector after a `reverse`, retrieved by `to_list` is equal to the `list.reverse` after retrieving a vector's `to_list`. -/ lemma to_list_reverse {v : vector α n} : v.reverse.to_list = v.to_list.reverse := rfl @[simp] lemma reverse_reverse {v : vector α n} : v.reverse.reverse = v := by { cases v, simp [vector.reverse], } @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a ::ᵥ v) 0 = a := by simp [nth_zero] /-- Accessing the `nth` element of a vector made up of one element `x : α` is `x` itself. -/ @[simp] lemma nth_cons_nil {ix : fin 1} (x : α) : nth (x ::ᵥ nil) ix = x := by convert nth_cons_zero x nil @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a ::ᵥ v) i.succ = nth v i := by rw [← nth_tail_succ, tail_cons] /-- The last element of a `vector`, given that the vector is at least one element. -/ def last (v : vector α (n + 1)) : α := v.nth (fin.last n) /-- The last element of a `vector`, given that the vector is at least one element. -/ lemma last_def {v : vector α (n + 1)} : v.last = v.nth (fin.last n) := rfl /-- The `last` element of a vector is the `head` of the `reverse` vector. -/ lemma reverse_nth_zero {v : vector α (n + 1)} : v.reverse.head = v.last := begin have : 0 = v.to_list.length - 1 - n, { simp only [nat.add_succ_sub_one, add_zero, to_list_length, tsub_self, list.length_reverse] }, rw [←nth_zero, last_def, nth_eq_nth_le, nth_eq_nth_le], simp_rw [to_list_reverse, fin.val_eq_coe, fin.coe_last, fin.coe_zero, this], rw list.nth_le_reverse, end section scan variables {β : Type*} variables (f : β → α → β) (b : β) variables (v : vector α n) /-- Construct a `vector β (n + 1)` from a `vector α n` by scanning `f : β → α → β` from the "left", that is, from 0 to `fin.last n`, using `b : β` as the starting value. -/ def scanl : vector β (n + 1) := ⟨list.scanl f b v.to_list, by rw [list.length_scanl, to_list_length]⟩ /-- Providing an empty vector to `scanl` gives the starting value `b : β`. -/ @[simp] lemma scanl_nil : scanl f b nil = b ::ᵥ nil := rfl /-- The recursive step of `scanl` splits a vector `x ::ᵥ v : vector α (n + 1)` into the provided starting value `b : β` and the recursed `scanl` `f b x : β` as the starting value. This lemma is the `cons` version of `scanl_nth`. -/ @[simp] lemma scanl_cons (x : α) : scanl f b (x ::ᵥ v) = b ::ᵥ scanl f (f b x) v := by simpa only [scanl, to_list_cons] /-- The underlying `list` of a `vector` after a `scanl` is the `list.scanl` of the underlying `list` of the original `vector`. -/ @[simp] lemma scanl_val : ∀ {v : vector α n}, (scanl f b v).val = list.scanl f b v.val | ⟨l, hl⟩ := rfl /-- The `to_list` of a `vector` after a `scanl` is the `list.scanl` of the `to_list` of the original `vector`. -/ @[simp] lemma to_list_scanl : (scanl f b v).to_list = list.scanl f b v.to_list := rfl /-- The recursive step of `scanl` splits a vector made up of a single element `x ::ᵥ nil : vector α 1` into a `vector` of the provided starting value `b : β` and the mapped `f b x : β` as the last value. -/ @[simp] lemma scanl_singleton (v : vector α 1) : scanl f b v = b ::ᵥ f b v.head ::ᵥ nil := begin rw [←cons_head_tail v], simp only [scanl_cons, scanl_nil, cons_head, singleton_tail] end /-- The first element of `scanl` of a vector `v : vector α n`, retrieved via `head`, is the starting value `b : β`. -/ @[simp] lemma scanl_head : (scanl f b v).head = b := begin cases n, { have : v = nil := by simp only [eq_iff_true_of_subsingleton], simp only [this, scanl_nil, cons_head] }, { rw ←cons_head_tail v, simp only [←nth_zero, nth_eq_nth_le, to_list_scanl, to_list_cons, list.scanl, fin.val_zero', list.nth_le] } end /-- For an index `i : fin n`, the `nth` element of `scanl` of a vector `v : vector α n` at `i.succ`, is equal to the application function `f : β → α → β` of the `i.cast_succ` element of `scanl f b v` and `nth v i`. This lemma is the `nth` version of `scanl_cons`. -/ @[simp] lemma scanl_nth (i : fin n) : (scanl f b v).nth i.succ = f ((scanl f b v).nth i.cast_succ) (v.nth i) := begin cases n, { exact fin_zero_elim i }, induction n with n hn generalizing b, { have i0 : i = 0 := by simp only [eq_iff_true_of_subsingleton], simpa only [scanl_singleton, i0, nth_zero] }, { rw [←cons_head_tail v, scanl_cons, nth_cons_succ], refine fin.cases _ _ i, { simp only [nth_zero, scanl_head, fin.cast_succ_zero, cons_head] }, { intro i', simp only [hn, fin.cast_succ_fin_succ, nth_cons_succ] } } end end scan /-- Monadic analog of `vector.of_fn`. Given a monadic function on `fin n`, return a `vector α n` inside the monad. -/ def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a ::ᵥ v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] /-- Apply a monadic function to each component of a vector, returning a vector inside the monad. -/ def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | 0 xs := pure nil | (n+1) xs := do h' ← f xs.head, t' ← @mmap n xs.tail, pure (h' ::ᵥ t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a ::ᵥ v) = do h' ← f a, t' ← mmap f v, pure (h' ::ᵥ t') | _ ⟨l, rfl⟩ := rfl /-- Define `C v` by induction on `v : vector α n`. This function has two arguments: `h_nil` handles the base case on `C nil`, and `h_cons` defines the inductive step using `∀ x : α, C w → C (x ::ᵥ w)`. -/ @[elab_as_eliminator] def induction_on {C : Π {n : ℕ}, vector α n → Sort*} (v : vector α n) (h_nil : C nil) (h_cons : ∀ {n : ℕ} {x : α} {w : vector α n}, C w → C (x ::ᵥ w)) : C v := begin induction n with n ih generalizing v, { rcases v with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases v with ⟨_|⟨a,v⟩,_⟩, cases v_property, apply @h_cons n _ ⟨v, (add_left_inj 1).mp v_property⟩, apply ih, } end variables {β γ : Type*} /-- Define `C v w` by induction on a pair of vectors `v : vector α n` and `w : vector β n`. -/ @[elab_as_eliminator] def induction_on₂ {C : Π {n}, vector α n → vector β n → Sort*} (v : vector α n) (w : vector β n) (h_nil : C nil nil) (h_cons : ∀ {n a b} {x : vector α n} {y}, C x y → C (a ::ᵥ x) (b ::ᵥ y)) : C v w := begin induction n with n ih generalizing v w, { rcases v with ⟨_|⟨-,-⟩,-|-⟩, rcases w with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases v with ⟨_|⟨a,v⟩,_⟩, cases v_property, rcases w with ⟨_|⟨b,w⟩,_⟩, cases w_property, apply @h_cons n _ _ ⟨v, (add_left_inj 1).mp v_property⟩ ⟨w, (add_left_inj 1).mp w_property⟩, apply ih, } end /-- Define `C u v w` by induction on a triplet of vectors `u : vector α n`, `v : vector β n`, and `w : vector γ b`. -/ @[elab_as_eliminator] def induction_on₃ {C : Π {n}, vector α n → vector β n → vector γ n → Sort*} (u : vector α n) (v : vector β n) (w : vector γ n) (h_nil : C nil nil nil) (h_cons : ∀ {n a b c} {x : vector α n} {y z}, C x y z → C (a ::ᵥ x) (b ::ᵥ y) (c ::ᵥ z)) : C u v w := begin induction n with n ih generalizing u v w, { rcases u with ⟨_|⟨-,-⟩,-|-⟩, rcases v with ⟨_|⟨-,-⟩,-|-⟩, rcases w with ⟨_|⟨-,-⟩,-|-⟩, exact h_nil, }, { rcases u with ⟨_|⟨a,u⟩,_⟩, cases u_property, rcases v with ⟨_|⟨b,v⟩,_⟩, cases v_property, rcases w with ⟨_|⟨c,w⟩,_⟩, cases w_property, apply @h_cons n _ _ _ ⟨u, (add_left_inj 1).mp u_property⟩ ⟨v, (add_left_inj 1).mp v_property⟩ ⟨w, (add_left_inj 1).mp w_property⟩, apply ih, } end /-- Cast a vector to an array. -/ def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array section insert_nth variable {a : α} /-- `v.insert_nth a i` inserts `a` into the vector `v` at position `i` (and shifting later components to the right). -/ def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) := ⟨v.1.insert_nth i a, begin rw [list.length_insert_nth, v.2], rw [v.2, ← nat.succ_le_succ_iff], exact i.2 end⟩ lemma insert_nth_val {i : fin (n+1)} {v : vector α n} : (v.insert_nth a i).val = v.val.insert_nth i.1 a := rfl @[simp] lemma remove_nth_val {i : fin n} : ∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i | ⟨l, hl⟩ := rfl lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v := subtype.eq $ list.remove_nth_insert_nth i.1 v.1 lemma remove_nth_insert_nth' {v : vector α (n+1)} : ∀{i : fin (n+1)} {j : fin (n+2)}, remove_nth (j.succ_above i) (insert_nth a j v) = insert_nth a (i.pred_above j) (remove_nth i v) | ⟨i, hi⟩ ⟨j, hj⟩ := begin dsimp [insert_nth, remove_nth, fin.succ_above, fin.pred_above], simp only [subtype.mk_eq_mk], split_ifs, { convert (list.insert_nth_remove_nth_of_ge i (j-1) _ _ _).symm, { convert (nat.succ_pred_eq_of_pos _).symm, exact lt_of_le_of_lt (zero_le _) h, }, { apply remove_nth_val, }, { convert hi, exact v.2, }, { exact nat.le_pred_of_lt h, }, }, { convert (list.insert_nth_remove_nth_of_le i j _ _ _).symm, { apply remove_nth_val, }, { convert hi, exact v.2, }, { simpa using h, }, } end lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) : ∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ | ⟨l, hl⟩ := begin refine subtype.eq _, simp only [insert_nth_val, fin.coe_succ, fin.cast_succ, fin.val_eq_coe, fin.coe_cast_add], apply list.insert_nth_comm, { assumption }, { rw hl, exact nat.le_of_succ_le_succ j.2 } end end insert_nth section update_nth /-- `update_nth v n a` replaces the `n`th element of `v` with `a` -/ def update_nth (v : vector α n) (i : fin n) (a : α) : vector α n := ⟨v.1.update_nth i.1 a, by rw [list.update_nth_length, v.2]⟩ @[simp] lemma to_list_update_nth (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list = v.to_list.update_nth i a := rfl @[simp] lemma nth_update_nth_same (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).nth i = a := by cases v; cases i; simp [vector.update_nth, vector.nth_eq_nth_le] lemma nth_update_nth_of_ne {v : vector α n} {i j : fin n} (h : i ≠ j) (a : α) : (v.update_nth i a).nth j = v.nth j := by cases v; cases i; cases j; simp [vector.update_nth, vector.nth_eq_nth_le, list.nth_le_update_nth_of_ne (fin.vne_of_ne h)] lemma nth_update_nth_eq_if {v : vector α n} {i j : fin n} (a : α) : (v.update_nth i a).nth j = if i = j then a else v.nth j := by split_ifs; try {simp *}; try {rw nth_update_nth_of_ne}; assumption @[to_additive] lemma prod_update_nth [monoid α] (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list.prod = (v.take i).to_list.prod * a * (v.drop (i + 1)).to_list.prod := begin refine (list.prod_update_nth v.to_list i a).trans _, have : ↑i < v.to_list.length := lt_of_lt_of_le i.2 (le_of_eq v.2.symm), simp [this], end @[to_additive] lemma prod_update_nth' [comm_group α] (v : vector α n) (i : fin n) (a : α) : (v.update_nth i a).to_list.prod = v.to_list.prod * (v.nth i)⁻¹ * a := begin refine (list.prod_update_nth' v.to_list i a).trans _, have : ↑i < v.to_list.length := lt_of_lt_of_le i.2 (le_of_eq v.2.symm), simp [this, nth_eq_nth_le, mul_assoc], end end update_nth end vector namespace vector section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs /-- Apply an applicative function to each component of a vector. -/ protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v section variables {α β : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x ::ᵥ xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end end open function variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} -- We need to turn off the linter here as -- the `is_lawful_traversable` instance below expects a particular signature. @[nolint unused_arguments] protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
83894691561887ea0375efdb06ec09b1bc2251dc
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/bench/rbmap_checkpoint.lean
cb0bb75e931c2bfbe040126b04a78ed2b98d48c3
[ "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
3,428
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.Data.Option.Basic import Init.Data.List.BasicAux import Init.Data.String import Init.System.IO universe u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree instance : Inhabited Tree := ⟨Tree.Leaf⟩ variable {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold f r (f k v (fold f l b)) @[inline] def balance1 : Nat → Bool → Tree → Tree → Tree | kv, vv, t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | kv, vv, t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | kv, vv, t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _, _, _ => Leaf @[inline] def balance2 : Tree → Nat → Bool → Tree → Tree | t, kv, vv, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | t, kv, vv, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | t, kv, vv, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _, _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 ky vy b (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 a ky vy (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux (freq : Nat) : Nat → Tree → List Tree → List Tree | 0, m, r => m::r | n+1, m, r => let m := insert m n (n % 10 = 0); let r := if n % freq == 0 then m::r else r; mkMapAux freq n m r def mkMap (n : Nat) (freq : Nat) : List Tree := mkMapAux freq n Leaf [] def myLen : List Tree → Nat → Nat | Node _ _ _ _ _ :: xs, r => myLen xs (r + 1) | _ :: xs, r => myLen xs r | [], r => r def main (xs : List String) : IO UInt32 := do let [n, freq] ← pure xs | throw $ IO.userError "invalid input"; let n := n.toNat!; let freq := freq.toNat!; let freq := if freq == 0 then 1 else freq; let mList := mkMap n freq; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) mList.head! 0; IO.println (toString (myLen mList 0) ++ " " ++ toString v) *> pure 0
4ccf0a566421067ee1771d19c5dacdd83d02bb24
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/ring/aut.lean
642a865bbe7c99bdd71ab5e8b29a6cc76e630d32
[ "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
2,174
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, Callum Sutton, Yury Kudryashov -/ import algebra.hom.aut import algebra.ring.equiv /-! # Ring automorphisms This file defines the automorphism group structure on `ring_aut R := ring_equiv R R`. ## Implementation notes The definition of multiplication in the automorphism group agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, but not with `category_theory.comp`. This file is kept separate from `data/equiv/ring` so that `group_theory.perm` is free to use equivalences (and other files that use them) before the group structure is defined. ## Tags ring_aut -/ /-- The group of ring automorphisms. -/ @[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R namespace ring_aut variables (R : Type*) [has_mul R] [has_add R] /-- The group operation on automorphisms of a ring is defined by `λ g h, ring_equiv.trans h g`. This means that multiplication agrees with composition, `(g*h)(x) = g (h x)`. -/ instance : group (ring_aut R) := by refine_struct { mul := λ g h, ring_equiv.trans h g, one := ring_equiv.refl R, inv := ring_equiv.symm, div := _, npow := @npow_rec _ ⟨ring_equiv.refl R⟩ ⟨λ g h, ring_equiv.trans h g⟩, zpow := @zpow_rec _ ⟨ring_equiv.refl R⟩ ⟨λ g h, ring_equiv.trans h g⟩ ⟨ring_equiv.symm⟩ }; intros; ext; try { refl }; apply equiv.left_inv instance : inhabited (ring_aut R) := ⟨1⟩ /-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/ def to_add_aut : ring_aut R →* add_aut R := by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/ def to_mul_aut : ring_aut R →* mul_aut R := by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl /-- Monoid homomorphism from ring automorphisms to permutations. -/ def to_perm : ring_aut R →* equiv.perm R := by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl end ring_aut
fe4832ccaa31a1d00b23e3b2f427b37d9a3a2ad2
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/implicit5.lean
0a47e5eaddd8847022bd7f1d73ac2d5e035271c8
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
315
lean
import Int. import Real. variable f {A : Type} (a1 a2 : A) : A variable g : Int -> Int -> Int variable h : Int -> Int -> Real -> Int variable p {A B : Type} (a1 a2 : A) (b : B) : A infix ++ : f infix ++ : g infix ++ : h infix ++ : p variable p2 {A B : Type} (a1 a2 : A) (b : B) {C : Type} (c : C) : A infix ++ : p2
7d11694c7c4177d502555d3f51dd1ab268f3bd47
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/p_series.lean
50ab921921ef63703346acf3625979fa1a675f8c
[ "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
10,269
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.special_functions.pow /-! # Convergence of `p`-series In this file we prove that the series `∑' k in ℕ, 1 / k ^ p` converges if and only if `p > 1`. The proof is based on the [Cauchy condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test): `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. We prove this test in `nnreal.summable_condensed_iff` and `summable_condensed_iff_of_nonneg`, then use it to prove `summable_one_div_rpow`. After this transformation, a `p`-series turns into a geometric series. ## TODO It should be easy to generalize arguments to Schlömilch's generalization of the Cauchy condensation test once we need it. ## Tags p-series, Cauchy condensation test -/ open filter open_locale big_operators ennreal nnreal topological_space /-! ### Cauchy condensation test In this section we prove the Cauchy condensation test: for `f : ℕ → ℝ≥0` or `f : ℕ → ℝ`, `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. Instead of giving a monolithic proof, we split it into a series of lemmas with explicit estimates of partial sums of each series in terms of the partial sums of the other series. -/ namespace finset variables {M : Type*} [ordered_add_comm_monoid M] {f : ℕ → M} lemma le_sum_condensed' (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in Ico 1 (2 ^ n), f k) ≤ ∑ k in range n, (2 ^ k) •ℕ f (2 ^ k) := begin induction n with n ihn, { simp }, suffices : (∑ k in Ico (2 ^ n) (2 ^ (n + 1)), f k) ≤ (2 ^ n) •ℕ f (2 ^ n), { rw [sum_range_succ, add_comm, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [n.one_le_two_pow, nat.pow_le_pow_of_le_right zero_lt_two n.le_succ] }, have : ∀ k ∈ Ico (2 ^ n) (2 ^ (n + 1)), f k ≤ f (2 ^ n) := λ k hk, hf (pow_pos zero_lt_two _) (Ico.mem.mp hk).1, convert sum_le_sum this, simp [pow_succ, two_mul] end lemma le_sum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (2 ^ n), f k) ≤ f 0 + ∑ k in range n, (2 ^ k) •ℕ f (2 ^ k) := begin convert add_le_add_left (le_sum_condensed' hf n) (f 0), rw [← sum_range_add_sum_Ico _ n.one_le_two_pow, sum_range_succ, sum_range_zero, add_zero] end lemma sum_condensed_le' (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range n, (2 ^ k) •ℕ f (2 ^ (k + 1))) ≤ ∑ k in Ico 2 (2 ^ n + 1), f k := begin induction n with n ihn, { simp }, suffices : (2 ^ n) •ℕ f (2 ^ (n + 1)) ≤ ∑ k in Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f k, { rw [sum_range_succ, add_comm, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [add_le_add_right n.one_le_two_pow _, add_le_add_right (nat.pow_le_pow_of_le_right zero_lt_two n.le_succ) _] }, have : ∀ k ∈ Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f (2 ^ (n + 1)) ≤ f k := λ k hk, hf (n.one_le_two_pow.trans_lt $ (nat.lt_succ_of_le le_rfl).trans_le (Ico.mem.mp hk).1) (nat.le_of_lt_succ $ (Ico.mem.mp hk).2), convert sum_le_sum this, simp [pow_succ, two_mul] end lemma sum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (n + 1), (2 ^ k) •ℕ f (2 ^ k)) ≤ f 1 + 2 •ℕ ∑ k in Ico 2 (2 ^ n + 1), f k := begin convert add_le_add_left (nsmul_le_nsmul_of_le_right (sum_condensed_le' hf n) 2) (f 1), simp [sum_range_succ', add_comm, pow_succ, mul_nsmul, sum_nsmul] end end finset namespace ennreal variable {f : ℕ → ℝ≥0∞} lemma le_tsum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : ∑' k, f k ≤ f 0 + ∑' k : ℕ, (2 ^ k) * f (2 ^ k) := begin rw [ennreal.tsum_eq_supr_nat' (nat.tendsto_pow_at_top_at_top_of_one_lt _root_.one_lt_two)], refine supr_le (λ n, (finset.le_sum_condensed hf n).trans (add_le_add_left _ _)), simp only [nsmul_eq_mul, nat.cast_pow, nat.cast_two], apply ennreal.sum_le_tsum end lemma tsum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) : ∑' k : ℕ, (2 ^ k * f (2 ^ k)) ≤ f 1 + 2 * ∑' k, f k := begin rw [ennreal.tsum_eq_supr_nat' (tendsto_at_top_mono nat.le_succ tendsto_id), two_mul, ← two_nsmul], refine supr_le (λ n, le_trans _ (add_le_add_left (nsmul_le_nsmul_of_le_right (ennreal.sum_le_tsum $ finset.Ico 2 (2^n + 1)) _) _)), simpa using finset.sum_condensed_le hf n end end ennreal namespace nnreal /-- Cauchy condensation test for a series of `nnreal` version. -/ lemma summable_condensed_iff {f : ℕ → ℝ≥0} (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin simp only [← ennreal.tsum_coe_ne_top_iff_summable, ne.def, not_iff_not, ennreal.coe_mul, ennreal.coe_pow, ennreal.coe_two], split; intro h, { replace hf : ∀ m n, 1 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf (zero_lt_one.trans hm) hmn), simpa [h, ennreal.add_eq_top] using (ennreal.tsum_condensed_le hf) }, { replace hf : ∀ m n, 0 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf hm hmn), simpa [h, ennreal.add_eq_top] using (ennreal.le_tsum_condensed hf) } end end nnreal /-- Cauchy condensation test for series of nonnegative real numbers. -/ lemma summable_condensed_iff_of_nonneg {f : ℕ → ℝ} (h_nonneg : ∀ n, 0 ≤ f n) (h_mono : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin set g : ℕ → ℝ≥0 := λ n, ⟨f n, h_nonneg n⟩, have : f = λ n, g n := rfl, simp only [this], have : ∀ ⦃m n⦄, 0 < m → m ≤ n → g n ≤ g m := λ m n hm h, nnreal.coe_le_coe.2 (h_mono hm h), exact_mod_cast nnreal.summable_condensed_iff this end open real /-! ### Convergence of the `p`-series In this section we prove that for a real number `p`, the series `∑' n : ℕ, 1 / (n ^ p)` converges if and only if `1 < p`. There are many different proofs of this fact. The proof in this file uses the Cauchy condensation test we formalized above. This test implies that `∑ n, 1 / (n ^ p)` converges if and only if `∑ n, 2 ^ n / ((2 ^ n) ^ p)` converges, and the latter series is a geometric series with common ratio `2 ^ {1 - p}`. -/ /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := begin cases le_or_lt 0 p with hp hp, /- Cauchy condensation test applies only to monotonically decreasing sequences, so we consider the cases `0 ≤ p` and `p < 0` separately. -/ { rw ← summable_condensed_iff_of_nonneg, { simp_rw [nat.cast_pow, nat.cast_two, ← rpow_nat_cast, ← rpow_mul zero_lt_two.le, mul_comm _ p, rpow_mul zero_lt_two.le, rpow_nat_cast, ← inv_pow', ← mul_pow, summable_geometric_iff_norm_lt_1], nth_rewrite 0 [← rpow_one 2], rw [← division_def, ← rpow_sub zero_lt_two, norm_eq_abs, abs_of_pos (rpow_pos_of_pos zero_lt_two _), rpow_lt_one_iff zero_lt_two.le], norm_num }, { intro n, exact inv_nonneg.2 (rpow_nonneg_of_nonneg n.cast_nonneg _) }, { intros m n hm hmn, exact inv_le_inv_of_le (rpow_pos_of_pos (nat.cast_pos.2 hm) _) (rpow_le_rpow m.cast_nonneg (nat.cast_le.2 hmn) hp) } }, /- If `p < 0`, then `1 / n ^ p` tends to infinity, thus the series diverges. -/ { suffices : ¬summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ), { have : ¬(1 < p) := λ hp₁, hp.not_le (zero_le_one.trans hp₁.le), simpa [this, -one_div] }, { intro h, obtain ⟨k : ℕ, hk₁ : ((k ^ p)⁻¹ : ℝ) < 1, hk₀ : k ≠ 0⟩ := ((h.tendsto_cofinite_zero.eventually (gt_mem_nhds zero_lt_one)).and (eventually_cofinite_ne 0)).exists, apply hk₀, rw [← pos_iff_ne_zero, ← @nat.cast_pos ℝ] at hk₀, simpa [inv_lt_one_iff_of_pos (rpow_pos_of_pos hk₀ _), one_lt_rpow_iff_of_pos hk₀, hp, hp.not_lt, hk₀] using hk₁ } } end /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_pow_inv {p : ℕ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := by simp only [← rpow_nat_cast, real.summable_nat_rpow_inv, nat.one_lt_cast] /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_pow {p : ℕ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_nat_cast_inv : ¬summable (λ n, n⁻¹ : ℕ → ℝ) := have ¬summable (λ n, (n^1)⁻¹ : ℕ → ℝ), from mt real.summable_nat_pow_inv.1 (lt_irrefl 1), by simpa /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_one_div_nat_cast : ¬summable (λ n, 1 / n : ℕ → ℝ) := by simpa only [inv_eq_one_div] using real.not_summable_nat_cast_inv /-- Harmonic series diverges. -/ lemma real.tendsto_sum_range_one_div_nat_succ_at_top : tendsto (λ n, ∑ i in finset.range n, (1 / (i + 1) : ℝ)) at_top at_top := begin rw ← not_summable_iff_tendsto_nat_at_top_of_nonneg, { exact_mod_cast mt (summable_nat_add_iff 1).1 real.not_summable_one_div_nat_cast }, { exact λ i, div_nonneg zero_le_one i.cast_add_one_pos.le } end @[simp] lemma nnreal.summable_one_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ≥0) ↔ 1 < p := by simp [← nnreal.summable_coe] lemma nnreal.summable_one_div_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ≥0) ↔ 1 < p := by simp
b0e086bea53f930451124a71398153a4c628306f
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/linear_algebra/determinant.lean
9555be081c7c008a3162ed55bc535aab039f8fcc
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
5,494
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes -/ import data.matrix import group_theory.perm.sign universes u v open equiv equiv.perm finset function namespace matrix variables {n : Type u} [fintype n] [decidable_eq n] {R : Type v} [comm_ring R] local notation `ε` σ:max := ((sign σ : ℤ ) : R) definition det (M : matrix n n R) : R := univ.sum (λ (σ : perm n), ε σ * univ.prod (λ i, M (σ i) i)) @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = univ.prod d := begin refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt (equiv.ext _ _) h2) with x h3, convert ring.mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card, zero_pow (fintype.card_pos_iff.2 h)] @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : univ.sum (λ σ : perm n, (ε σ) * (univ.prod (λ x, M (σ x) (p x) * N (p x) x))) = 0 := let ⟨i, hi⟩ := classical.not_forall.1 (mt fintype.injective_iff_bijective.1 H) in let ⟨j, hij'⟩ := classical.not_forall.1 hi in have hij : p i = p j ∧ i ≠ j, from not_imp.1 hij', sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc, have univ.prod (λ x, M (σ x) (p x)) = univ.prod (λ x, M ((σ * swap i j) x) (p x)), from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this]) (λ _ _ _ _ h, (swap i j).injective h) (λ b _, ⟨swap i j b, mem_univ _, by simp⟩), by simp [sign_mul, this, sign_swap hij.2, prod_mul_distrib]) (λ σ _ _ h, hij.2 (σ.injective $ by conv {to_lhs, rw ← h}; simp)) (λ _ _, mem_univ _) (λ _ _, equiv.ext _ _ $ by simp) @[simp] lemma det_mul (M N : matrix n n R) : det (M * N) = det M * det N := calc det (M * N) = univ.sum (λ σ : perm n, (univ.pi (λ a, univ)).sum (λ (p : Π (a : n), a ∈ univ → n), ε σ * univ.attach.prod (λ i, M (σ i.1) (p i.1 (mem_univ _)) * N (p i.1 (mem_univ _)) i.1))) : by simp only [det, mul_val', prod_sum, mul_sum] ... = univ.sum (λ σ : perm n, univ.sum (λ p : n → n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : sum_congr rfl (λ σ _, sum_bij (λ f h i, f i (mem_univ _)) (λ _ _, mem_univ _) (by simp) (by simp [funext_iff]) (λ b _, ⟨λ i hi, b i, by simp⟩)) ... = univ.sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_comm ... = ((@univ (n → n) _).filter bijective ∪ univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_congr (finset.ext.2 (by simp; tauto)) (λ _ _, rfl) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : finset.sum_union (by simp [finset.ext]; tauto) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) + (univ.filter (λ p : n → n, ¬bijective p)).sum (λ p, 0) : (add_left_inj _).2 (finset.sum_congr rfl $ λ p h, det_mul_aux (mem_filter.1 h).2) ... = ((@univ (n → n) _).filter bijective).sum (λ p : n → n, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (p i) * N (p i) i))) : by simp ... = (@univ (perm n) _).sum (λ τ, univ.sum (λ σ : perm n, ε σ * univ.prod (λ i, M (σ i) (τ i) * N (τ i) i))) : sum_bij (λ p h, equiv.of_bijective (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, eq_of_to_fun_eq rfl⟩) ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * ε τ) * univ.prod (λ j, M (τ j) (σ j)))) : by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = univ.sum (λ σ : perm n, univ.sum (λ τ : perm n, (univ.prod (λ i, N (σ i) i) * (ε σ * ε τ)) * univ.prod (λ i, M (τ i) i))) : sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _) (λ τ _, have univ.prod (λ j, M (τ j) (σ j)) = univ.prod (λ j, M ((τ * σ⁻¹) j) j), by rw prod_univ_perm σ⁻¹; simp [mul_apply], have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul] ... = ε τ : by simp, by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm]) (λ _ _ _ _, (mul_right_inj _).1) (λ τ _, ⟨τ * σ, by simp⟩)) ... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm] instance : is_monoid_hom (det : matrix n n R → R) := { map_one := det_one, map_mul := det_mul } end matrix
ef183dd1314282420cb6a376bac4811754da017a
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Widget/Diff.lean
b4de3948acb637fed7ad846989b7fe6653b7a0da
[ "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
12,797
lean
/- Copyright (c) 2022 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ import Lean.Meta.PPGoal import Lean.Widget.InteractiveCode import Lean.Widget.InteractiveGoal import Lean.Data.Lsp.Extra import Lean.Elab.InfoTree namespace Lean.Widget register_builtin_option showTacticDiff : Bool := { defValue := true descr := "When true, interactive goals for tactics will be decorated with diffing information. " } open Server Std Lean SubExpr /-- A marker for a point in the expression where a subexpression has been inserted. NOTE: in the future we may add other tags. -/ inductive ExprDiffTag where | change | delete def ExprDiffTag.toHighlightColor : (useAfter : Bool) → ExprDiffTag → HighlightColor | true, .change => .green | false, .change => .yellow | _, .delete => .red def ExprDiffTag.toString : ExprDiffTag → String | .change => "change" | .delete => "delete" instance : ToString ExprDiffTag := ⟨ExprDiffTag.toString⟩ /-- A description of the differences between a pair of expressions `before`, `after : Expr`. The information can be used to display a 'visual diff' for either `before`, showing the parts of the expression that are about to change, or `after` showing which parts of the expression have changed. -/ structure ExprDiff where /-- Map from subexpr positions in `e₀` to diff points.-/ changesBefore : PosMap ExprDiffTag := ∅ /-- A map from subexpr positions in `e₁` to 'diff points' which are tags describing how the expression has changed relative to `before` at the given position.-/ changesAfter : PosMap ExprDiffTag := ∅ instance : EmptyCollection ExprDiff := ⟨{}⟩ instance : Append ExprDiff where append a b := { changesBefore := RBMap.mergeBy (fun _ _ b => b) a.changesBefore b.changesBefore, changesAfter := RBMap.mergeBy (fun _ _ b => b) a.changesAfter b.changesAfter } instance : ToString ExprDiff where toString x := let f := fun (p : PosMap ExprDiffTag) => RBMap.toList p |>.map (fun (k,v) => s!"({toString k}:{toString v})") s!"before: {f x.changesBefore}\nafter: {f x.changesAfter}" /-- Add a tag at the given position to the `changesBefore` dict. -/ def ExprDiff.insertBeforeChange (p : Pos) (d : ExprDiffTag := .change) (δ : ExprDiff) : ExprDiff := {δ with changesBefore := δ.changesBefore.insert p d} /-- Add a tag at the given position to the `changesAfter` dict. -/ def ExprDiff.insertAfterChange (p : Pos) (d : ExprDiffTag := .change) (δ : ExprDiff) : ExprDiff := {δ with changesAfter := δ.changesAfter.insert p d} def ExprDiff.withChangePos (before after : Pos) (d : ExprDiffTag := .change) : ExprDiff := { changesAfter := RBMap.empty.insert after d changesBefore := RBMap.empty.insert before d } /-- Add a tag to the diff at the positions given by `before` and `after`. -/ def ExprDiff.withChange (before after : SubExpr) (d : ExprDiffTag := .change) : ExprDiff := ExprDiff.withChangePos before.pos after.pos d /-- If true, the expression before and the expression after are identical. -/ def ExprDiff.isEmpty (d : ExprDiff) : Bool := d.changesAfter.isEmpty ∧ d.changesBefore.isEmpty /-- Computes a diff between `before` and `after` expressions. This works by recursively comparing function arguments. TODO(ed): experiment with a 'greatest common subexpression' design where given `e₀`, `e₁`, find the greatest common subexpressions `Xs : Array Expr` and a congruence `F` such that `e₀ = F[A₀[..Xs]]` and `e₀ = F[A₁[..Xs]]`. Then, we can have fancy diff highlighting where common subexpressions are not highlighted. ## Diffing binders Two binding domains are identified if they have the same user name and the same type. The most common tactic that modifies binders is after an `intros`. To deal with this case, if `before = (a : α) → β` and `after`, is not a matching binder (ie: not `(a : α) → _`) then we instantiate the `before` variable in a new context and continue diffing `β` against `after`. -/ partial def exprDiffCore (before after : SubExpr) : MetaM ExprDiff := do if before.expr == after.expr then return ∅ match before.expr, after.expr with | .app .., .app .. => let (fn₀, args₀) := after.expr.withApp Prod.mk let (fn₁, args₁) := before.expr.withApp Prod.mk if fn₀ != fn₁ || args₀.size != args₁.size then return ExprDiff.withChange before after let args := Array.zip args₀ args₁ let args ← args.mapIdxM (fun i (beforeArg, afterArg) => exprDiffCore ⟨beforeArg, before.pos.pushNaryArg args₀.size i⟩ ⟨afterArg, after.pos.pushNaryArg args₀.size i⟩ ) return args.foldl (init := ∅) (· ++ ·) | .forallE .., _ => piDiff before after | .lam n₀ d₀ b₀ i₀, .lam n₁ d₁ b₁ i₁=> if n₀ != n₁ || i₀ != i₁ then return ExprDiff.withChange before after let δd ← exprDiffCore ⟨d₀, before.pos.pushBindingDomain⟩ ⟨d₁, after.pos.pushBindingDomain⟩ if δd.isEmpty then return ← exprDiffCore ⟨b₀, before.pos.pushBindingBody⟩ ⟨b₁, after.pos.pushBindingBody⟩ else return δd ++ ExprDiff.withChangePos before.pos.pushBindingBody after.pos.pushBindingBody | _, _ => return ExprDiff.withChange before after where piDiff (before after : SubExpr) : MetaM ExprDiff := do let .forallE n₀ d₀ b₀ i₀ := before.expr | return ∅ if let .forallE n₁ d₁ b₁ i₁ := after.expr then if n₀ == n₁ && i₀ == i₁ then -- assume that these are the same binders let δd ← exprDiffCore ⟨d₀, before.pos.pushBindingDomain⟩ ⟨d₁, after.pos.pushBindingDomain⟩ if δd.isEmpty then -- the types have changed, so we can no longer meaningfully compare the targets let δt ← Lean.Meta.withLocalDecl n₀ i₀ d₀ fun x => exprDiffCore ⟨b₀.instantiate1 x, before.pos.pushBindingBody⟩ ⟨b₁.instantiate1 x, after.pos.pushBindingBody⟩ return δt else return δd ++ ExprDiff.withChangePos before.pos.pushBindingBody after.pos.pushBindingBody -- in this case, the after expression does not match the before expression. -- however, a special case is intros: if let some s := List.isSuffixOf? after.expr.getForallBinderNames before.expr.getForallBinderNames then -- s ++ namesAfter = namesBefore if s.length == 0 then throwError "should not happen" let body₀ := before.expr.getForallBodyMaxDepth s.length let mut δ : ExprDiff ← (do -- this line can fail if we are using `before`'s mvar context, in which case -- we can skip giving a diff. let fvars ← s.mapM Lean.Meta.getFVarFromUserName return ← exprDiffCore ⟨body₀.instantiateRev fvars.toArray, before.pos.pushNthBindingBody s.length⟩ after ) <|> (pure ∅) for i in [0:s.length] do δ := δ.insertBeforeChange (before.pos.pushNthBindingDomain i) .delete -- [todo] maybe here insert a tag on the after case indicating an expression was deleted above the expression? return δ return ExprDiff.withChange before after /-- Computes the diff for `e₀` and `e₁`. If `useAfter` is `false`, `e₀, e₁` are interpreted as `after, before` instead of `before, after`.-/ def exprDiff (e₀ e₁ : Expr) (useAfter := true) : MetaM ExprDiff := do let s₀ := ⟨e₀, Pos.root⟩ let s₁ := ⟨e₁, Pos.root⟩ if useAfter then exprDiffCore s₀ s₁ else exprDiffCore s₁ s₀ /-- Given a `diff` between `before` and `after : Expr`, and the rendered `infoAfter : CodeWithInfos` for `after`, this function decorates `infoAfter` with tags indicating where the expression has changed. If `useAfter == false` before and after are swapped. -/ def addDiffTags (useAfter : Bool) (diff : ExprDiff) (info₁ : CodeWithInfos) : MetaM CodeWithInfos := do let cs := if useAfter then diff.changesAfter else diff.changesBefore info₁.mergePosMap (fun info d => pure <| info.highlight <| d.toHighlightColor useAfter) cs open Meta /-- Diffs the given hypothesis bundle against the given local context. If `useAfter == true`, `ctx₀` is the context _before_ and `h₁` is the bundle _after_. If `useAfter == false`, these are swapped. -/ def diffHypothesesBundle (useAfter : Bool) (ctx₀ : LocalContext) (h₁ : InteractiveHypothesisBundle) : MetaM InteractiveHypothesisBundle := do /- Strategy: we say a hypothesis has mutated if the ppName is the same but the fvarid has changed. this indicates that something like `rewrite at` has hit it. -/ for (ppName, fvid) in Array.zip h₁.names h₁.fvarIds do if !(ctx₀.contains fvid) then if let some decl₀ := ctx₀.findFromUserName? ppName then -- on ctx₀ there is an fvar with the same name as this one. let t₀ := decl₀.type return ← withTypeDiff t₀ h₁ else if useAfter then return {h₁ with isInserted? := true } else return {h₁ with isRemoved? := true } -- all fvids are present on original so we can assume no change. return h₁ where withTypeDiff (t₀ : Expr) (h₁ : InteractiveHypothesisBundle) : MetaM InteractiveHypothesisBundle := do let some x₁ := h₁.fvarIds[0]? | throwError "internal error: empty fvar list!" let t₁ ← inferType <| Expr.fvar x₁ let tδ ← exprDiff t₀ t₁ useAfter let c₁ ← addDiffTags useAfter tδ h₁.type return {h₁ with type := c₁} def diffHypotheses (useAfter : Bool) (lctx₀ : LocalContext) (hs₁ : Array InteractiveHypothesisBundle) : MetaM (Array InteractiveHypothesisBundle) := do -- [todo] also show when hypotheses (user-names present in lctx₀ but not in hs₁) are deleted hs₁.mapM (diffHypothesesBundle useAfter lctx₀) /-- Decorates the given goal `i₁` with a diff by comparing with goal `g₀`. If `useAfter` is true then `i₁` is _after_ and `g₀` is _before_. Otherwise they are swapped. -/ def diffInteractiveGoal (useAfter : Bool) (g₀ : MVarId) (i₁ : InteractiveGoal) : MetaM InteractiveGoal := do let mctx ← getMCtx let some md₀ := mctx.findDecl? g₀ | throwError "Failed to find decl for {g₀}." let lctx₀ := md₀.lctx |>.sanitizeNames.run' {options := (← getOptions)} let hs₁ ← diffHypotheses useAfter lctx₀ i₁.hyps let i₁ := {i₁ with hyps := hs₁} let some g₁ := i₁.mvarId? | throwError "Expected InteractiveGoal to have an mvarId" let t₀ ← instantiateMVars <|← inferType (Expr.mvar g₀) let some md₁ := (← getMCtx).findDecl? g₁ | throwError "Unknown goal {g₁}" let t₁ ← instantiateMVars md₁.type let tδ ← exprDiff t₀ t₁ useAfter let c₁ ← addDiffTags useAfter tδ i₁.type let i₁ := {i₁ with type := c₁, isInserted? := false} return i₁ /-- Modifies `goalsAfter` with additional information about how it is different to `goalsBefore`. If `useAfter` is `true` then `igs₁` is the set of interactive goals _after_ the tactic has been applied. Otherwise `igs₁` is the set of interactive goals _before_. -/ def diffInteractiveGoals (useAfter : Bool) (info : Elab.TacticInfo) (igs₁ : InteractiveGoals) : MetaM InteractiveGoals := do if ! showTacticDiff.get (← getOptions) then return igs₁ else let goals₀ := if useAfter then info.goalsBefore else info.goalsAfter let parentMap : MVarIdMap MVarIdSet ← info.goalsBefore.foldlM (init := ∅) (fun s g => do let ms ← Expr.mvar g |> Lean.Meta.getMVars let ms : MVarIdSet := RBTree.fromArray ms _ return s.insert g ms ) let isParent (before after : MVarId) : Bool := match parentMap.find? before with | some xs => xs.contains after | none => false let goals ← igs₁.goals.mapM (fun ig₁ => do let some g₁ := ig₁.mvarId? | throwError "error: goal not found" withGoalCtx (g₁ : MVarId) (fun _lctx₁ _md₁ => do -- if the goal is present on the previous version then continue if goals₀.any (fun g₀ => g₀ == g₁) then return {ig₁ with isInserted? := none} let some g₀ := goals₀.find? (fun g₀ => if useAfter then isParent g₀ g₁ else isParent g₁ g₀) | return if useAfter then {ig₁ with isInserted? := true } else {ig₁ with isRemoved? := true} let ig₁ ← diffInteractiveGoal useAfter g₀ ig₁ return ig₁ ) ) return {igs₁ with goals := goals} end Lean.Widget
b20313aec36b0afdf9a9e159310089a7476d1be5
94e33a31faa76775069b071adea97e86e218a8ee
/src/linear_algebra/basis.lean
dfad04351c8844849a761253529906723bbb86f0
[ "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
50,124
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp -/ import algebra.big_operators.finsupp import algebra.big_operators.finprod import data.fintype.card import linear_algebra.finsupp import linear_algebra.linear_independent import linear_algebra.linear_pmap import linear_algebra.projection /-! # Bases This file defines bases in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `basis ι R M` is the type of `ι`-indexed `R`-bases for a module `M`, represented by a linear equiv `M ≃ₗ[R] ι →₀ R`. * the basis vectors of a basis `b : basis ι R M` are available as `b i`, where `i : ι` * `basis.repr` is the isomorphism sending `x : M` to its coordinates `basis.repr x : ι →₀ R`. The converse, turning this isomorphism into a basis, is called `basis.of_repr`. * If `ι` is finite, there is a variant of `repr` called `basis.equiv_fun b : M ≃ₗ[R] ι → R` (saving you from having to work with `finsupp`). The converse, turning this isomorphism into a basis, is called `basis.of_equiv_fun`. * `basis.constr hv f` constructs a linear map `M₁ →ₗ[R] M₂` given the values `f : ι → M₂` at the basis elements `⇑b : ι → M₁`. * `basis.reindex` uses an equiv to map a basis to a different indexing set. * `basis.map` uses a linear equiv to map a basis to a different module. ## Main statements * `basis.mk`: a linear independent set of vectors spanning the whole module determines a basis * `basis.ext` states that two linear maps are equal if they coincide on a basis. Similar results are available for linear equivs (if they coincide on the basis vectors), elements (if their coordinates coincide) and the functions `b.repr` and `⇑b`. * `basis.of_vector_space` states that every vector space has a basis. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. For bases, this is useful as well because we can easily derive ordered bases by using an ordered index type `ι`. ## Tags basis, bases -/ noncomputable theory universe u open function set submodule open_locale classical big_operators variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables [semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] section variables (ι) (R) (M) /-- A `basis ι R M` for a module `M` is the type of `ι`-indexed `R`-bases of `M`. The basis vectors are available as `coe_fn (b : basis ι R M) : ι → M`. To turn a linear independent family of vectors spanning `M` into a basis, use `basis.mk`. They are internally represented as linear equivs `M ≃ₗ[R] (ι →₀ R)`, available as `basis.repr`. -/ structure basis := of_repr :: (repr : M ≃ₗ[R] (ι →₀ R)) end namespace basis instance : inhabited (basis ι R (ι →₀ R)) := ⟨basis.of_repr (linear_equiv.refl _ _)⟩ variables (b b₁ : basis ι R M) (i : ι) (c : R) (x : M) section repr /-- `b i` is the `i`th basis vector. -/ instance : has_coe_to_fun (basis ι R M) (λ _, ι → M) := { coe := λ b i, b.repr.symm (finsupp.single i 1) } @[simp] lemma coe_of_repr (e : M ≃ₗ[R] (ι →₀ R)) : ⇑(of_repr e) = λ i, e.symm (finsupp.single i 1) := rfl protected lemma injective [nontrivial R] : injective b := b.repr.symm.injective.comp (λ _ _, (finsupp.single_left_inj (one_ne_zero : (1 : R) ≠ 0)).mp) lemma repr_symm_single_one : b.repr.symm (finsupp.single i 1) = b i := rfl lemma repr_symm_single : b.repr.symm (finsupp.single i c) = c • b i := calc b.repr.symm (finsupp.single i c) = b.repr.symm (c • finsupp.single i 1) : by rw [finsupp.smul_single', mul_one] ... = c • b i : by rw [linear_equiv.map_smul, repr_symm_single_one] @[simp] lemma repr_self : b.repr (b i) = finsupp.single i 1 := linear_equiv.apply_symm_apply _ _ lemma repr_self_apply (j) [decidable (i = j)] : b.repr (b i) j = if i = j then 1 else 0 := by rw [repr_self, finsupp.single_apply] @[simp] lemma repr_symm_apply (v) : b.repr.symm v = finsupp.total ι M R b v := calc b.repr.symm v = b.repr.symm (v.sum finsupp.single) : by simp ... = ∑ i in v.support, b.repr.symm (finsupp.single i (v i)) : by rw [finsupp.sum, linear_equiv.map_sum] ... = finsupp.total ι M R b v : by simp [repr_symm_single, finsupp.total_apply, finsupp.sum] @[simp] lemma coe_repr_symm : ↑b.repr.symm = finsupp.total ι M R b := linear_map.ext (λ v, b.repr_symm_apply v) @[simp] lemma repr_total (v) : b.repr (finsupp.total _ _ _ b v) = v := by { rw ← b.coe_repr_symm, exact b.repr.apply_symm_apply v } @[simp] lemma total_repr : finsupp.total _ _ _ b (b.repr x) = x := by { rw ← b.coe_repr_symm, exact b.repr.symm_apply_apply x } lemma repr_range : (b.repr : M →ₗ[R] (ι →₀ R)).range = finsupp.supported R R univ := by rw [linear_equiv.range, finsupp.supported_univ] lemma mem_span_repr_support {ι : Type*} (b : basis ι R M) (m : M) : m ∈ span R (b '' (b.repr m).support) := (finsupp.mem_span_image_iff_total _).2 ⟨b.repr m, (by simp [finsupp.mem_supported_support])⟩ lemma repr_support_subset_of_mem_span {ι : Type*} (b : basis ι R M) (s : set ι) {m : M} (hm : m ∈ span R (b '' s)) : ↑(b.repr m).support ⊆ s := begin rcases (finsupp.mem_span_image_iff_total _).1 hm with ⟨l, hl, hlm⟩, rwa [←hlm, repr_total, ←finsupp.mem_supported R l] end end repr section coord /-- `b.coord i` is the linear function giving the `i`'th coordinate of a vector with respect to the basis `b`. `b.coord i` is an element of the dual space. In particular, for finite-dimensional spaces it is the `ι`th basis vector of the dual space. -/ @[simps] def coord : M →ₗ[R] R := (finsupp.lapply i) ∘ₗ ↑b.repr lemma forall_coord_eq_zero_iff {x : M} : (∀ i, b.coord i x = 0) ↔ x = 0 := iff.trans (by simp only [b.coord_apply, finsupp.ext_iff, finsupp.zero_apply]) b.repr.map_eq_zero_iff /-- The sum of the coordinates of an element `m : M` with respect to a basis. -/ noncomputable def sum_coords : M →ₗ[R] R := finsupp.lsum ℕ (λ i, linear_map.id) ∘ₗ (b.repr : M →ₗ[R] ι →₀ R) @[simp] lemma coe_sum_coords : (b.sum_coords : M → R) = λ m, (b.repr m).sum (λ i, id) := rfl lemma coe_sum_coords_eq_finsum : (b.sum_coords : M → R) = λ m, ∑ᶠ i, b.coord i m := begin ext m, simp only [basis.sum_coords, basis.coord, finsupp.lapply_apply, linear_map.id_coe, linear_equiv.coe_coe, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsum_eq_sum _ (b.repr m).finite_support, finsupp.sum, finset.finite_to_set_to_finset, id.def, finsupp.fun_support_eq], end @[simp] lemma coe_sum_coords_of_fintype [fintype ι] : (b.sum_coords : M → R) = ∑ i, b.coord i := begin ext m, simp only [sum_coords, finsupp.sum_fintype, linear_map.id_coe, linear_equiv.coe_coe, coord_apply, id.def, fintype.sum_apply, implies_true_iff, eq_self_iff_true, finsupp.coe_lsum, linear_map.coe_comp], end @[simp] lemma sum_coords_self_apply : b.sum_coords (b i) = 1 := by simp only [basis.sum_coords, linear_map.id_coe, linear_equiv.coe_coe, id.def, basis.repr_self, function.comp_app, finsupp.coe_lsum, linear_map.coe_comp, finsupp.sum_single_index] end coord section ext variables {R₁ : Type*} [semiring R₁] {σ : R →+* R₁} {σ' : R₁ →+* R} variables [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] variables {M₁ : Type*} [add_comm_monoid M₁] [module R₁ M₁] /-- Two linear maps are equal if they are equal on basis vectors. -/ theorem ext {f₁ f₂ : M →ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_map.map_sum, linear_map.map_smulₛₗ, h] } include σ' /-- Two linear equivs are equal if they are equal on basis vectors. -/ theorem ext' {f₁ f₂ : M ≃ₛₗ[σ] M₁} (h : ∀ i, f₁ (b i) = f₂ (b i)) : f₁ = f₂ := by { ext x, rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], simp only [linear_equiv.map_sum, linear_equiv.map_smulₛₗ, h] } omit σ' /-- Two elements are equal if their coordinates are equal. -/ theorem ext_elem {x y : M} (h : ∀ i, b.repr x i = b.repr y i) : x = y := by { rw [← b.total_repr x, ← b.total_repr y], congr' 1, ext i, exact h i } lemma repr_eq_iff {b : basis ι R M} {f : M →ₗ[R] ι →₀ R} : ↑b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma repr_eq_iff' {b : basis ι R M} {f : M ≃ₗ[R] ι →₀ R} : b.repr = f ↔ ∀ i, f (b i) = finsupp.single i 1 := ⟨λ h i, h ▸ b.repr_self i, λ h, b.ext' (λ i, (b.repr_self i).trans (h i).symm)⟩ lemma apply_eq_iff {b : basis ι R M} {x : M} {i : ι} : b i = x ↔ b.repr x = finsupp.single i 1 := ⟨λ h, h ▸ b.repr_self i, λ h, b.repr.injective ((b.repr_self i).trans h.symm)⟩ /-- An unbundled version of `repr_eq_iff` -/ lemma repr_apply_eq (f : M → ι → R) (hadd : ∀ x y, f (x + y) = f x + f y) (hsmul : ∀ (c : R) (x : M), f (c • x) = c • f x) (f_eq : ∀ i, f (b i) = finsupp.single i 1) (x : M) (i : ι) : b.repr x i = f x i := begin let f_i : M →ₗ[R] R := { to_fun := λ x, f x i, map_add' := λ _ _, by rw [hadd, pi.add_apply], map_smul' := λ _ _, by { simp [hsmul, pi.smul_apply] } }, have : (finsupp.lapply i) ∘ₗ ↑b.repr = f_i, { refine b.ext (λ j, _), show b.repr (b j) i = f (b j) i, rw [b.repr_self, f_eq] }, calc b.repr x i = f_i x : by { rw ← this, refl } ... = f x i : rfl end /-- Two bases are equal if they assign the same coordinates. -/ lemma eq_of_repr_eq_repr {b₁ b₂ : basis ι R M} (h : ∀ x i, b₁.repr x i = b₂.repr x i) : b₁ = b₂ := have b₁.repr = b₂.repr, by { ext, apply h }, by { cases b₁, cases b₂, simpa } /-- Two bases are equal if their basis vectors are the same. -/ @[ext] lemma eq_of_apply_eq {b₁ b₂ : basis ι R M} (h : ∀ i, b₁ i = b₂ i) : b₁ = b₂ := suffices b₁.repr = b₂.repr, by { cases b₁, cases b₂, simpa }, repr_eq_iff'.mpr (λ i, by rw [h, b₂.repr_self]) end ext section map variables (f : M ≃ₗ[R] M') /-- Apply the linear equivalence `f` to the basis vectors. -/ @[simps] protected def map : basis ι R M' := of_repr (f.symm.trans b.repr) @[simp] lemma map_apply (i) : b.map f i = f (b i) := rfl end map section map_coeffs variables {R' : Type*} [semiring R'] [module R' M] (f : R ≃+* R') (h : ∀ c (x : M), f c • x = c • x) include f h b local attribute [instance] has_smul.comp.is_scalar_tower /-- If `R` and `R'` are isomorphic rings that act identically on a module `M`, then a basis for `M` as `R`-module is also a basis for `M` as `R'`-module. See also `basis.algebra_map_coeffs` for the case where `f` is equal to `algebra_map`. -/ @[simps {simp_rhs := tt}] def map_coeffs : basis ι R' M := begin letI : module R' R := module.comp_hom R (↑f.symm : R' →+* R), haveI : is_scalar_tower R' R M := { smul_assoc := λ x y z, begin dsimp [(•)], rw [mul_smul, ←h, f.apply_symm_apply], end }, exact (of_repr $ (b.repr.restrict_scalars R').trans $ finsupp.map_range.linear_equiv (module.comp_hom.to_linear_equiv f.symm).symm ) end lemma map_coeffs_apply (i : ι) : b.map_coeffs f h i = b i := apply_eq_iff.mpr $ by simp [f.to_add_equiv_eq_coe] @[simp] lemma coe_map_coeffs : (b.map_coeffs f h : ι → M) = b := funext $ b.map_coeffs_apply f h end map_coeffs section reindex variables (b' : basis ι' R M') variables (e : ι ≃ ι') /-- `b.reindex (e : ι ≃ ι')` is a basis indexed by `ι'` -/ def reindex : basis ι' R M := basis.of_repr (b.repr.trans (finsupp.dom_lcongr e)) lemma reindex_apply (i' : ι') : b.reindex e i' = b (e.symm i') := show (b.repr.trans (finsupp.dom_lcongr e)).symm (finsupp.single i' 1) = b.repr.symm (finsupp.single (e.symm i') 1), by rw [linear_equiv.symm_trans_apply, finsupp.dom_lcongr_symm, finsupp.dom_lcongr_single] @[simp] lemma coe_reindex : (b.reindex e : ι' → M) = b ∘ e.symm := funext (b.reindex_apply e) @[simp] lemma coe_reindex_repr : ((b.reindex e).repr x : ι' → R) = b.repr x ∘ e.symm := funext $ λ i', show (finsupp.dom_lcongr e : _ ≃ₗ[R] _) (b.repr x) i' = _, by simp @[simp] lemma reindex_repr (i' : ι') : (b.reindex e).repr x i' = b.repr x (e.symm i') := by rw coe_reindex_repr @[simp] lemma reindex_refl : b.reindex (equiv.refl ι) = b := eq_of_apply_eq $ λ i, by simp /-- `simp` normal form version of `range_reindex` -/ @[simp] lemma range_reindex' : set.range (b ∘ e.symm) = set.range b := by rw [range_comp, equiv.range_eq_univ, set.image_univ] lemma range_reindex : set.range (b.reindex e) = set.range b := by rw [coe_reindex, range_reindex'] /-- `b.reindex_range` is a basis indexed by `range b`, the basis vectors themselves. -/ def reindex_range : basis (range b) R M := if h : nontrivial R then by letI := h; exact b.reindex (equiv.of_injective b (basis.injective b)) else by letI : subsingleton R := not_nontrivial_iff_subsingleton.mp h; exact basis.of_repr (module.subsingleton_equiv R M (range b)) lemma finsupp.single_apply_left {α β γ : Type*} [has_zero γ] {f : α → β} (hf : function.injective f) (x z : α) (y : γ) : finsupp.single (f x) y (f z) = finsupp.single x y z := by simp [finsupp.single_apply, hf.eq_iff] lemma reindex_range_self (i : ι) (h := set.mem_range_self i) : b.reindex_range ⟨b i, h⟩ = b i := begin by_cases htr : nontrivial R, { letI := htr, simp [htr, reindex_range, reindex_apply, equiv.apply_of_injective_symm b.injective, subtype.coe_mk] }, { letI : subsingleton R := not_nontrivial_iff_subsingleton.mp htr, letI := module.subsingleton R M, simp [reindex_range] } end lemma reindex_range_repr_self (i : ι) : b.reindex_range.repr (b i) = finsupp.single ⟨b i, mem_range_self i⟩ 1 := calc b.reindex_range.repr (b i) = b.reindex_range.repr (b.reindex_range ⟨b i, mem_range_self i⟩) : congr_arg _ (b.reindex_range_self _ _).symm ... = finsupp.single ⟨b i, mem_range_self i⟩ 1 : b.reindex_range.repr_self _ @[simp] lemma reindex_range_apply (x : range b) : b.reindex_range x = x := by { rcases x with ⟨bi, ⟨i, rfl⟩⟩, exact b.reindex_range_self i, } lemma reindex_range_repr' (x : M) {bi : M} {i : ι} (h : b i = bi) : b.reindex_range.repr x ⟨bi, ⟨i, h⟩⟩ = b.repr x i := begin nontriviality, subst h, refine (b.repr_apply_eq (λ x i, b.reindex_range.repr x ⟨b i, _⟩) _ _ _ x i).symm, { intros x y, ext i, simp only [pi.add_apply, linear_equiv.map_add, finsupp.coe_add] }, { intros c x, ext i, simp only [pi.smul_apply, linear_equiv.map_smul, finsupp.coe_smul] }, { intros i, ext j, simp only [reindex_range_repr_self], refine @finsupp.single_apply_left _ _ _ _ (λ i, (⟨b i, _⟩ : set.range b)) _ _ _ _, exact λ i j h, b.injective (subtype.mk.inj h) } end @[simp] lemma reindex_range_repr (x : M) (i : ι) (h := set.mem_range_self i) : b.reindex_range.repr x ⟨b i, h⟩ = b.repr x i := b.reindex_range_repr' _ rfl section fintype variables [fintype ι] /-- `b.reindex_finset_range` is a basis indexed by `finset.univ.image b`, the finite set of basis vectors themselves. -/ def reindex_finset_range : basis (finset.univ.image b) R M := b.reindex_range.reindex ((equiv.refl M).subtype_equiv (by simp)) lemma reindex_finset_range_self (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range ⟨b i, h⟩ = b i := by { rw [reindex_finset_range, reindex_apply, reindex_range_apply], refl } @[simp] lemma reindex_finset_range_apply (x : finset.univ.image b) : b.reindex_finset_range x = x := by { rcases x with ⟨bi, hbi⟩, rcases finset.mem_image.mp hbi with ⟨i, -, rfl⟩, exact b.reindex_finset_range_self i } lemma reindex_finset_range_repr_self (i : ι) : b.reindex_finset_range.repr (b i) = finsupp.single ⟨b i, finset.mem_image_of_mem b (finset.mem_univ i)⟩ 1 := begin ext ⟨bi, hbi⟩, rw [reindex_finset_range, reindex_repr, reindex_range_repr_self], convert finsupp.single_apply_left ((equiv.refl M).subtype_equiv _).symm.injective _ _ _, refl end @[simp] lemma reindex_finset_range_repr (x : M) (i : ι) (h := finset.mem_image_of_mem b (finset.mem_univ i)) : b.reindex_finset_range.repr x ⟨b i, h⟩ = b.repr x i := by simp [reindex_finset_range] end fintype end reindex protected lemma linear_independent : linear_independent R b := linear_independent_iff.mpr $ λ l hl, calc l = b.repr (finsupp.total _ _ _ b l) : (b.repr_total l).symm ... = 0 : by rw [hl, linear_equiv.map_zero] protected lemma ne_zero [nontrivial R] (i) : b i ≠ 0 := b.linear_independent.ne_zero i protected lemma mem_span (x : M) : x ∈ span R (range b) := by { rw [← b.total_repr x, finsupp.total_apply, finsupp.sum], exact submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ (submodule.subset_span ⟨i, rfl⟩)) } protected lemma span_eq : span R (range b) = ⊤ := eq_top_iff.mpr $ λ x _, b.mem_span x lemma index_nonempty (b : basis ι R M) [nontrivial M] : nonempty ι := begin obtain ⟨x, y, ne⟩ : ∃ (x y : M), x ≠ y := nontrivial.exists_pair_ne, obtain ⟨i, _⟩ := not_forall.mp (mt b.ext_elem ne), exact ⟨i⟩ end section constr variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] /-- Construct a linear map given the value at the basis. This definition is parameterized over an extra `semiring S`, such that `smul_comm_class R S M'` holds. If `R` is commutative, you can set `S := R`; if `R` is not commutative, you can recover an `add_equiv` by setting `S := ℕ`. See library note [bundled maps over different rings]. -/ def constr : (ι → M') ≃ₗ[S] (M →ₗ[R] M') := { to_fun := λ f, (finsupp.total M' M' R id).comp $ (finsupp.lmap_domain R R f) ∘ₗ ↑b.repr, inv_fun := λ f i, f (b i), left_inv := λ f, by { ext, simp }, right_inv := λ f, by { refine b.ext (λ i, _), simp }, map_add' := λ f g, by { refine b.ext (λ i, _), simp }, map_smul' := λ c f, by { refine b.ext (λ i, _), simp } } theorem constr_def (f : ι → M') : b.constr S f = (finsupp.total M' M' R id) ∘ₗ ((finsupp.lmap_domain R R f) ∘ₗ ↑b.repr) := rfl theorem constr_apply (f : ι → M') (x : M) : b.constr S f x = (b.repr x).sum (λ b a, a • f b) := by { simp only [constr_def, linear_map.comp_apply, finsupp.lmap_domain_apply, finsupp.total_apply], rw finsupp.sum_map_domain_index; simp [add_smul] } @[simp] lemma constr_basis (f : ι → M') (i : ι) : (b.constr S f : M → M') (b i) = f i := by simp [basis.constr_apply, b.repr_self] lemma constr_eq {g : ι → M'} {f : M →ₗ[R] M'} (h : ∀i, g i = f (b i)) : b.constr S g = f := b.ext $ λ i, (b.constr_basis S g i).trans (h i) lemma constr_self (f : M →ₗ[R] M') : b.constr S (λ i, f (b i)) = f := b.constr_eq S $ λ x, rfl lemma constr_range [nonempty ι] {f : ι → M'} : (b.constr S f).range = span R (range f) := by rw [b.constr_def S f, linear_map.range_comp, linear_map.range_comp, linear_equiv.range, ← finsupp.supported_univ, finsupp.lmap_domain_supported, ←set.image_univ, ← finsupp.span_image_eq_map_total, set.image_id] @[simp] lemma constr_comp (f : M' →ₗ[R] M') (v : ι → M') : b.constr S (f ∘ v) = f.comp (b.constr S v) := b.ext (λ i, by simp only [basis.constr_basis, linear_map.comp_apply]) end constr section equiv variables (b' : basis ι' R M') (e : ι ≃ ι') variables [add_comm_monoid M''] [module R M''] /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and the index types are equivalent, `b.equiv b' e` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `b' (e i)`. -/ protected def equiv : M ≃ₗ[R] M' := b.repr.trans (b'.reindex e.symm).repr.symm @[simp] lemma equiv_apply : b.equiv b' e (b i) = b' (e i) := by simp [basis.equiv] @[simp] lemma equiv_refl : b.equiv b (equiv.refl ι) = linear_equiv.refl R M := b.ext' (λ i, by simp) @[simp] lemma equiv_symm : (b.equiv b' e).symm = b'.equiv b e.symm := b'.ext' $ λ i, (b.equiv b' e).injective (by simp) @[simp] lemma equiv_trans {ι'' : Type*} (b'' : basis ι'' R M'') (e : ι ≃ ι') (e' : ι' ≃ ι'') : (b.equiv b' e).trans (b'.equiv b'' e') = b.equiv b'' (e.trans e') := b.ext' (λ i, by simp) @[simp] lemma map_equiv (b : basis ι R M) (b' : basis ι' R M') (e : ι ≃ ι') : b.map (b.equiv b' e) = b'.reindex e.symm := by { ext i, simp } end equiv section prod variables (b' : basis ι' R M') /-- `basis.prod` maps a `ι`-indexed basis for `M` and a `ι'`-indexed basis for `M'` to a `ι ⊕ ι'`-index basis for `M × M'`. For the specific case of `R × R`, see also `basis.fin_two_prod`. -/ protected def prod : basis (ι ⊕ ι') R (M × M') := of_repr ((b.repr.prod b'.repr).trans (finsupp.sum_finsupp_lequiv_prod_finsupp R).symm) @[simp] lemma prod_repr_inl (x) (i) : (b.prod b').repr x (sum.inl i) = b.repr x.1 i := rfl @[simp] lemma prod_repr_inr (x) (i) : (b.prod b').repr x (sum.inr i) = b'.repr x.2 i := rfl lemma prod_apply_inl_fst (i) : (b.prod b' (sum.inl i)).1 = b i := b.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inl_injective } lemma prod_apply_inr_fst (i) : (b.prod b' (sum.inr i)).1 = 0 := b.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.fst_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inr_ne_inl } lemma prod_apply_inl_snd (i) : (b.prod b' (sum.inl i)).2 = 0 := b'.repr.injective $ by { ext j, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp, linear_equiv.map_zero, finsupp.zero_apply], apply finsupp.single_eq_of_ne sum.inl_ne_inr } lemma prod_apply_inr_snd (i) : (b.prod b' (sum.inr i)).2 = b' i := b'.repr.injective $ by { ext i, simp only [basis.prod, basis.coe_of_repr, linear_equiv.symm_trans_apply, linear_equiv.prod_symm, linear_equiv.prod_apply, b'.repr.apply_symm_apply, linear_equiv.symm_symm, repr_self, equiv.to_fun_as_coe, finsupp.snd_sum_finsupp_lequiv_prod_finsupp], apply finsupp.single_apply_left sum.inr_injective } @[simp] lemma prod_apply (i) : b.prod b' i = sum.elim (linear_map.inl R M M' ∘ b) (linear_map.inr R M M' ∘ b') i := by { ext; cases i; simp only [prod_apply_inl_fst, sum.elim_inl, linear_map.inl_apply, prod_apply_inr_fst, sum.elim_inr, linear_map.inr_apply, prod_apply_inl_snd, prod_apply_inr_snd, comp_app] } end prod section no_zero_smul_divisors -- Can't be an instance because the basis can't be inferred. protected lemma no_zero_smul_divisors [no_zero_divisors R] (b : basis ι R M) : no_zero_smul_divisors R M := ⟨λ c x hcx, or_iff_not_imp_right.mpr (λ hx, begin rw [← b.total_repr x, ← linear_map.map_smul] at hcx, have := linear_independent_iff.mp b.linear_independent (c • b.repr x) hcx, rw smul_eq_zero at this, exact this.resolve_right (λ hr, hx (b.repr.map_eq_zero_iff.mp hr)) end)⟩ protected lemma smul_eq_zero [no_zero_divisors R] (b : basis ι R M) {c : R} {x : M} : c • x = 0 ↔ c = 0 ∨ x = 0 := @smul_eq_zero _ _ _ _ _ b.no_zero_smul_divisors _ _ lemma _root_.eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, finset.univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, convert (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end end no_zero_smul_divisors section singleton /-- `basis.singleton ι R` is the basis sending the unique element of `ι` to `1 : R`. -/ protected def singleton (ι R : Type*) [unique ι] [semiring R] : basis ι R R := of_repr { to_fun := λ x, finsupp.single default x, inv_fun := λ f, f default, left_inv := λ x, by simp, right_inv := λ f, finsupp.unique_ext (by simp), map_add' := λ x y, by simp, map_smul' := λ c x, by simp } @[simp] lemma singleton_apply (ι R : Type*) [unique ι] [semiring R] (i) : basis.singleton ι R i = 1 := apply_eq_iff.mpr (by simp [basis.singleton]) @[simp] lemma singleton_repr (ι R : Type*) [unique ι] [semiring R] (x i) : (basis.singleton ι R).repr x i = x := by simp [basis.singleton, unique.eq_default i] lemma basis_singleton_iff {R M : Type*} [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] (ι : Type*) [unique ι] : nonempty (basis ι R M) ↔ ∃ x ≠ 0, ∀ y : M, ∃ r : R, r • x = y := begin fsplit, { rintro ⟨b⟩, refine ⟨b default, b.linear_independent.ne_zero _, _⟩, simpa [span_singleton_eq_top_iff, set.range_unique] using b.span_eq }, { rintro ⟨x, nz, w⟩, refine ⟨of_repr $ linear_equiv.symm { to_fun := λ f, f default • x, inv_fun := λ y, finsupp.single default (w y).some, left_inv := λ f, finsupp.unique_ext _, right_inv := λ y, _, map_add' := λ y z, _, map_smul' := λ c y, _ }⟩, { rw [finsupp.add_apply, add_smul] }, { rw [finsupp.smul_apply, smul_assoc], simp }, { refine smul_left_injective _ nz _, simp only [finsupp.single_eq_same], exact (w (f default • x)).some_spec }, { simp only [finsupp.single_eq_same], exact (w y).some_spec } } end end singleton section empty variables (M) /-- If `M` is a subsingleton and `ι` is empty, this is the unique `ι`-indexed basis for `M`. -/ protected def empty [subsingleton M] [is_empty ι] : basis ι R M := of_repr 0 instance empty_unique [subsingleton M] [is_empty ι] : unique (basis ι R M) := { default := basis.empty M, uniq := λ ⟨x⟩, congr_arg of_repr $ subsingleton.elim _ _ } end empty end basis section fintype open basis open fintype variables [fintype ι] (b : basis ι R M) /-- A module over `R` with a finite basis is linearly equivalent to functions from its basis to `R`. -/ def basis.equiv_fun : M ≃ₗ[R] (ι → R) := linear_equiv.trans b.repr ({ to_fun := coe_fn, map_add' := finsupp.coe_add, map_smul' := finsupp.coe_smul, ..finsupp.equiv_fun_on_fintype } : (ι →₀ R) ≃ₗ[R] (ι → R)) /-- A module over a finite ring that admits a finite basis is finite. -/ def module.fintype_of_fintype [fintype R] : fintype M := fintype.of_equiv _ b.equiv_fun.to_equiv.symm theorem module.card_fintype [fintype R] [fintype M] : card M = (card R) ^ (card ι) := calc card M = card (ι → R) : card_congr b.equiv_fun.to_equiv ... = card R ^ card ι : card_fun /-- Given a basis `v` indexed by `ι`, the canonical linear equivalence between `ι → R` and `M` maps a function `x : ι → R` to the linear combination `∑_i x i • v i`. -/ @[simp] lemma basis.equiv_fun_symm_apply (x : ι → R) : b.equiv_fun.symm x = ∑ i, x i • b i := by simp [basis.equiv_fun, finsupp.total_apply, finsupp.sum_fintype] @[simp] lemma basis.equiv_fun_apply (u : M) : b.equiv_fun u = b.repr u := rfl @[simp] lemma basis.map_equiv_fun (f : M ≃ₗ[R] M') : (b.map f).equiv_fun = f.symm.trans b.equiv_fun := rfl lemma basis.sum_equiv_fun (u : M) : ∑ i, b.equiv_fun u i • b i = u := begin conv_rhs { rw ← b.total_repr u }, simp [finsupp.total_apply, finsupp.sum_fintype, b.equiv_fun_apply] end lemma basis.sum_repr (u : M) : ∑ i, b.repr u i • b i = u := b.sum_equiv_fun u @[simp] lemma basis.equiv_fun_self (i j : ι) : b.equiv_fun (b i) j = if i = j then 1 else 0 := by { rw [b.equiv_fun_apply, b.repr_self_apply] } /-- Define a basis by mapping each vector `x : M` to its coordinates `e x : ι → R`, as long as `ι` is finite. -/ def basis.of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : basis ι R M := basis.of_repr $ e.trans $ linear_equiv.symm $ finsupp.linear_equiv_fun_on_fintype R R ι @[simp] lemma basis.of_equiv_fun_repr_apply (e : M ≃ₗ[R] (ι → R)) (x : M) (i : ι) : (basis.of_equiv_fun e).repr x i = e x i := rfl @[simp] lemma basis.coe_of_equiv_fun (e : M ≃ₗ[R] (ι → R)) : (basis.of_equiv_fun e : ι → M) = λ i, e.symm (function.update 0 i 1) := funext $ λ i, e.injective $ funext $ λ j, by simp [basis.of_equiv_fun, ←finsupp.single_eq_pi_single, finsupp.single_eq_update] @[simp] lemma basis.of_equiv_fun_equiv_fun (v : basis ι R M) : basis.of_equiv_fun v.equiv_fun = v := begin ext j, simp only [basis.equiv_fun_symm_apply, basis.coe_of_equiv_fun], simp_rw [function.update_apply, ite_smul], simp only [finset.mem_univ, if_true, pi.zero_apply, one_smul, finset.sum_ite_eq', zero_smul], end variables (S : Type*) [semiring S] [module S M'] variables [smul_comm_class R S M'] @[simp] theorem basis.constr_apply_fintype (f : ι → M') (x : M) : (b.constr S f : M → M') x = ∑ i, (b.equiv_fun x i) • f i := by simp [b.constr_apply, b.equiv_fun_apply, finsupp.sum_fintype] end fintype end module section comm_semiring namespace basis variables [comm_semiring R] variables [add_comm_monoid M] [module R M] [add_comm_monoid M'] [module R M'] variables (b : basis ι R M) (b' : basis ι' R M') /-- If `b` is a basis for `M` and `b'` a basis for `M'`, and `f`, `g` form a bijection between the basis vectors, `b.equiv' b' f g hf hg hgf hfg` is a linear equivalence `M ≃ₗ[R] M'`, mapping `b i` to `f (b i)`. -/ def equiv' (f : M → M') (g : M' → M) (hf : ∀ i, f (b i) ∈ range b') (hg : ∀ i, g (b' i) ∈ range b) (hgf : ∀i, g (f (b i)) = b i) (hfg : ∀i, f (g (b' i)) = b' i) : M ≃ₗ[R] M' := { inv_fun := b'.constr R (g ∘ b'), left_inv := have (b'.constr R (g ∘ b')).comp (b.constr R (f ∘ b)) = linear_map.id, from (b.ext $ λ i, exists.elim (hf i) (λ i' hi', by rw [linear_map.comp_apply, b.constr_basis, function.comp_apply, ← hi', b'.constr_basis, function.comp_apply, hi', hgf, linear_map.id_apply])), λ x, congr_arg (λ (h : M →ₗ[R] M), h x) this, right_inv := have (b.constr R (f ∘ b)).comp (b'.constr R (g ∘ b')) = linear_map.id, from (b'.ext $ λ i, exists.elim (hg i) (λ i' hi', by rw [linear_map.comp_apply, b'.constr_basis, function.comp_apply, ← hi', b.constr_basis, function.comp_apply, hi', hfg, linear_map.id_apply])), λ x, congr_arg (λ (h : M' →ₗ[R] M'), h x) this, .. b.constr R (f ∘ b) } @[simp] lemma equiv'_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι) : b.equiv' b' f g hf hg hgf hfg (b i) = f (b i) := b.constr_basis R _ _ @[simp] lemma equiv'_symm_apply (f : M → M') (g : M' → M) (hf hg hgf hfg) (i : ι') : (b.equiv' b' f g hf hg hgf hfg).symm (b' i) = g (b' i) := b'.constr_basis R _ _ lemma sum_repr_mul_repr {ι'} [fintype ι'] (b' : basis ι' R M) (x : M) (i : ι) : ∑ (j : ι'), b.repr (b' j) i * b'.repr x j = b.repr x i := begin conv_rhs { rw [← b'.sum_repr x] }, simp_rw [linear_equiv.map_sum, linear_equiv.map_smul, finset.sum_apply'], refine finset.sum_congr rfl (λ j _, _), rw [finsupp.smul_apply, smul_eq_mul, mul_comm] end end basis end comm_semiring section module open linear_map variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {c d : R} {x y : M} variables (b : basis ι R M) namespace basis /-- Any basis is a maximal linear independent set. -/ lemma maximal [nontrivial R] (b : basis ι R M) : b.linear_independent.maximal := λ w hi h, begin -- If `range w` is strictly bigger than `range b`, apply le_antisymm h, -- then choose some `x ∈ range w \ range b`, intros x p, by_contradiction q, -- and write it in terms of the basis. have e := b.total_repr x, -- This then expresses `x` as a linear combination -- of elements of `w` which are in the range of `b`, let u : ι ↪ w := ⟨λ i, ⟨b i, h ⟨i, rfl⟩⟩, λ i i' r, b.injective (by simpa only [subtype.mk_eq_mk] using r)⟩, have r : ∀ i, b i = u i := λ i, rfl, simp_rw [finsupp.total_apply, r] at e, change (b.repr x).sum (λ (i : ι) (a : R), (λ (x : w) (r : R), r • (x : M)) (u i) a) = ((⟨x, p⟩ : w) : M) at e, rw [←finsupp.sum_emb_domain, ←finsupp.total_apply] at e, -- Now we can contradict the linear independence of `hi` refine hi.total_ne_of_not_mem_support _ _ e, simp only [finset.mem_map, finsupp.support_emb_domain], rintro ⟨j, -, W⟩, simp only [embedding.coe_fn_mk, subtype.mk_eq_mk, ←r] at W, apply q ⟨j, W⟩, end section mk variables (hli : linear_independent R v) (hsp : span R (range v) = ⊤) /-- A linear independent family of vectors spanning the whole module is a basis. -/ protected noncomputable def mk : basis ι R M := basis.of_repr { inv_fun := finsupp.total _ _ _ v, left_inv := λ x, hli.total_repr ⟨x, _⟩, right_inv := λ x, hli.repr_eq rfl, .. hli.repr.comp (linear_map.id.cod_restrict _ (λ h, hsp.symm ▸ submodule.mem_top)) } @[simp] lemma mk_repr : (basis.mk hli hsp).repr x = hli.repr ⟨x, hsp.symm ▸ submodule.mem_top⟩ := rfl lemma mk_apply (i : ι) : basis.mk hli hsp i = v i := show finsupp.total _ _ _ v _ = v i, by simp @[simp] lemma coe_mk : ⇑(basis.mk hli hsp) = v := funext (mk_apply _ _) variables {hli hsp} /-- Given a basis, the `i`th element of the dual basis evaluates to 1 on the `i`th element of the basis. -/ lemma mk_coord_apply_eq (i : ι) : (basis.mk hli hsp).coord i (v i) = 1 := show hli.repr ⟨v i, submodule.subset_span (mem_range_self i)⟩ i = 1, by simp [hli.repr_eq_single i] /-- Given a basis, the `i`th element of the dual basis evaluates to 0 on the `j`th element of the basis if `j ≠ i`. -/ lemma mk_coord_apply_ne {i j : ι} (h : j ≠ i) : (basis.mk hli hsp).coord i (v j) = 0 := show hli.repr ⟨v j, submodule.subset_span (mem_range_self j)⟩ i = 0, by simp [hli.repr_eq_single j, h] /-- Given a basis, the `i`th element of the dual basis evaluates to the Kronecker delta on the `j`th element of the basis. -/ lemma mk_coord_apply {i j : ι} : (basis.mk hli hsp).coord i (v j) = if j = i then 1 else 0 := begin cases eq_or_ne j i, { simp only [h, if_true, eq_self_iff_true, mk_coord_apply_eq i], }, { simp only [h, if_false, mk_coord_apply_ne h], }, end end mk section span variables (hli : linear_independent R v) /-- A linear independent family of vectors is a basis for their span. -/ protected noncomputable def span : basis ι R (span R (range v)) := basis.mk (linear_independent_span hli) $ begin rw eq_top_iff, intros x _, have h₁ : (coe : span R (range v) → M) '' set.range (λ i, subtype.mk (v i) _) = range v, { rw ← set.range_comp, refl }, have h₂ : map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))) = span R (range v), { rw [← span_image, submodule.coe_subtype, h₁] }, have h₃ : (x : M) ∈ map (submodule.subtype _) (span R (set.range (λ i, subtype.mk (v i) _))), { rw h₂, apply subtype.mem x }, rcases mem_map.1 h₃ with ⟨y, hy₁, hy₂⟩, have h_x_eq_y : x = y, { rw [subtype.ext_iff, ← hy₂], simp }, rwa h_x_eq_y end end span lemma group_smul_span_eq_top {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → G} : submodule.span R (set.range (w • v)) = ⊤ := begin rw eq_top_iff, intros j hj, rw ← hv at hj, rw submodule.mem_span at hj ⊢, refine λ p hp, hj p (λ u hu, _), obtain ⟨i, rfl⟩ := hu, have : ((w i)⁻¹ • 1 : R) • w i • v i ∈ p := p.smul_mem ((w i)⁻¹ • 1 : R) (hp ⟨i, rfl⟩), rwa [smul_one_smul, inv_smul_smul] at this, end /-- Given a basis `v` and a map `w` such that for all `i`, `w i` are elements of a group, `group_smul` provides the basis corresponding to `w • v`. -/ def group_smul {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] (v : basis ι R M) (w : ι → G) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq) lemma group_smul_apply {G : Type*} [group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : basis ι R M} {w : ι → G} (i : ι) : v.group_smul w i = (w • v : ι → M) i := mk_apply (v.linear_independent.group_smul w) (group_smul_span_eq_top v.span_eq) i lemma units_smul_span_eq_top {v : ι → M} (hv : submodule.span R (set.range v) = ⊤) {w : ι → Rˣ} : submodule.span R (set.range (w • v)) = ⊤ := group_smul_span_eq_top hv /-- Given a basis `v` and a map `w` such that for all `i`, `w i` is a unit, `smul_of_is_unit` provides the basis corresponding to `w • v`. -/ def units_smul (v : basis ι R M) (w : ι → Rˣ) : basis ι R M := @basis.mk ι R M (w • v) _ _ _ (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq) lemma units_smul_apply {v : basis ι R M} {w : ι → Rˣ} (i : ι) : v.units_smul w i = w i • v i := mk_apply (v.linear_independent.units_smul w) (units_smul_span_eq_top v.span_eq) i /-- A version of `smul_of_units` that uses `is_unit`. -/ def is_unit_smul (v : basis ι R M) {w : ι → R} (hw : ∀ i, is_unit (w i)): basis ι R M := units_smul v (λ i, (hw i).unit) lemma is_unit_smul_apply {v : basis ι R M} {w : ι → R} (hw : ∀ i, is_unit (w i)) (i : ι) : v.is_unit_smul hw i = w i • v i := units_smul_apply i section fin /-- Let `b` be a basis for a submodule `N` of `M`. If `y : M` is linear independent of `N` and `y` and `N` together span the whole of `M`, then there is a basis for `M` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R M := have span_b : submodule.span R (set.range (N.subtype ∘ b)) = N, { rw [set.range_comp, submodule.span_image, b.span_eq, submodule.map_subtype_top] }, @basis.mk _ _ _ (fin.cons y (N.subtype ∘ b) : fin (n + 1) → M) _ _ _ ((b.linear_independent.map' N.subtype (submodule.ker_subtype _)) .fin_cons' _ _ $ by { rintros c ⟨x, hx⟩ hc, rw span_b at hx, exact hli c x hx hc }) (eq_top_iff.mpr (λ x _, by { rw [fin.range_cons, submodule.mem_span_insert', span_b], exact hsp x })) @[simp] lemma coe_mk_fin_cons {n : ℕ} {N : submodule R M} (y : M) (b : basis (fin n) R N) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z : M), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons y b hli hsp : fin (n + 1) → M) = fin.cons y (coe ∘ b) := coe_mk _ _ /-- Let `b` be a basis for a submodule `N ≤ O`. If `y ∈ O` is linear independent of `N` and `y` and `N` together span the whole of `O`, then there is a basis for `O` whose basis vectors are given by `fin.cons y b`. -/ noncomputable def mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : basis (fin (n + 1)) R O := mk_fin_cons ⟨y, yO⟩ (b.map (submodule.comap_subtype_equiv_of_le hNO).symm) (λ c x hc hx, hli c x (submodule.mem_comap.mp hc) (congr_arg coe hx)) (λ z, hsp z z.2) @[simp] lemma coe_mk_fin_cons_of_le {n : ℕ} {N O : submodule R M} (y : M) (yO : y ∈ O) (b : basis (fin n) R N) (hNO : N ≤ O) (hli : ∀ (c : R) (x ∈ N), c • y + x = 0 → c = 0) (hsp : ∀ (z ∈ O), ∃ (c : R), z + c • y ∈ N) : (mk_fin_cons_of_le y yO b hNO hli hsp : fin (n + 1) → O) = fin.cons ⟨y, yO⟩ (submodule.of_le hNO ∘ b) := coe_mk_fin_cons _ _ _ _ /-- The basis of `R × R` given by the two vectors `(1, 0)` and `(0, 1)`. -/ protected def fin_two_prod (R : Type*) [semiring R] : basis (fin 2) R (R × R) := basis.of_equiv_fun (linear_equiv.fin_two_arrow R R).symm @[simp] lemma fin_two_prod_zero (R : Type*) [semiring R] : basis.fin_two_prod R 0 = (1, 0) := by simp [basis.fin_two_prod] @[simp] lemma fin_two_prod_one (R : Type*) [semiring R] : basis.fin_two_prod R 1 = (0, 1) := by simp [basis.fin_two_prod] @[simp] lemma coe_fin_two_prod_repr {R : Type*} [semiring R] (x : R × R) : ⇑((basis.fin_two_prod R).repr x) = ![x.fst, x.snd] := rfl end fin end basis end module section induction variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, nat.le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end end induction section division_ring variables [division_ring K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule namespace basis section exists_basis /-- If `s` is a linear independent set of vectors, we can extend it to a basis. -/ noncomputable def extend (hs : linear_independent K (coe : s → V)) : basis _ K V := basis.mk (@linear_independent.restrict_of_comp_subtype _ _ _ id _ _ _ _ (hs.linear_independent_extend _)) (eq_top_iff.mpr $ set_like.coe_subset_coe.mp $ by simpa using hs.subset_span_extend (subset_univ s)) lemma extend_apply_self (hs : linear_independent K (coe : s → V)) (x : hs.extend _) : basis.extend hs x = x := basis.mk_apply _ _ _ @[simp] lemma coe_extend (hs : linear_independent K (coe : s → V)) : ⇑(basis.extend hs) = coe := funext (extend_apply_self hs) lemma range_extend (hs : linear_independent K (coe : s → V)) : range (basis.extend hs) = hs.extend (subset_univ _) := by rw [coe_extend, subtype.range_coe_subtype, set_of_mem_eq] /-- If `v` is a linear independent family of vectors, extend it to a basis indexed by a sum type. -/ noncomputable def sum_extend (hs : linear_independent K v) : basis (ι ⊕ _) K V := let s := set.range v, e : ι ≃ s := equiv.of_injective v hs.injective, b := hs.to_subtype_range.extend (subset_univ (set.range v)) in (basis.extend hs.to_subtype_range).reindex $ equiv.symm $ calc ι ⊕ (b \ s : set V) ≃ s ⊕ (b \ s : set V) : equiv.sum_congr e (equiv.refl _) ... ≃ b : equiv.set.sum_diff_subset (hs.to_subtype_range.subset_extend _) lemma subset_extend {s : set V} (hs : linear_independent K (coe : s → V)) : s ⊆ hs.extend (set.subset_univ _) := hs.subset_extend _ section variables (K V) /-- A set used to index `basis.of_vector_space`. -/ noncomputable def of_vector_space_index : set V := (linear_independent_empty K V).extend (subset_univ _) /-- Each vector space has a basis. -/ noncomputable def of_vector_space : basis (of_vector_space_index K V) K V := basis.extend (linear_independent_empty K V) lemma of_vector_space_apply_self (x : of_vector_space_index K V) : of_vector_space K V x = x := basis.mk_apply _ _ _ @[simp] lemma coe_of_vector_space : ⇑(of_vector_space K V) = coe := funext (λ x, of_vector_space_apply_self K V x) lemma of_vector_space_index.linear_independent : linear_independent K (coe : of_vector_space_index K V → V) := by { convert (of_vector_space K V).linear_independent, ext x, rw of_vector_space_apply_self } lemma range_of_vector_space : range (of_vector_space K V) = of_vector_space_index K V := range_extend _ lemma exists_basis : ∃ s : set V, nonempty (basis s K V) := ⟨of_vector_space_index K V, ⟨of_vector_space K V⟩⟩ end end exists_basis end basis open fintype variables (K V) theorem vector_space.card_fintype [fintype K] [fintype V] : ∃ n : ℕ, card V = (card K) ^ n := ⟨card (basis.of_vector_space_index K V), module.card_fintype (basis.of_vector_space K V)⟩ end division_ring section field variables [field K] [add_comm_group V] [add_comm_group V'] [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} lemma linear_map.exists_left_inverse_of_injective (f : V →ₗ[K] V') (hf_inj : f.ker = ⊥) : ∃g:V' →ₗ[K] V, g.comp f = linear_map.id := begin let B := basis.of_vector_space_index K V, let hB := basis.of_vector_space K V, have hB₀ : _ := hB.linear_independent.to_subtype_range, have : linear_independent K (λ x, x : f '' B → V'), { have h₁ : linear_independent K (λ (x : ↥(⇑f '' range (basis.of_vector_space _ _))), ↑x) := @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ f hB₀ (show disjoint _ _, by simp [hf_inj]), rwa [basis.range_of_vector_space K V] at h₁ }, let C := this.extend (subset_univ _), have BC := this.subset_extend (subset_univ _), let hC := basis.extend this, haveI : inhabited V := ⟨0⟩, refine ⟨hC.constr K (C.restrict (inv_fun f)), hB.ext (λ b, _)⟩, rw image_subset_iff at BC, have fb_eq : f b = hC ⟨f b, BC b.2⟩, { change f b = basis.extend this _, rw [basis.extend_apply_self, subtype.coe_mk] }, dsimp [hB], rw [basis.of_vector_space_apply_self, fb_eq, hC.constr_basis], exact left_inverse_inv_fun (linear_map.ker_eq_bot.1 hf_inj) _ end lemma submodule.exists_is_compl (p : submodule K V) : ∃ q : submodule K V, is_compl p q := let ⟨f, hf⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ instance module.submodule.is_complemented : is_complemented (submodule K V) := ⟨submodule.exists_is_compl⟩ lemma linear_map.exists_right_inverse_of_surjective (f : V →ₗ[K] V') (hf_surj : f.range = ⊤) : ∃g:V' →ₗ[K] V, f.comp g = linear_map.id := begin let C := basis.of_vector_space_index K V', let hC := basis.of_vector_space K V', haveI : inhabited V := ⟨0⟩, use hC.constr K (C.restrict (inv_fun f)), refine hC.ext (λ c, _), rw [linear_map.comp_apply, hC.constr_basis], simp [right_inverse_inv_fun (linear_map.range_eq_top.1 hf_surj) c] end /-- Any linear map `f : p →ₗ[K] V'` defined on a subspace `p` can be extended to the whole space. -/ lemma linear_map.exists_extend {p : submodule K V} (f : p →ₗ[K] V') : ∃ g : V →ₗ[K] V', g.comp p.subtype = f := let ⟨g, hg⟩ := p.subtype.exists_left_inverse_of_injective p.ker_subtype in ⟨f.comp g, by rw [linear_map.comp_assoc, hg, f.comp_id]⟩ open submodule linear_map /-- If `p < ⊤` is a subspace of a vector space `V`, then there exists a nonzero linear map `f : V →ₗ[K] K` such that `p ≤ ker f`. -/ lemma submodule.exists_le_ker_of_lt_top (p : submodule K V) (hp : p < ⊤) : ∃ f ≠ (0 : V →ₗ[K] K), p ≤ ker f := begin rcases set_like.exists_of_lt hp with ⟨v, -, hpv⟩, clear hp, rcases (linear_pmap.sup_span_singleton ⟨p, 0⟩ v (1 : K) hpv).to_fun.exists_extend with ⟨f, hf⟩, refine ⟨f, _, _⟩, { rintro rfl, rw [linear_map.zero_comp] at hf, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv 0 p.zero_mem 1, simpa using (linear_map.congr_fun hf _).trans this }, { refine λ x hx, mem_ker.2 _, have := linear_pmap.sup_span_singleton_apply_mk ⟨p, 0⟩ v (1 : K) hpv x hx 0, simpa using (linear_map.congr_fun hf _).trans this } end theorem quotient_prod_linear_equiv (p : submodule K V) : nonempty (((V ⧸ p) × p) ≃ₗ[K] V) := let ⟨q, hq⟩ := p.exists_is_compl in nonempty.intro $ ((quotient_equiv_of_is_compl p q hq).prod (linear_equiv.refl _ _)).trans (prod_equiv_of_is_compl q p hq.symm) end field
5d88d34a9616b6d309793f1e153c8310f2de7a09
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/pnat/xgcd.lean
1b8b380488e1f75a629cac12af91db94217944c9
[ "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
13,399
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Neil Strickland This file sets up a version of the Euclidean algorithm that works only with natural numbers. Given a, b > 0, it computes the unique system (w, x, y, z, d) such that the following identities hold: w * z = x * y + 1 a = (w + x) d b = (y + z) d These equations force w, z, d > 0. They also imply that the integers a' = w + x = a / d and b' = y + z = b / d are coprime, and that d is the gcd of a and b. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. -/ import tactic.ring import tactic.abel namespace pnat open nat pnat /-- A term of xgcd_type is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ @[derive inhabited] structure xgcd_type := (wp x y zp ap bp : ℕ) namespace xgcd_type variable (u : xgcd_type) instance : has_sizeof xgcd_type := ⟨λ u, u.bp⟩ /-- The has_repr instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : has_repr xgcd_type := ⟨λ u, "[[[" ++ (repr (u.wp + 1)) ++ ", " ++ (repr u.x) ++ "], [" ++ (repr u.y) ++ ", " ++ (repr (u.zp + 1)) ++ "]], [" ++ (repr (u.ap + 1)) ++ ", " ++ (repr (u.bp + 1)) ++ "]]"⟩ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : xgcd_type := mk w.val.pred x y z.val.pred a.val.pred b.val.pred def w : ℕ+ := succ_pnat u.wp def z : ℕ+ := succ_pnat u.zp def a : ℕ+ := succ_pnat u.ap def b : ℕ+ := succ_pnat u.bp def r : ℕ := (u.ap + 1) % (u.bp + 1) def q : ℕ := (u.ap + 1) / (u.bp + 1) def qp : ℕ := u.q - 1 /-- The map v gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map vp gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨ u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp ⟩ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by { ext; dsimp [v, vp, w, z, a, b, succ₂]; repeat { rw [nat.succ_eq_add_one] }; ring } /-- is_special holds if the matrix has determinant one. -/ def is_special : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y def is_special' : Prop := u.w * u.z = succ_pnat (u.x * u.y) theorem is_special_iff : u.is_special ↔ u.is_special' := begin dsimp [is_special, is_special'], split; intro h, { apply eq, dsimp [w, z, succ_pnat], rw [← h], repeat { rw [nat.succ_eq_add_one] }, ring }, { apply nat.succ_inj, replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [mul_coe, w, z] at h, repeat { rw [succ_pnat_coe, nat.succ_eq_add_one] at h }, repeat { rw [nat.succ_eq_add_one] }, rw [← h], ring } end /-- is_reduced holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def is_reduced : Prop := u.ap = u.bp def is_reduced' : Prop := u.a = u.b theorem is_reduced_iff : u.is_reduced ↔ u.is_reduced' := ⟨ congr_arg succ_pnat, succ_pnat_inj ⟩ def flip : xgcd_type := { wp := u.zp, x := u.y, y := u.x, zp := u.wp, ap := u.bp, bp := u.ap } @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_is_reduced : (flip u).is_reduced ↔ u.is_reduced := by { dsimp [is_reduced, flip], split; intro h; exact h.symm } theorem flip_is_special : (flip u).is_special ↔ u.is_special := by { dsimp [is_special, flip], rw[mul_comm u.x, mul_comm u.zp, add_comm u.zp] } theorem flip_v : (flip u).v = (u.v).swap := by { dsimp [v], ext, { simp only [], ring }, { simp only [], ring } } /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := begin by_cases hq : u.q = 0, { let h := u.rq_eq, rw [hr, hq, mul_zero, add_zero] at h, cases h }, { exact (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hq)).symm } end /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying is_reduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : xgcd_type := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_is_special (a b : ℕ+) : (start a b).is_special := by { dsimp [start, is_special], refl } theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := begin dsimp [start, v, xgcd_type.a, xgcd_type.b, w, z], rw [one_mul, one_mul, zero_mul, zero_mul, zero_add, add_zero], rw [← nat.pred_eq_sub_one, ← nat.pred_eq_sub_one], rw [nat.succ_pred_eq_of_pos a.pos, nat.succ_pred_eq_of_pos b.pos] end def finish : xgcd_type := xgcd_type.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_is_reduced : u.finish.is_reduced := by { dsimp [is_reduced], refl } theorem finish_is_special (hs : u.is_special) : u.finish.is_special := begin dsimp [is_special, finish] at hs ⊢, rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs], ring end theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, rw [hr, zero_add] at ha, ext, { change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b, have : u.wp + 1 = u.w := rfl, rw [this, ← ha, u.qp_eq hr], ring }, { change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b, rw [← ha, u.qp_eq hr], ring } end /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : xgcd_type := xgcd_type.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : sizeof u.step < sizeof u := begin change u.r - 1 < u.bp, have h₀ : (u.r - 1) + 1 = u.r := nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hr), have h₁ : u.r < u.bp + 1 := nat.mod_lt (u.ap + 1) u.bp.succ_pos, rw[← h₀] at h₁, exact lt_of_succ_lt_succ h₁, end theorem step_is_special (hs : u.is_special) : u.step.is_special := begin dsimp [is_special, step] at hs ⊢, rw [mul_add, mul_comm u.y u.x, ← hs], ring end /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = (u.v).swap := begin let ha : u.r + u.b * u.q = u.a := u.rq_eq, let hr : (u.r - 1) + 1 = u.r := (add_comm _ 1).trans (nat.add_sub_of_le (nat.pos_of_ne_zero hr)), ext, { change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b, rw [← ha, hr], ring }, { change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b, rw [← ha, hr], ring } end /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce : xgcd_type → xgcd_type | u := dite (u.r = 0) (λ h, u.finish) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, flip (reduce u.step)) theorem reduce_a {u : xgcd_type} (h : u.r = 0) : u.reduce = u.finish := by { rw [reduce], simp only [], rw [if_pos h] } theorem reduce_b {u : xgcd_type} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by { rw [reduce], simp only [], rw [if_neg h, step] } theorem reduce_reduced : ∀ (u : xgcd_type), u.reduce.is_reduced | u := dite (u.r = 0) (λ h, by { rw [reduce_a h], exact u.finish_is_reduced }) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h, flip_is_reduced], apply reduce_reduced }) theorem reduce_reduced' (u : xgcd_type) : u.reduce.is_reduced' := (is_reduced_iff _).mp u.reduce_reduced theorem reduce_special : ∀ (u : xgcd_type), u.is_special → u.reduce.is_special | u := dite (u.r = 0) (λ h hs, by { rw [reduce_a h], exact u.finish_is_special hs }) (λ h hs, have sizeof u.step < sizeof u, from u.step_wf h, by { rw [reduce_b h], let u' := u.step.reduce, have : u'.is_special := reduce_special u.step (u.step_is_special hs), exact (flip_is_special _).mpr (reduce_special _ (u.step_is_special hs)) }) theorem reduce_special' (u : xgcd_type) (hs : u.is_special) : u.reduce.is_special' := (is_special_iff _).mp (u.reduce_special hs) theorem reduce_v : ∀ (u : xgcd_type), u.reduce.v = u.v | u := dite (u.r = 0) (λ h, by {rw[reduce_a h, finish_v u h]}) (λ h, have sizeof u.step < sizeof u, from u.step_wf h, by { rw[reduce_b h, flip_v, reduce_v (step u), step_v u h, prod.swap_swap] }) end xgcd_type section gcd variables (a b : ℕ+) def xgcd: xgcd_type := (xgcd_type.start a b).reduce def gcd_d : ℕ+ := (xgcd a b).a def gcd_w : ℕ+ := (xgcd a b).w def gcd_x : ℕ := (xgcd a b).x def gcd_y : ℕ := (xgcd a b).y def gcd_z : ℕ+ := (xgcd a b).z def gcd_a' : ℕ+ := succ_pnat ((xgcd a b).wp + (xgcd a b).x) def gcd_b' : ℕ+ := succ_pnat ((xgcd a b).y + (xgcd a b).zp) theorem gcd_a'_coe : ((gcd_a' a b) : ℕ) = (gcd_w a b) + (gcd_x a b) := by { dsimp [gcd_a', gcd_w, xgcd_type.w], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_b'_coe : ((gcd_b' a b) : ℕ) = (gcd_y a b) + (gcd_z a b) := by { dsimp [gcd_b', gcd_z, xgcd_type.z], rw [nat.succ_eq_add_one, nat.succ_eq_add_one], ring } theorem gcd_props : let d := gcd_d a b, w := gcd_w a b, x := gcd_x a b, y := gcd_y a b, z := gcd_z a b, a' := gcd_a' a b, b' := gcd_b' a b in (w * z = succ_pnat (x * y) ∧ (a = a' * d) ∧ (b = b' * d) ∧ z * a' = succ_pnat (x * b') ∧ w * b' = succ_pnat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d ) := begin intros, let u := (xgcd_type.start a b), let ur := u.reduce, have ha : d = ur.a := rfl, have hb : d = ur.b := u.reduce_reduced', have ha' : (a' : ℕ) = w + x := gcd_a'_coe a b, have hb' : (b' : ℕ) = y + z := gcd_b'_coe a b, have hdet : w * z = succ_pnat (x * y) := u.reduce_special' rfl, split, exact hdet, have hdet' : ((w * z) : ℕ) = x * y + 1 := by { rw [← mul_coe, hdet, succ_pnat_coe] }, have huv : u.v = ⟨a, b⟩ := (xgcd_type.start_v a b), let hv : prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (xgcd_type.start_v a b), rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv, have ha'' : (a : ℕ) = a' * d := (congr_arg prod.fst hv).symm, have hb'' : (b : ℕ) = b' * d := (congr_arg prod.snd hv).symm, split, exact eq ha'', split, exact eq hb'', have hza' : (z * a' : ℕ) = x * b' + 1, by { rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'], ring }, have hwb' : (w * b' : ℕ) = y * a' + 1, by { rw [ha', hb', mul_add, mul_add, hdet'], ring }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hza'] }, split, { apply eq, rw [succ_pnat_coe, nat.succ_eq_add_one, mul_coe, hwb'] }, rw [ha'', hb''], repeat { rw [← mul_assoc] }, rw [hza', hwb'], split; ring, end theorem gcd_eq : gcd_d a b = gcd a b := begin rcases gcd_props a b with ⟨h₀, h₁, h₂, h₃, h₄, h₅, h₆⟩, apply dvd_antisymm, { apply dvd_gcd, exact dvd_intro (gcd_a' a b) (h₁.trans (mul_comm _ _)).symm, exact dvd_intro (gcd_b' a b) (h₂.trans (mul_comm _ _)).symm}, { have h₇ := calc ((gcd a b) : ℕ) ∣ a : nat.gcd_dvd_left a b ... ∣ (gcd_z a b) * a : dvd_mul_left _ _, have h₈ := calc ((gcd a b) : ℕ) ∣ b : nat.gcd_dvd_right a b ... ∣ (gcd_x a b) * b : dvd_mul_left _ _, rw[h₅] at h₇, exact (nat.dvd_add_iff_right h₈).mpr h₇} end theorem gcd_det_eq : (gcd_w a b) * (gcd_z a b) = succ_pnat ((gcd_x a b) * (gcd_y a b)) := (gcd_props a b).1 theorem gcd_a_eq : a = (gcd_a' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = (gcd_b' a b) * (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : (gcd_z a b) * (gcd_a' a b) = succ_pnat ((gcd_x a b) * (gcd_b' a b)) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : (gcd_w a b) * (gcd_b' a b) = succ_pnat ((gcd_y a b) * (gcd_a' a b)) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : ((gcd_z a b) * a : ℕ) = (gcd_x a b) * b + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : ((gcd_w a b) * b : ℕ) = (gcd_y a b) * a + (gcd a b) := (gcd_eq a b) ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end pnat
ae41695809a9d9f88923ab1b46cbfd12c9eb3cd9
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/basic_skills/unnamed_670.lean
bd6c68af167f87455c9062a9af2c50ee14043eda
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
233
lean
namespace my_ring variables {R : Type*} [ring R] -- BEGIN theorem mul_zero (a : R) : a * 0 = 0 := begin have h : a * 0 + a * 0 = a * 0 + 0, { rw [←mul_add, add_zero, add_zero] }, rw add_left_cancel h end -- END end my_ring
d2b47fe56929595a66bd74caa2823768d3ecc725
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Init/System/IOError.lean
c51cae9547a228d1407903d915063af81447dd5d
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
8,665
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ prelude import Init.Core import Init.Data.UInt import Init.Data.ToString.Basic import Init.Data.String.Basic /- Imitate the structure of IOErrorType in Haskell: https://hackage.haskell.org/package/base-4.12.0.0/docs/System-IO-Error.html#t:IOErrorType -/ inductive IO.Error where | alreadyExists (osCode : UInt32) (details : String) -- EEXIST, EINPROGRESS, EISCONN | otherError (osCode : UInt32) (details : String) -- EFAULT, default | resourceBusy (osCode : UInt32) (details : String) -- EADDRINUSE, EBUSY, EDEADLK, ETXTBSY | resourceVanished (osCode : UInt32) (details : String) -- ECONNRESET, EIDRM, ENETDOWN, ENETRESET, -- ENOLINK, EPIPE | unsupportedOperation (osCode : UInt32) (details : String) -- EADDRNOTAVAIL, EAFNOSUPPORT, ENODEV, ENOPROTOOPT -- ENOSYS, EOPNOTSUPP, ERANGE, ESPIPE, EXDEV | hardwareFault (osCode : UInt32) (details : String) -- EIO | unsatisfiedConstraints (osCode : UInt32) (details : String) -- ENOTEMPTY | illegalOperation (osCode : UInt32) (details : String) -- ENOTTY | protocolError (osCode : UInt32) (details : String) -- EPROTO, EPROTONOSUPPORT, EPROTOTYPE | timeExpired (osCode : UInt32) (details : String) -- ETIME, ETIMEDOUT | interrupted (filename : String) (osCode : UInt32) (details : String) -- EINTR | noFileOrDirectory (filename : String) (osCode : UInt32) (details : String) -- ENOENT | invalidArgument (filename : Option String) (osCode : UInt32) (details : String) -- ELOOP, ENAMETOOLONG, EDESTADDRREQ, EILSEQ, EINVAL, EDOM, EBADF -- ENOEXEC, ENOSTR, ENOTCONN, ENOTSOCK | permissionDenied (filename : Option String) (osCode : UInt32) (details : String) -- EACCES, EROFS, ECONNABORTED, EFBIG, EPERM | resourceExhausted (filename : Option String) (osCode : UInt32) (details : String) -- EMFILE, ENFILE, ENOSPC, E2BIG, EAGAIN, EMLINK: -- EMSGSIZE, ENOBUFS, ENOLCK, ENOMEM, ENOSR: | inappropriateType (filename : Option String) (osCode : UInt32) (details : String) -- EISDIR, EBADMSG, ENOTDIR: | noSuchThing (filename : Option String) (osCode : UInt32) (details : String) -- ENXIO, EHOSTUNREACH, ENETUNREACH, ECHILD, ECONNREFUSED, -- ENODATA, ENOMSG, ESRCH | unexpectedEof | userError (msg : String) deriving Inhabited @[export mk_io_user_error] def IO.userError (s : String) : IO.Error := IO.Error.userError s instance : Coe String IO.Error := ⟨IO.userError⟩ namespace IO.Error @[export lean_mk_io_error_eof] def mkEofError : Unit → IO.Error := fun _ => unexpectedEof @[export lean_mk_io_error_inappropriate_type_file] def mkInappropriateTypeFile : String → UInt32 → String → IO.Error := inappropriateType ∘ some @[export lean_mk_io_error_interrupted] def mkInterrupted : String → UInt32 → String → IO.Error := interrupted @[export lean_mk_io_error_invalid_argument_file] def mkInvalidArgumentFile : String → UInt32 → String → IO.Error := invalidArgument ∘ some @[export lean_mk_io_error_no_file_or_directory] def mkNoFileOrDirectory : String → UInt32 → String → IO.Error := noFileOrDirectory @[export lean_mk_io_error_no_such_thing_file] def mkNoSuchThingFile : String → UInt32 → String → IO.Error := noSuchThing ∘ some @[export lean_mk_io_error_permission_denied_file] def mkPermissionDeniedFile : String → UInt32 → String → IO.Error := permissionDenied ∘ some @[export lean_mk_io_error_resource_exhausted_file] def mkResourceExhaustedFile : String → UInt32 → String → IO.Error := resourceExhausted ∘ some @[export lean_mk_io_error_unsupported_operation] def mkUnsupportedOperation : UInt32 → String → IO.Error := unsupportedOperation @[export lean_mk_io_error_resource_exhausted] def mkResourceExhausted : UInt32 → String → IO.Error := resourceExhausted none @[export lean_mk_io_error_already_exists] def mkAlreadyExists : UInt32 → String → IO.Error := alreadyExists @[export lean_mk_io_error_inappropriate_type] def mkInappropriateType : UInt32 → String → IO.Error := inappropriateType none @[export lean_mk_io_error_no_such_thing] def mkNoSuchThing : UInt32 → String → IO.Error := noSuchThing none @[export lean_mk_io_error_resource_vanished] def mkResourceVanished : UInt32 → String → IO.Error := resourceVanished @[export lean_mk_io_error_resource_busy] def mkResourceBusy : UInt32 → String → IO.Error := resourceBusy @[export lean_mk_io_error_invalid_argument] def mkInvalidArgument : UInt32 → String → IO.Error := invalidArgument none @[export lean_mk_io_error_other_error] def mkOtherError : UInt32 → String → IO.Error := otherError @[export lean_mk_io_error_permission_denied] def mkPermissionDenied : UInt32 → String → IO.Error := permissionDenied none @[export lean_mk_io_error_hardware_fault] def mkHardwareFault : UInt32 → String → IO.Error := hardwareFault @[export lean_mk_io_error_unsatisfied_constraints] def mkUnsatisfiedConstraints : UInt32 → String → IO.Error := unsatisfiedConstraints @[export lean_mk_io_error_illegal_operation] def mkIllegalOperation : UInt32 → String → IO.Error := illegalOperation @[export lean_mk_io_error_protocol_error] def mkProtocolError : UInt32 → String → IO.Error := protocolError @[export lean_mk_io_error_time_expired] def mkTimeExpired : UInt32 → String → IO.Error := timeExpired private def downCaseFirst (s : String) : String := s.modify 0 Char.toLower def fopenErrorToString (gist fn : String) (code : UInt32) : Option String → String | some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")\n file: " ++ fn | none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")\n file: " ++ fn def otherErrorToString (gist : String) (code : UInt32) : Option String → String | some details => downCaseFirst gist ++ " (error code: " ++ toString code ++ ", " ++ downCaseFirst details ++ ")" | none => downCaseFirst gist ++ " (error code: " ++ toString code ++ ")" @[export lean_io_error_to_string] def toString : IO.Error → String | unexpectedEof => "end of file" | inappropriateType (some fn) code details => fopenErrorToString "inappropriate type" fn code details | inappropriateType none code details => otherErrorToString "inappropriate type" code details | interrupted fn code details => fopenErrorToString "interrupted system call" fn code details | invalidArgument (some fn) code details => fopenErrorToString "invalid argument" fn code details | invalidArgument none code details => otherErrorToString "invalid argument" code details | noFileOrDirectory fn code _ => fopenErrorToString "no such file or directory" fn code none | noSuchThing (some fn) code details => fopenErrorToString "no such thing" fn code details | noSuchThing none code details => otherErrorToString "no such thing" code details | permissionDenied (some fn) code details => fopenErrorToString details fn code none | permissionDenied none code details => otherErrorToString details code none | resourceExhausted (some fn) code details => fopenErrorToString "resource exhausted" fn code details | resourceExhausted none code details => otherErrorToString "resource exhausted" code details | alreadyExists code details => otherErrorToString "already exists" code details | otherError code details => otherErrorToString details code none | resourceBusy code details => otherErrorToString "resource busy" code details | resourceVanished code details => otherErrorToString "resource vanished" code details | hardwareFault code _ => otherErrorToString "hardware fault" code none | illegalOperation code details => otherErrorToString "illegal operation" code details | protocolError code details => otherErrorToString "protocol error" code details | timeExpired code details => otherErrorToString "time expired" code details | unsatisfiedConstraints code _ => otherErrorToString "directory not empty" code none | unsupportedOperation code details => otherErrorToString "unsupported operation" code details | userError msg => msg instance : ToString IO.Error := ⟨ IO.Error.toString ⟩ end IO.Error
0fcad111116912ddc82ea8fbf14778343d19a04e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/pge.lean
c14f53c8ecc823889403e3051ba0a6b87791d6ee
[ "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
12,168
lean
-- This module defines namespace Nat -- `forallRange i n f` is true if f holds for all indices j from i to n-1. def forallRange (i:Nat) (n:Nat) (f: ∀ (j:Nat), j < n → Bool) : Bool := if h:i < n then f i h && forallRange (i+1) n f else true termination_by forallRange i n f => n-i -- `forallRange` correctness theorem. theorem forallRangeImplies' (n i j : Nat) (f : ∀(k:Nat), k < n → Bool) (eq : i+j = n) (p : forallRange i n f = true) (k : Nat) (lb : i ≤ k) (ub : k < n) : f k ub = true := by induction j generalizing i with | zero => simp at eq simp [eq] at lb have pr := Nat.not_le_of_gt ub contradiction | succ j ind => have i_lt_n : i < n := Nat.le_trans (Nat.succ_le_succ lb) ub unfold forallRange at p simp [i_lt_n] at p cases Nat.eq_or_lt_of_le lb with | inl hEq => subst hEq apply p.1 | inr hLt => have succ_i_add_j : succ i + j = n := by simp_arith [← eq] apply ind (succ i) succ_i_add_j p.2 hLt -- Correctness theorem for `forallRange` theorem forallRangeImplies (p:forallRange i n f = true) {j:Nat} (lb:i ≤ j) (ub : j < n) : f j ub = true := have h : i+(n-i)=n := Nat.add_sub_of_le (Nat.le_trans lb (Nat.le_of_lt ub)) forallRangeImplies' n i (n-i) f h p j lb ub theorem lt_or_eq_of_succ {i j:Nat} (lt : i < Nat.succ j) : i < j ∨ i = j := match lt with | Nat.le.step m => Or.inl m | Nat.le.refl => Or.inr rfl -- Introduce strong induction principal for natural numbers. theorem strong_induction_on {p : Nat → Prop} (n:Nat) (h:∀n, (∀ m, m < n → p m) → p n) : p n := by suffices ∀n m, m < n → p m from this (succ n) n (Nat.lt_succ_self _) intros n induction n with | zero => intros m h contradiction | succ i ind => intros m h1 cases Nat.lt_or_eq_of_succ h1 with | inl is_lt => apply ind _ is_lt | inr is_eq => apply h rw [is_eq] apply ind end Nat -- Introduce strong induction principal for Fin. theorem Fin.strong_induction_on {P : Fin w → Prop} (i:Fin w) (ind : ∀(i:Fin w), (∀(j:Fin w), j < i → P j) → P i) : P i := by cases i with | mk i i_lt => revert i_lt apply @Nat.strong_induction_on (λi => ∀ (i_lt : i < w), P { val := i, isLt := i_lt }) intros j p j_lt_w apply ind ⟨j, j_lt_w⟩ intros z z_lt_j apply p _ z_lt_j namespace PEG inductive Expression (t : Type) (nt : Type) where | epsilon : Expression t nt | fail : Expression t nt | any : Expression t nt | terminal : t → Expression t nt | seq : (a b : nt) → Expression t nt | choice : (a b : nt) → Expression t nt | look : (a : nt) → Expression t nt | notP : (e : nt) → Expression t nt def Grammar (t nt : Type _) := nt → Expression t nt structure ProofRecord (nt : Type) where leftnonterminal : nt success : Bool position : Nat lengthofspan : Nat subproof1index : Nat subproof2index : Nat namespace ProofRecord def endposition {nt:Type} (r:ProofRecord nt) : Nat := r.position + r.lengthofspan inductive Result where | fail : Result | success : Nat → Result def record_result (r:ProofRecord nt) : Result := if r.success then Result.success r.lengthofspan else Result.fail end ProofRecord def PreProof (nt : Type) := Array (ProofRecord nt) def record_match [dnt : DecidableEq nt] (r:ProofRecord nt) (n:nt) (i:Nat) : Bool := r.leftnonterminal = n && r.position = i open Expression section well_formed variable {t nt : Type} variable [dt : DecidableEq t] variable [dnt : DecidableEq nt] variable (g : Grammar t nt) variable (s : Array t) def well_formed_record (p : PreProof nt) (i:Nat) (i_lt : i < p.size) (r : ProofRecord nt) : Bool := let n := r.leftnonterminal match g n with | epsilon => r.success ∧ r.lengthofspan = 0 | fail => ¬ r.success | any => if r.position < s.size then r.success && r.lengthofspan = 1 else ¬ r.success | terminal t => if r.position < s.size && s.getD r.position t = t then r.success && r.lengthofspan = 1 else ¬ r.success | seq a b => r.subproof1index < i && let r1 := p.getD r.subproof1index r record_match r1 a r.position && if r1.success then r.subproof2index < i && let r2 := p.getD r.subproof2index r record_match r2 b r1.endposition && if r2.success then r.success && r.endposition = r2.endposition else ¬r.success else ¬r.success | choice a b => r.subproof1index < i && let r1 := p.getD r.subproof1index r record_match r1 a r.position && if r1.success then r.success && r.lengthofspan = r1.lengthofspan else r.subproof2index < i && let r2 := p.getD r.subproof2index r record_match r2 b r.position && if r2.success then r.success && r.lengthofspan = r2.lengthofspan else ¬r.success | look a => r.subproof1index < i && let r1 := p.getD r.subproof1index r record_match r1 a r.position && if r1.success then r.success && r.lengthofspan = 0 else ¬r.success | notP a => r.subproof1index < i && let r1 := p.getD r.subproof1index r record_match r1 a r.position && if r1.success then ¬r.success else r.success && r.lengthofspan = 0 def well_formed_proof (p : PreProof nt) : Bool := Nat.forallRange 0 p.size (λi lt => well_formed_record g s p i lt (p.get ⟨i, lt⟩)) end well_formed def Proof [DecidableEq t] [DecidableEq nt] (g:Grammar t nt) (s: Array t) := { p:PreProof nt // well_formed_proof g s p } namespace Proof variable {g:Grammar t nt} variable {s : Array t} variable [DecidableEq t] variable [DecidableEq nt] def size (p:Proof g s) := p.val.size def get (p:Proof g s) : Fin p.size → ProofRecord nt := p.val.get instance : CoeFun (Proof g s) (fun p => Fin p.size → ProofRecord nt) := ⟨fun p => p.get⟩ theorem has_well_formed_record (p:Proof g s) (i:Fin p.size) : well_formed_record g s p.val i.val i.isLt (p i) := Nat.forallRangeImplies p.property (Nat.zero_le i.val) i.isLt end Proof section correctness variable {g:Grammar t nt} variable {s : Array t} variable [h1:DecidableEq t] variable [h2:DecidableEq nt] -- Lemma to rewrite from dependent use of proof index to get-with-default theorem proof_get_to_getD (r:ProofRecord nt) (p:Proof g s) (i:Fin p.size) : p i = p.val.getD i.val r := by have isLt : i.val < Array.size p.val := i.isLt simp [Proof.get, Array.get, Array.getD, isLt ] apply congrArg apply Fin.eq_of_val_eq trivial set_option tactic.dbg_cache true theorem is_deterministic : forall (p q : Proof g s) (i: Fin p.size) (j: Fin q.size), (p i).leftnonterminal = (q j).leftnonterminal → (p i).position = (q j).position → (p i).record_result = (q j).record_result := by intros p q i0 induction i0 using Fin.strong_induction_on with | ind i ind => intro j eq_nt p_pos_eq_q_pos have p_def := p.has_well_formed_record i have q_def := q.has_well_formed_record j simp only [well_formed_record, eq_nt, p_pos_eq_q_pos] at p_def q_def generalize q_j_eq : q j = q_j generalize e_eq : g (q_j.leftnonterminal) = e simp only [q_j_eq, e_eq] at p_def q_def p_pos_eq_q_pos simp only [ProofRecord.record_result] cases e case epsilon => simp_all case fail => simp_all case any => simp at q_def; split at q_def <;> simp_all case terminal t => simp at q_def; split at q_def <;> simp_all case seq a b => simp [record_match, ProofRecord.endposition] at p_def q_def generalize p_sub1_eq : (p i).subproof1index = p_sub1 generalize p_sub2_eq : (p i).subproof2index = p_sub2 generalize q_sub1_eq : q_j.subproof1index = q_sub1 generalize q_sub2_eq : q_j.subproof2index = q_sub2 simp only [p_sub1_eq, p_sub2_eq] at p_def simp only [q_sub1_eq, q_sub2_eq] at q_def have ⟨p_sub1_bound, ⟨p_sub1_nt, p_sub1_pos⟩, p_def⟩ := p_def have ⟨q_sub1_bound, ⟨q_sub1_nt, q_sub1_pos⟩, q_def⟩ := q_def have ind1 := ind (Fin.mk p_sub1 (Nat.lt_trans p_sub1_bound i.isLt)) p_sub1_bound (Fin.mk q_sub1 (Nat.lt_trans q_sub1_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind1 simp [ProofRecord.record_result] at ind1 split at p_def <;> split at q_def <;> simp [*] at ind1 p_def q_def <;> simp [*] have ⟨p_sub2_bound, ⟨p_sub2_nt, p_sub2_pos⟩, p_def⟩ := p_def have ⟨q_sub2_bound, ⟨q_sub2_nt, q_sub2_pos⟩, q_def⟩ := q_def -- Instantiate second invariant on subterm 2 have ind2 := ind (Fin.mk p_sub2 (Nat.lt_trans p_sub2_bound i.isLt)) p_sub2_bound (Fin.mk q_sub2 (Nat.lt_trans q_sub2_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind2 simp [ProofRecord.record_result] at ind2 split at p_def <;> split at q_def <;> simp_arith [*] at ind2 p_def q_def <;> simp_arith [*] save case choice => simp [record_match] at p_def q_def -- checkpoint simp generalize p_sub1_eq : (p i).subproof1index = p_sub1 generalize p_sub2_eq : (p i).subproof2index = p_sub2 simp only [p_sub1_eq, p_sub2_eq] at p_def generalize q_sub1_eq : q_j.subproof1index = q_sub1 generalize q_sub2_eq : q_j.subproof2index = q_sub2 simp only [q_sub1_eq, q_sub2_eq] at q_def have ⟨p_sub1_bound, ⟨p_sub1_nt, p_sub1_pos⟩, p_def⟩ := p_def have ⟨q_sub1_bound, ⟨q_sub1_nt, q_sub1_pos⟩, q_def⟩ := q_def have ind1 := ind (Fin.mk p_sub1 (Nat.lt_trans p_sub1_bound i.isLt)) p_sub1_bound (Fin.mk q_sub1 (Nat.lt_trans q_sub1_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind1 simp [ProofRecord.record_result] at ind1 save trace "type here" stop split at p_def <;> split at q_def <;> simp_all have ⟨p_sub2_bound, ⟨p_sub2_nt, p_sub2_pos⟩, p_def⟩ := p_def have ⟨q_sub2_bound, ⟨q_sub2_nt, q_sub2_pos⟩, q_def⟩ := q_def -- Instantiate second invariant on subterm 2 have ind2 := ind (Fin.mk p_sub2 (Nat.lt_trans p_sub2_bound i.isLt)) p_sub2_bound (Fin.mk q_sub2 (Nat.lt_trans q_sub2_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind2 simp [ProofRecord.record_result] at ind2 split at p_def <;> split at q_def <;> simp_all stop case look => simp [record_match] at p_def q_def generalize p_sub1_eq : (p i).subproof1index = p_sub1 simp only [p_sub1_eq] at p_def generalize q_sub1_eq : q_j.subproof1index = q_sub1 simp only [q_sub1_eq] at q_def have ⟨p_sub1_bound, ⟨p_sub1_nt, p_sub1_pos⟩, p_def⟩ := p_def have ⟨q_sub1_bound, ⟨q_sub1_nt, q_sub1_pos⟩, q_def⟩ := q_def have ind1 := ind (Fin.mk p_sub1 (Nat.lt_trans p_sub1_bound i.isLt)) p_sub1_bound (Fin.mk q_sub1 (Nat.lt_trans q_sub1_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind1 simp [ProofRecord.record_result] at ind1 split at p_def <;> split at q_def <;> simp_all case notP => simp [record_match] at p_def q_def generalize p_sub1_eq : (p i).subproof1index = p_sub1 simp only [p_sub1_eq] at p_def generalize q_sub1_eq : q_j.subproof1index = q_sub1 simp only [q_sub1_eq] at q_def have ⟨p_sub1_bound, ⟨p_sub1_nt, p_sub1_pos⟩, p_def⟩ := p_def have ⟨q_sub1_bound, ⟨q_sub1_nt, q_sub1_pos⟩, q_def⟩ := q_def have ind1 := ind (Fin.mk p_sub1 (Nat.lt_trans p_sub1_bound i.isLt)) p_sub1_bound (Fin.mk q_sub1 (Nat.lt_trans q_sub1_bound j.isLt)) rw [proof_get_to_getD (p i) p, proof_get_to_getD q_j q] at ind1 simp [ProofRecord.record_result] at ind1 split at p_def <;> split at q_def <;> simp_all end correctness end PEG
d780a68517846750d8f91dc8b2a56fef5ef14fba
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/div.lean
414337e97976b029e20d5e8919304f0740fb0208
[ "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
23,111
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.algebra_map import data.polynomial.inductions import data.polynomial.monic import ring_theory.multiplicity /-! # Division of univariate polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The main defs are `div_by_monic` and `mod_by_monic`. The compatibility between these is given by `mod_by_monic_add_div`. We also define `root_multiplicity`. -/ noncomputable theory open_locale classical big_operators polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] theorem X_dvd_iff {f : R[X]} : X ∣ f ↔ f.coeff 0 = 0 := ⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero], λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩ theorem X_pow_dvd_iff {f : R[X]} {n : ℕ} : X^n ∣ f ↔ ∀ d < n, f.coeff d = 0 := ⟨λ ⟨g, hgf⟩ d hd, by simp only [hgf, coeff_X_pow_mul', ite_eq_right_iff, not_le_of_lt hd, is_empty.forall_iff], λ hd, begin induction n with n hn, { simp only [pow_zero, one_dvd] }, { obtain ⟨g, hgf⟩ := hn (λ d : ℕ, λ H : d < n, hd _ (nat.lt_succ_of_lt H)), have := coeff_X_pow_mul g n 0, rw [zero_add, ← hgf, hd n (nat.lt_succ_self n)] at this, obtain ⟨k, hgk⟩ := polynomial.X_dvd_iff.mpr this.symm, use k, rwa [pow_succ, mul_comm X _, mul_assoc, ← hgk]}, end⟩ end comm_semiring section comm_semiring variables [comm_semiring R] {p q : R[X]} lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, by haveI := nontrivial.of_polynomial_ne hq; exact zero_ne_one, ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section ring variables [ring R] {p q : R[X]} lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne h.2, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [hq.degree_mul, degree_C_mul_X_pow _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, tsub_add_cancel_of_le hlt]) h.2 (by rw [leading_coeff_mul_monic hq, leading_coeff_mul_X_pow, leading_coeff_C]) /-- See `div_by_monic`. -/ noncomputable def div_mod_by_monic_aux : Π (p : R[X]) {q : R[X]}, monic q → R[X] × R[X] | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : R[X]) : R[X] := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : R[X]) : R[X] := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt [nontrivial R] : ∀ (p : R[X]) {q : R[X]} (hq : monic q), degree (p %ₘ q) < degree q | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq.ne_zero)), end using_well_founded {dec_tac := tactic.assumption} @[simp] lemma zero_mod_by_monic (p : R[X]) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : R[X]) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : R[X]) : p %ₘ 0 = p := if h : monic (0 : R[X]) then by { haveI := monic_zero_iff_subsingleton.mp h, simp } else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : R[X]) : p /ₘ 0 = 0 := if h : monic (0 : R[X]) then by { haveI := monic_zero_iff_subsingleton.mp h, simp } else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff [nontrivial R] (hq : monic q) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ theorem degree_mod_by_monic_le (p : R[X]) {q : R[X]} (hq : monic q) : degree (p %ₘ q) ≤ degree q := by { nontriviality R, exact (degree_mod_by_monic_lt _ hq).le } end ring section comm_ring variables [comm_ring R] {p q : R[X]} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : R[X]) {q : R[X]} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : R[X]) {q : R[X]} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma div_by_monic_eq_zero_iff [nontrivial R] (hq : monic q) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := begin nontriviality R, have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq ... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_right_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) end lemma degree_div_by_monic_le (p q : R[X]) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then if h : degree q ≤ degree p then by haveI := nontrivial.of_polynomial_ne hp0; rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : R[X]) {q : R[X]} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := if hpq : degree p < degree q then begin haveI := nontrivial.of_polynomial_ne hp0, rw [(div_by_monic_eq_zero_iff hq).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_coe _ end else begin haveI := nontrivial.of_polynomial_ne hp0, rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq.ne_zero) ▸ h0q)) end theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : R[X]) {g : R[X]} (hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g := begin nontriviality R, by_cases hfg : f /ₘ g = 0, { rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg at hfg, rw tsub_eq_zero_iff_le.mpr (nat_degree_le_nat_degree $ le_of_lt hfg) }, have hgf := hfg, rw div_by_monic_eq_zero_iff hg at hgf, push_neg at hgf, have := degree_add_div_by_monic hg hgf, have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] }, rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg, ← with_bot.coe_add, with_bot.coe_eq_coe] at this, rw [← this, add_tsub_cancel_left] end lemma div_mod_by_monic_unique {f g} (q r : R[X]) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := begin nontriviality R, have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (f %ₘ g)) : degree_sub_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, degree_mod_by_monic_lt _ hg⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul']; simpa [monic.def.1 hg]), exact ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ end lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := begin nontriviality S, haveI : nontrivial R := f.domain_nontrivial, have : map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), { exact (div_mod_by_monic_unique ((p /ₘ q).map f) _ (hq.map f) ⟨eq.symm $ by rw [← polynomial.map_mul, ← polynomial.map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ _ ... < degree q : degree_mod_by_monic_lt _ hq ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, f.map_one]; exact one_ne_zero)⟩) }, exact ⟨this.1.symm, this.2.symm⟩ end lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, begin nontriviality R, obtain ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h, by_contradiction hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q), { rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr] }, have : degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this, exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this) end⟩ theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : R[X]} (hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y := begin rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (hx.map f), ← map_mod_by_monic f hx], exact ⟨λ H, map_injective f hf $ by rw [H, polynomial.map_zero], λ H, by rw [H, polynomial.map_zero]⟩ end @[simp] lemma mod_by_monic_one (p : R[X]) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : R[X]) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p %ₘ (X - C a) = C (p.eval a) := begin nontriviality R, have h : (p %ₘ (X - C a)).eval a = p.eval a, { rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero] }, have : degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a), have : degree (p %ₘ (X - C a)) ≤ 0, { cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } }, rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : X - C a ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma X_sub_C_dvd_sub_C_eval : X - C a ∣ p - C (p.eval a) := by rw [dvd_iff_is_root, is_root, eval_sub, eval_C, sub_self] lemma mem_span_C_X_sub_C_X_sub_C_iff_eval_eval_eq_zero {b : R[X]} {P : R[X][X]} : P ∈ (ideal.span {C (X - C a), X - C b} : ideal R[X][X]) ↔ (P.eval b).eval a = 0 := begin rw [ideal.mem_span_pair], split; intro h, { rcases h with ⟨_, _, rfl⟩, simp only [eval_C, eval_X, eval_add, eval_sub, eval_mul, add_zero, mul_zero, sub_self] }, { cases dvd_iff_is_root.mpr h with p hp, cases @X_sub_C_dvd_sub_C_eval _ b _ P with q hq, exact ⟨C p, q, by rw [mul_comm, mul_comm q, eq_add_of_sub_eq' hq, hp, C_mul]⟩ } end lemma mod_by_monic_X (p : R[X]) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] lemma eval₂_mod_by_monic_eq_self_of_root [comm_ring S] {f : R →+* S} {p q : R[X]} (hq : q.monic) {x : S} (hx : q.eval₂ f x = 0) : (p %ₘ q).eval₂ f x = p.eval₂ f x := by rw [mod_by_monic_eq_sub_mul_div p hq, eval₂_sub, eval₂_mul, hx, zero_mul, sub_zero] lemma sum_mod_by_monic_coeff (hq : q.monic) {n : ℕ} (hn : q.degree ≤ n) : ∑ (i : fin n), monomial i ((p %ₘ q).coeff i) = p %ₘ q := begin nontriviality R, exact (sum_fin (λ i c, monomial i c) (by simp) ((degree_mod_by_monic_lt _ hq).trans_le hn)).trans (sum_monomial_eq _) end lemma sub_dvd_eval_sub (a b : R) (p : R[X]) : a - b ∣ p.eval a - p.eval b := begin suffices : X - C b ∣ p - C (p.eval b), { simpa only [coe_eval_ring_hom, eval_sub, eval_X, eval_C] using (eval_ring_hom a).map_dvd this }, simp [dvd_iff_is_root] end lemma mul_div_mod_by_monic_cancel_left (p : R[X]) {q : R[X]} (hmo : q.monic) : q * p /ₘ q = p := begin nontriviality R, refine (div_mod_by_monic_unique _ 0 hmo ⟨by rw [zero_add], _⟩).1, rw [degree_zero], exact ne.bot_lt (λ h, hmo.ne_zero (degree_eq_bot.1 h)) end variable (R) lemma not_is_field : ¬ is_field R[X] := begin nontriviality R, rw ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top, use ideal.span {polynomial.X}, split, { rw [bot_lt_iff_ne_bot, ne.def, ideal.span_singleton_eq_bot], exact polynomial.X_ne_zero, }, { rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ideal.mem_span_singleton, polynomial.X_dvd_iff, polynomial.coeff_one_zero], exact one_ne_zero, } end variable {R} lemma ker_eval_ring_hom (x : R) : (eval_ring_hom x).ker = ideal.span {X - C x} := by { ext y, simpa only [ideal.mem_span_singleton, dvd_iff_is_root] } section multiplicity /-- An algorithm for deciding polynomial divisibility. The algorithm is "compute `p %ₘ q` and compare to `0`". See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`. -/ def decidable_dvd_monic (p : R[X]) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := begin haveI := nontrivial.of_polynomial_ne h0, refine multiplicity_finite_of_degree_pos_of_monic _ (monic_X_sub_C _) h0, rw degree_X_sub_C, dec_trivial, end /-- The largest power of `X - C a` which divides `p`. This is computable via the divisibility algorithm `polynomial.decidable_dvd_monic`. -/ def root_multiplicity (a : R) (p : R[X]) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p ((monic_X_sub_C a).pow (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : R[X]) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, part.dom]; congr; funext; congr @[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl @[simp] lemma root_multiplicity_eq_zero_iff {p : R[X]} {x : R} : root_multiplicity x p = 0 ↔ (is_root p x → p = 0) := by simp only [root_multiplicity_eq_multiplicity, dite_eq_left_iff, part_enat.get_eq_iff_eq_coe, nat.cast_zero, multiplicity.multiplicity_eq_zero, dvd_iff_is_root, not_imp_not] lemma root_multiplicity_eq_zero {p : R[X]} {x : R} (h : ¬ is_root p x) : root_multiplicity x p = 0 := root_multiplicity_eq_zero_iff.2 (λ h', (h h').elim) @[simp] lemma root_multiplicity_pos' {p : R[X]} {x : R} : 0 < root_multiplicity x p ↔ p ≠ 0 ∧ is_root p x := by rw [pos_iff_ne_zero, ne.def, root_multiplicity_eq_zero_iff, not_imp, and.comm] lemma root_multiplicity_pos {p : R[X]} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := root_multiplicity_pos'.trans (and_iff_right hp) @[simp] lemma root_multiplicity_C (r a : R) : root_multiplicity a (C r) = 0 := by simp only [root_multiplicity_eq_zero_iff, is_root, eval_C, C_eq_zero, imp_self] lemma pow_root_multiplicity_dvd (p : R[X]) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : R[X]) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from (monic_X_sub_C _).pow _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : R[X]} (a : R) (hp : p ≠ 0) : eval a (p /ₘ ((X - C a) ^ root_multiplicity a p)) ≠ 0 := begin haveI : nontrivial R := nontrivial.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring end polynomial
53caecd45b382cbe846ade64f643581cfe78dfac
90edd5cdcf93124fe15627f7304069fdce3442dd
/src/Lean/Aesop/Util.lean
d4c7e6b570216c77456e94761715f228b9adc059
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
13,278
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg, Asta Halkjær From -/ import Lean.Elab.Syntax import Lean.Elab.Tactic.Basic import Lean.Message import Lean.Meta.DiscrTree import Lean.Meta.Tactic.Simp.SimpLemmas import Lean.Syntax import Std.Data.BinomialHeap namespace String def joinSep (sep : String) : List String → String | [] => "" | "" :: ss => joinSep sep ss | s :: ss => let tail := joinSep sep ss match tail with | "" => s | _ => s ++ sep ++ tail end String namespace Std.Format @[inlineIfReduce] def isEmptyShallow : Format → Bool | nil => true | text "" => true | _ => false @[inline] def indentDSkipEmpty [ToFormat α] (f : α) : Format := let f := format f if f.isEmptyShallow then nil else indentD f @[inline] def unlines [ToFormat α] (fs : List α) : Format := Format.joinSep fs line @[inline] def indentDUnlines [ToFormat α] : List α → Format := indentDSkipEmpty ∘ unlines @[inline] def indentDUnlinesSkipEmpty [ToFormat α] (fs : List α) : Format := indentDSkipEmpty $ unlines (fs.map format |>.filter (¬ ·.isEmptyShallow)) def formatIf (b : Bool) (f : Thunk Format) : Format := if b then f.get else nil end Std.Format namespace Lean.MessageData @[inline] def join (ms : List MessageData) : MessageData := ms.foldl (· ++ ·) nil @[inlineIfReduce] def isEmptyShallow : MessageData → Bool | ofFormat f => f.isEmptyShallow | _ => false @[inline] def indentDSkipEmpty (m : MessageData) : MessageData := if m.isEmptyShallow then nil else indentD m @[inline] def unlines (ms : List MessageData) : MessageData := joinSep ms Format.line @[inline] def indentDUnlines : List MessageData → MessageData := indentDSkipEmpty ∘ unlines @[inline] def indentDUnlinesSkipEmpty (fs : List MessageData) : MessageData := indentDSkipEmpty $ unlines $ fs.filter (¬ ·.isEmptyShallow) def toMessageDataIf (b : Bool) (f : Thunk MessageData) : MessageData := if b then f.get else nil def nodeFiltering (fs : Array (Option MessageData)) : MessageData := node $ fs.filterMap id end Lean.MessageData namespace Std.PersistentHashSet @[inline] def merge [BEq α] [Hashable α] (s t : PersistentHashSet α) : PersistentHashSet α := if s.size < t.size then loop s t else loop t s where @[inline] loop s t := s.fold (init := t) λ s a => s.insert a -- Elements are returned in unspecified order. def toList [BEq α] [Hashable α] (s : PersistentHashSet α) : List α := s.fold (init := []) λ as a => a :: as -- Elements are returned in unspecified order. (In fact, they are currently -- returned in reverse order of `toList`.) def toArray [BEq α] [Hashable α] (s : PersistentHashSet α) : Array α := s.fold (init := #[]) λ as a => as.push a end Std.PersistentHashSet namespace Std.PersistentHashMap @[inline] def merge [BEq α] [Hashable α] (m n : PersistentHashMap α β) (f : α → β → β → β) : PersistentHashMap α β := if m.size < n.size then loop m n f else loop n m (λ a b b' => f a b' b) where @[inline] loop m n f := m.foldl (init := n) λ map k v => match map.find? k with | some v' => map.insert k (f k v v') | none => map.insert k v universe u v -- We need to give u and v explicitly here, otherwise the compiler gets -- confused. unsafe def forInImpl [BEq α] [Hashable α] {m : Type u → Type v} [Monad m] (map : PersistentHashMap α β) (init : σ) (f : α × β → σ → m (ForInStep σ)) : m σ := do match (← go map.root init) with | ForInStep.yield r => pure r | ForInStep.done r => pure r where go : Node α β → σ → m (ForInStep σ) | Node.collision keys vals heq, acc => let rec go' (i : Nat) (acc : σ) : m (ForInStep σ) := do if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ match (← f (k, v) acc) with | ForInStep.done result => return ForInStep.done result | ForInStep.yield acc => go' (i + 1) acc else return ForInStep.yield acc go' 0 acc | Node.entries entries, acc => do let mut acc := acc for entry in entries do match entry with | Entry.null => pure ⟨⟩ | Entry.entry k v => match (← f (k, v) acc) with | ForInStep.done result => return ForInStep.done result | ForInStep.yield acc' => acc := acc' | Entry.ref node => match (← go node acc) with | ForInStep.done result => return ForInStep.done result | ForInStep.yield acc' => acc := acc' return ForInStep.yield acc -- Inhabited inference is being stupid here, so we can't use `partial`. @[implementedBy forInImpl] constant forIn [BEq α] [Hashable α] {m : Type u → Type v} [Monad m] (map : PersistentHashMap α β) (init : σ) (f : α × β → σ → m (ForInStep σ)) : m σ := pure init instance [BEq α] [Hashable α] : ForIn m (PersistentHashMap α β) (α × β) where forIn map := map.forIn end Std.PersistentHashMap namespace Lean.Meta.DiscrTree.Trie unsafe def foldMUnsafe [Monad m] (initialKeys : Array Key) (f : σ → Array Key → α → m σ) (init : σ) : Trie α → m σ | Trie.node vs children => do let s ← vs.foldlM (init := init) λ s v => f s initialKeys v children.foldlM (init := s) λ s (k, t) => t.foldMUnsafe (initialKeys.push k) f s @[implementedBy foldMUnsafe] constant foldM [Monad m] (initalKeys : Array Key) (f : σ → Array Key → α → m σ) (init : σ) (t : Trie α) : m σ := pure init @[inline] def fold (initialKeys : Array Key) (f : σ → Array Key → α → σ) (init : σ) (t : Trie α) : σ := Id.run $ t.foldM initialKeys (init := init) λ s k a => return f s k a end Trie @[inline] def foldM [Monad m] (f : σ → Array Key → α → m σ) (init : σ) (t : DiscrTree α) : m σ := t.root.foldlM (init := init) λ s k t => t.foldM #[k] (init := s) f @[inline] def fold (f : σ → Array Key → α → σ) (init : σ) (t : DiscrTree α) : σ := Id.run $ t.foldM (init := init) λ s keys a => return f s keys a -- TODO inefficient since it doesn't take advantage of the Trie structure at all @[inline] def merge [BEq α] (t u : DiscrTree α) : DiscrTree α := if t.root.size < u.root.size then loop t u else loop u t where @[inline] loop t u := t.fold (init := u) DiscrTree.insertCore def values (t : DiscrTree α) : Array α := t.fold (init := #[]) λ as _ a => as.push a def toArray (t : DiscrTree α) : Array (Array Key × α) := t.fold (init := #[]) λ as keys a => as.push (keys, a) end DiscrTree namespace SimpLemmas def merge (s t : SimpLemmas) : SimpLemmas where pre := s.pre.merge t.pre post := s.post.merge t.post lemmaNames := s.lemmaNames.merge t.lemmaNames toUnfold := s.toUnfold.merge t.toUnfold erased := s.erased.merge t.erased def addSimpEntry (s : SimpLemmas) : SimpEntry → SimpLemmas | SimpEntry.lemma l => addSimpLemmaEntry s l | SimpEntry.toUnfold d => s.addDeclToUnfold d open MessageData in protected def toMessageData (s : SimpLemmas) : MessageData := node #[ "pre lemmas:" ++ node (s.pre.values.map toMessageData), "post lemmas:" ++ node (s.post.values.map toMessageData), "definitions to unfold:" ++ node (s.toUnfold.toArray.qsort Name.lt |>.map toMessageData), "erased entries:" ++ node (s.erased.toArray.qsort Name.lt |>.map toMessageData) ] end SimpLemmas def copyMVar (mvarId : MVarId) : MetaM MVarId := do let decl ← getMVarDecl mvarId let mv ← mkFreshExprMVarAt decl.lctx decl.localInstances decl.type decl.kind decl.userName decl.numScopeArgs return mv.mvarId! end Lean.Meta namespace Std.BinomialHeap @[inline] def removeMin {lt : α → α → Bool} (h : BinomialHeap α lt) : Option (α × BinomialHeap α lt) := match h.head? with | some hd => some (hd, h.tail) | none => none end Std.BinomialHeap namespace MonadStateOf @[inline] def ofLens [Monad m] [MonadStateOf α m] (project : α → β) (inject : β → α → α) : MonadStateOf β m where get := return project (← get) set b := modify λ a => inject b a modifyGet f := modifyGet λ a => let (r, b) := f (project a) (r, inject b a) end MonadStateOf @[inline] abbrev setThe (σ) {m} [MonadStateOf σ m] (s : σ) : m PUnit := MonadStateOf.set s namespace ST.Ref variable {m} [Monad m] [MonadLiftT (ST σ) m] @[inline] unsafe def modifyMUnsafe (r : Ref σ α) (f : α → m α) : m Unit := do let v ← r.take r.set (← f v) @[implementedBy modifyMUnsafe] def modifyM (r : Ref σ α) (f : α → m α) : m Unit := do let v ← r.get r.set (← f v) @[inline] unsafe def modifyGetMUnsafe (r : Ref σ α) (f : α → m (β × α)) : m β := do let v ← r.take let (b, a) ← f v r.set a return b @[implementedBy modifyGetMUnsafe] def modifyGetM (r : Ref σ α) (f : α → m (β × α)) : m β := do let v ← r.get let (b, a) ← f v r.set a return b end ST.Ref namespace Lean.Meta def instantiateMVarsMVarType (mvarId : MVarId) : MetaM Expr := do let type ← instantiateMVars (← getMVarDecl mvarId).type setMVarType mvarId type return type end Lean.Meta namespace Lean.Syntax -- TODO for debugging, maybe remove partial def formatRaw : Syntax → String | missing => "missing" | node kind args => let args := ", ".joinSep $ args.map formatRaw |>.toList s!"(node {kind} [{args}])" | atom _ val => s!"(atom {val})" | ident _ _ val _ => s!"(ident {val})" end Lean.Syntax namespace Lean open Lean.Elab.Tactic def runTacticMAsMetaM (tac : TacticM Unit) (goal : MVarId) : MetaM (List MVarId) := run goal tac |>.run' def runMetaMAsImportM (x : MetaM α) : ImportM α := do let ctx : Core.Context := { options := (← read).opts } let state : Core.State := { env := (← read).env } let r ← x |>.run {} {} |>.run ctx state |>.toIO' match r with | Except.ok ((a, _), _) => pure a | Except.error e => throw $ IO.userError (← e.toMessageData.toString) def runMetaMAsCoreM (x : MetaM α) : CoreM α := Prod.fst <$> x.run {} {} end Lean namespace Lean.Elab.Command syntax (name := syntaxCatWithUnreservedTokens) "declare_syntax_cat' " ident (&"allow_leading_unreserved_tokens" <|> &"force_leading_unreserved_tokens")? : command -- Copied from Lean/Elab/Syntax.lean private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do if let Name.str _ suffix _ := catName then let quotSymbol := "`(" ++ suffix ++ "|" let name := catName ++ `quot -- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator let kind := ``Lean.Parser.Term.quot let cmd ← `( @[termParser] def $(mkIdent name) : Lean.ParserDescr := Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0)) (Lean.ParserDescr.symbol ")")))) elabCommand cmd open Lean.Parser (LeadingIdentBehavior) in @[commandElab syntaxCatWithUnreservedTokens] def elabDeclareSyntaxCatWithUnreservedTokens : CommandElab := fun stx => do let catName := stx[1].getId let leadingIdentBehavior := match stx[2].getOptional? with | none => LeadingIdentBehavior.default | some b => match b.getAtomVal! with | "allow_leading_unreserved_tokens" => LeadingIdentBehavior.both | "force_leading_unreserved_tokens" => LeadingIdentBehavior.symbol | _ => unreachable! let attrName := catName.appendAfter "Parser" let env ← getEnv let env ← liftIO $ Parser.registerParserCategory env attrName catName leadingIdentBehavior setEnv env declareSyntaxCatQuotParser catName end Lean.Elab.Command namespace Lean.Elab.Tactic open Lean.Elab.Term open Lean.Meta syntax (name := Parser.runTactic) &"run" term : tactic private abbrev TacticMUnit := TacticM Unit -- TODO copied from evalExpr unsafe def evalTacticMUnitUnsafe (value : Expr) : TermElabM (TacticM Unit) := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value unless (← isDefEq type (mkConst ``TacticMUnit)) do throwError "unexpected type at evalTacticMUnit:{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst (TacticM Unit) name @[implementedBy evalTacticMUnitUnsafe] constant evalTacticMUnit : Expr → TermElabM (TacticM Unit) @[tactic Parser.runTactic] def evalRunTactic : Tactic | `(tactic|run $t:term) => do let t ← elabTerm t (some (mkApp (mkConst ``TacticM) (mkConst ``Unit))) let t ← evalTacticMUnit t t | _ => unreachable! end Lean.Elab.Tactic
82213234ff5f970a2a3bfc6f83bc23ab7d7b70ee
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/multiplicity.lean
5bf0efe12486fa771e87abd8ac9c01e63e55396a
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,693
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Chris Hughes -/ import algebra.associated import algebra.big_operators.basic import ring_theory.valuation.basic /-! # Multiplicity of a divisor For a commutative monoid, this file introduces the notion of multiplicity of a divisor and proves several basic results on it. ## Main definitions * `multiplicity a b`: for two elements `a` and `b` of a commutative monoid returns the largest number `n` such that `a ^ n ∣ b` or infinity, written `⊤`, if `a ^ n ∣ b` for all natural numbers `n`. * `multiplicity.finite a b`: a predicate denoting that the multiplicity of `a` in `b` is finite. -/ variables {α : Type*} open nat part open_locale big_operators /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_monoid α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := enat.find $ λ n, ¬a ^ (n + 1) ∣ b namespace multiplicity section comm_monoid variables [comm_monoid α] /-- `multiplicity.finite a b` indicates that the multiplicity of `a` in `b` is finite. -/ @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b := begin apply part.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }} end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _ }) (by simpa [finite, not_not] using h), by simp [finite, multiplicity, not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit.pow (n + 1)) $ λ h, hn (h b) lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (h.trans (by simp [mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := by { rw ← enat.some_eq_coe, exact nat.cases_on k (λ _, by { rw pow_zero, exact one_dvd _ }) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) } lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, by rw [enat.lt_coe_iff] at hm; exact nat.find_spec hm.fst ((pow_dvd_pow _ hm.snd).trans h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by { rw [enat.le_coe_iff], exact ⟨this, nat.find_min' _ hsucc⟩ } lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} : multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b := by { rw [pow_dvd_iff_le_multiplicity, not_le] } lemma eq_coe_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := begin rw [← enat.some_eq_coe], exact ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by { rw [enat.lt_coe_iff], exact ⟨h₁, lt_succ_self _⟩ })⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ end lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := (enat.find_eq_top_iff _).trans $ by { simp only [not_not], exact ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _}) (λ n, h _), λ h n, h _⟩ } @[simp] lemma is_unit_left {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (ha.pow _) _) lemma is_unit_right {a b : α} (ha : ¬is_unit a) (hb : is_unit b) : multiplicity a b = 0 := eq_coe_iff.2 ⟨show a ^ 0 ∣ b, by simp only [pow_zero, one_dvd], by { rw pow_one, exact λ h, mt (is_unit_of_dvd_unit h) ha hb }⟩ @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := is_unit_left b is_unit_one lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := is_unit_right ha is_unit_one @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := begin rw [enat.get_eq_iff_eq_coe, eq_coe_iff, pow_zero], simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha, end @[simp] lemma unit_left (a : α) (u : units α) : multiplicity (u : α) a = ⊤ := is_unit_left a u.is_unit lemma unit_right {a : α} (ha : ¬is_unit a) (u : units α) : multiplicity a u = 0 := is_unit_right ha u.is_unit lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := by { rw [← nat.cast_zero, eq_coe_iff], simpa } lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := part.eq_none_iff' lemma ne_top_iff_finite {a b : α} : multiplicity a b ≠ ⊤ ↔ finite a b := by rw [ne.def, eq_top_iff_not_finite, not_not] lemma lt_top_iff_finite {a b : α} : multiplicity a b < ⊤ ↔ finite a b := by rw [lt_top_iff_ne_top, ne_top_iff_finite] open_locale classical lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma multiplicity_le_multiplicity_of_dvd_left {a b c : α} (hdvd : a ∣ b) : multiplicity b c ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n h, (pow_dvd_pow_of_dvd hdvd n).trans h lemma eq_of_associated_left {a b c : α} (h : associated a b) : multiplicity b c = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_left h.dvd) (multiplicity_le_multiplicity_of_dvd_left h.symm.dvd) lemma multiplicity_le_multiplicity_of_dvd_right {a b c : α} (h : b ∣ c) : multiplicity a b ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n hb, hb.trans h lemma eq_of_associated_right {a b c : α} (h : associated b c) : multiplicity a b = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_right h.dvd) (multiplicity_le_multiplicity_of_dvd_right h.symm.dvd) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := begin rw ← pow_one a, apply pow_dvd_of_le_multiplicity, simpa only [nat.cast_one, enat.pos_iff_one_le] using h end lemma dvd_iff_multiplicity_pos {a b : α} : (0 : enat) < multiplicity a b ↔ a ∣ b := ⟨dvd_of_multiplicity_pos, λ hdvd, lt_of_le_of_ne (zero_le _) (λ heq, is_greatest (show multiplicity a b < ↑1, by simpa only [heq, nat.cast_zero] using enat.coe_lt_coe.mpr zero_lt_one) (by rwa pow_one a))⟩ lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from lt_of_not_ge (λ ha', by { clear h, revert ha ha1, dec_trivial! }), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end end comm_monoid section comm_monoid_with_zero variable [comm_monoid_with_zero α] lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn variable [decidable_rel ((∣) : α → α → Prop)] @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := part.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) @[simp] lemma multiplicity_zero_eq_zero_of_ne_zero (a : α) (ha : a ≠ 0) : multiplicity 0 a = 0 := begin apply multiplicity.multiplicity_eq_zero_of_not_dvd, rwa zero_dvd_iff, end end comm_monoid_with_zero section comm_semiring variables [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] open_locale classical @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := part.ext' (by simp only [multiplicity, enat.find, dvd_neg]) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a + b) = multiplicity p b := begin apply le_antisymm, { apply enat.le_of_lt_add_one, cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk, rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd, rw [← dvd_add_iff_right] at h_dvd, apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self, rw [pow_dvd_iff_le_multiplicity, nat.cast_add, ← hk, nat.cast_one], exact enat.add_one_le_of_lt h }, { convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] } end lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a - b) = multiplicity p b := by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] } lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) : multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := begin rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab, { rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab }, { contradiction }, { rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab}, end end comm_ring section comm_cancel_monoid_with_zero variables [comm_cancel_monoid_with_zero α] lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from sub_lt_self' hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [nat.sub_add_cancel hn0] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (nat.le_add_right n m), finite_mul_aux hpx hb ⟨s, mul_right_cancel₀ hp.1 begin rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from sub_lt_self' hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [nat.sub_add_cancel hm0] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, mul_right_cancel₀ hp.1 begin rw [add_assoc, nat.sub_add_cancel hm0], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [pow_succ]; exact finite_mul hp ha (finite_pow ha) variable [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := by { rw ← nat.cast_one, exact eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, mul_left_cancel₀ ha0 $ by { clear _fun_match, simpa [pow_succ, mul_assoc] using hb }⟩)⟩ } @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := enat.get_eq_iff_eq_coe.2 (eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, pow_add, pow_one, mul_assoc, mul_assoc, mul_right_inj' (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (by exact succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp hdiva hdivb h), by rw [← enat.coe_inj, enat.coe_get, eq_coe_iff]; exact ⟨hdiv, hsucc⟩ open_locale classical protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← nat.cast_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) : multiplicity p (∏ x in s, f x) = ∑ x in s, multiplicity p (f x) := begin classical, induction s using finset.induction with a s has ih h, { simp only [finset.sum_empty, finset.prod_empty], convert one_right hp.not_unit }, { simp [has, ← ih], convert multiplicity.mul hp } end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by simp [one_right hp.not_unit] | (k+1) := have multiplicity p (a ^ (k + 1)) = multiplicity p (a * a ^ k), by rw pow_succ, by rw [get_eq_get_of_eq _ _ this, multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = k • (multiplicity p a) | 0 := by simp [one_right hp.not_unit] | (succ k) := by simp [pow_succ, succ_nsmul, pow, multiplicity.mul hp] lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) : multiplicity p (p ^ n) = n := by { rw [eq_coe_iff], use dvd_rfl, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self } lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.not_unit n end comm_cancel_monoid_with_zero section valuation variables {R : Type*} [comm_ring R] [integral_domain R] {p : R} [decidable_rel (has_dvd.dvd : R → R → Prop)] /-- `multiplicity` of a prime inan integral domain as an additive valuation to `enat`. -/ noncomputable def add_valuation (hp : prime p) : add_valuation R enat := add_valuation.of (multiplicity p) (multiplicity.zero _) (one_right hp.not_unit) (λ _ _, min_le_multiplicity_add) (λ a b, multiplicity.mul hp) @[simp] lemma add_valuation_apply {hp : prime p} {r : R} : add_valuation hp r = multiplicity p r := rfl end valuation end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← nonpos_iff_eq_zero, ← not_lt, enat.pos_iff_one_le, ← nat.cast_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, pow_one] at this, exact hp this end end nat