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
e9d47af948bff57965c9b5dcbff3a814196eec00
a338c3e75cecad4fb8d091bfe505f7399febfd2b
/src/ring_theory/fractional_ideal.lean
da8d16b3ecfe8d66e6aabd4bc6f1718515897464
[ "Apache-2.0" ]
permissive
bacaimano/mathlib
88eb7911a9054874fba2a2b74ccd0627c90188af
f2edc5a3529d95699b43514d6feb7eb11608723f
refs/heads/master
1,686,410,075,833
1,625,497,070,000
1,625,497,070,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,585
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.localization import ring_theory.noetherian import ring_theory.principal_ideal_domain import tactic.field_simp /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal S P` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal S P)` instance * `comm_semiring (fractional_ideal S P)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal S P)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R⁰ = R \ {0}` (i.e. the field of fractions). * `fractional_ideal R⁰ K` is the type of fractional ideals in the field of fractions * `has_div (fractional_ideal R⁰ K)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists * `is_noetherian` states that very fractional ideal of a noetherian integral domain is noetherian ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. Many results in fact do not need that `P` is a localization, only that `P` is an `R`-algebra. We omit the `is_localization` parameter whenever this is practical. Similarly, we don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `R⁰`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open is_localization local notation R`⁰`:9000 := non_zero_divisors R namespace ring section defs variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] variables (S) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R P) := ∃ a ∈ S, ∀ b ∈ I, is_integer R (a • b) variables (S P) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R P // is_fractional S I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] variables [algebra R P] [loc : is_localization S P] instance : has_coe (fractional_ideal S P) (submodule R P) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal S P) : I.val = I := rfl @[simp, norm_cast] lemma coe_mk (I : submodule R P) (hI : is_fractional S I) : (subtype.mk I hI : submodule R P) = I := rfl instance : has_mem P (fractional_ideal S P) := ⟨λ x I, x ∈ (I : submodule R P)⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ lemma coe_injective {I J : fractional_ideal S P} : (I : submodule R P) = J → I = J := subtype.ext_iff_val.mpr lemma ext_iff {I J : fractional_ideal S P} : (∀ x, (x ∈ I ↔ x ∈ J)) ↔ I = J := ⟨λ h, coe_injective (submodule.ext h), λ h x, h ▸ iff.rfl⟩ @[ext] lemma ext {I J : fractional_ideal S P} : (∀ x, (x ∈ I ↔ x ∈ J)) → I = J := ext_iff.mp lemma fractional_of_subset_one (I : submodule R P) (h : I ≤ (submodule.span R {1})) : is_fractional S I := begin use [1, S.one_mem], intros b hb, rw one_smul, rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, rfl⟩ := h hb, exact set.mem_range_self b', end lemma is_fractional_of_le {I : submodule R P} {J : fractional_ideal S P} (hIJ : I ≤ J) : is_fractional S I := begin obtain ⟨a, a_mem, ha⟩ := J.2, use [a, a_mem], intros b b_mem, exact ha b (hIJ b_mem) end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal S P) := ⟨λ I, ⟨coe_submodule P I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ← h; exact (algebra.algebra_map_eq_smul_one y).symm⟩⟩⟩ @[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal S P) : submodule R P) = coe_submodule P I := rfl variables (S) @[simp] lemma mem_coe_ideal {x : P} {I : ideal R} : x ∈ (I : fractional_ideal S P) ↔ ∃ (x' ∈ I), algebra_map R P x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal S P) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal S P) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ variables {S} @[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal S P) = (⊥ : submodule R P) := submodule.ext $ λ _, mem_zero_iff S @[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal S P) = 0 := rfl variables (P) include loc @[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) : (∃ x', x' ∈ I ∧ algebra_map R P x' = algebra_map R P x) ↔ x ∈ I := ⟨λ ⟨x', hx', eq⟩, is_localization.injective _ h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ variables {P} lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) : function.injective (coe : ideal R → fractional_ideal S P) := λ I J heq, have ∀ (x : R), algebra_map R P x ∈ (I : fractional_ideal S P) ↔ algebra_map R P x ∈ (J : fractional_ideal S P) := λ x, heq ▸ iff.rfl, ideal.ext (by simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq P h] using this) lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) = 0 ↔ I = (⊥ : ideal R) := ⟨λ h, coe_to_fractional_ideal_injective hS h, λ h, by rw [h, coe_to_fractional_ideal_bot]⟩ lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal S P) ≠ 0 ↔ I ≠ (⊥ : ideal R) := not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS) omit loc lemma coe_to_submodule_eq_bot {I : fractional_ideal S P} : (I : submodule R P) = ⊥ ↔ I = 0 := ⟨λ h, coe_injective (by simp [h]), λ h, by simp [h] ⟩ lemma coe_to_submodule_ne_bot {I : fractional_ideal S P} : ↑I ≠ (⊥ : submodule R P) ↔ I ≠ 0 := not_iff_not.mpr coe_to_submodule_eq_bot instance : inhabited (fractional_ideal S P) := ⟨0⟩ instance : has_one (fractional_ideal S P) := ⟨(1 : ideal R)⟩ variables (S) lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal S P) ↔ ∃ x' : R, algebra_map R P x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : algebra_map R P x ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal S P) := (mem_one_iff S).mpr ⟨1, ring_hom.map_one _⟩ variables {S} /-- `(1 : fractional_ideal S P)` is defined as the R-submodule `f(R) ≤ P`. However, this is not definitionally equal to `1 : submodule R P`, which is proved in the actual `simp` lemma `coe_one`. -/ lemma coe_one_eq_coe_submodule_one : ↑(1 : fractional_ideal S P) = coe_submodule P (1 : ideal R) := rfl @[simp, norm_cast] lemma coe_one : (↑(1 : fractional_ideal S P) : submodule R P) = 1 := begin simp only [coe_one_eq_coe_submodule_one, ideal.one_eq_top], convert (submodule.one_eq_map_top).symm, end section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal S P) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff_mem {I J : fractional_ideal S P} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.rfl @[simp] lemma coe_le_coe {I J : fractional_ideal S P} : (I : submodule R P) ≤ (J : submodule R P) ↔ I ≤ J := iff.rfl lemma zero_le (I : fractional_ideal S P) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal S P) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal S P) = 0 := rfl @[simp] lemma le_zero_iff {I : fractional_ideal S P} : I ≤ 0 ↔ I = 0 := le_bot_iff lemma eq_zero_iff {I : fractional_ideal S P} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, (mem_zero_iff S).mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal S P) : is_fractional S (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, rfl⟩, rw smul_add, apply is_integer_add, { rw [mul_smul, smul_comm], exact is_integer_smul (hI bI hbI), }, { rw mul_smul, exact is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal S P) : is_fractional S (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact hI b hbI end instance lattice : lattice (fractional_ideal S P) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal S P) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal S P) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal S P) : I ⊔ J = I + J := rfl @[simp, norm_cast] lemma coe_add (I J : fractional_ideal S P) : (↑(I + J) : submodule R P) = I + J := rfl lemma fractional_mul (I J : fractional_ideal S P) : is_fractional S (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [mul_smul, mul_comm m, ← smul_mul_assoc, ← hn', ← algebra.smul_def], apply hI, exact submodule.smul_mem _ _ hm }, { rw smul_zero, exact ⟨0, ring_hom.map_zero _⟩ }, { intros x y hx hy, rw smul_add, apply is_integer_add hx hy }, { intros r x hx, rw smul_comm, exact is_integer_smul hx }, end /-- `fractional_ideal.mul` is the product of two fractional ideals, used to define the `has_mul` instance. This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`. Elaborated terms involving `fractional_ideal` tend to grow quite large, so by making definitions irreducible, we hope to avoid deep unfolds. -/ @[irreducible] def mul (I J : fractional_ideal S P) : fractional_ideal S P := ⟨I.1 * J.1, fractional_mul I J⟩ local attribute [semireducible] mul instance : has_mul (fractional_ideal S P) := ⟨λ I J, mul I J⟩ @[simp] lemma mul_eq_mul (I J : fractional_ideal S P) : mul I J = I * J := rfl @[simp, norm_cast] lemma coe_mul (I J : fractional_ideal S P) : (↑(I * J) : submodule R P) = I * J := rfl lemma mul_left_mono (I : fractional_ideal S P) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal S P) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) lemma mul_mem_mul {I J : fractional_ideal S P} {i j : P} (hi : i ∈ I) (hj : j ∈ J) : i * j ∈ I * J := submodule.mul_mem_mul hi hj lemma mul_le {I J K : fractional_ideal S P} : I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) := submodule.mul_le @[elab_as_eliminator] protected theorem mul_induction_on {I J : fractional_ideal S P} {C : P → Prop} {r : P} (hr : r ∈ I * J) (hm : ∀ (i ∈ I) (j ∈ J), C (i * j)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := submodule.mul_induction_on hr hm h0 ha hs instance comm_semiring : comm_semiring (fractional_ideal S P) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, mul_assoc := λ I J K, coe_injective (submodule.mul_assoc _ _ _), mul_comm := λ I J, coe_injective (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, rfl⟩, convert submodule.smul_mem _ y' hx, rw [mul_comm, eq_comm], exact algebra.smul_def y' x }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h (one_mem_one _), rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, rfl⟩ y hy, convert submodule.smul_mem _ x' hy, rw eq_comm, exact algebra.smul_def x' y }, { have : 1 * x ∈ (1 * I) := mul_mem_mul (one_mem_one _) h, rwa one_mul at this } end, mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [(mem_zero_iff S).mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [(mem_zero_iff S).mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, coe_injective (mul_add _ _ _), right_distrib := λ I J K, coe_injective (add_mul _ _ _), ..fractional_ideal.has_zero S, ..fractional_ideal.has_add, ..fractional_ideal.has_one, ..fractional_ideal.has_mul } section order lemma add_le_add_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' + I ≤ J' + J := sup_le_sup_left hIJ J' lemma mul_le_mul_left {I J : fractional_ideal S P} (hIJ : I ≤ J) (J' : fractional_ideal S P) : J' * I ≤ J' * J := mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj)) lemma le_self_mul_self {I : fractional_ideal S P} (hI: 1 ≤ I) : I ≤ I * I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma mul_self_le_self {I : fractional_ideal S P} (hI: I ≤ 1) : I * I ≤ I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal S P) ≤ 1 := λ x hx, let ⟨y, _, hy⟩ := (fractional_ideal.mem_coe_ideal S).mp hx in (fractional_ideal.mem_one_iff S).mpr ⟨y, hy⟩ lemma le_one_iff_exists_coe_ideal {J : fractional_ideal S P} : J ≤ (1 : fractional_ideal S P) ↔ ∃ (I : ideal R), ↑I = J := begin split, { intro hJ, refine ⟨⟨{x : R | algebra_map R P x ∈ J}, _, _, _⟩, _⟩, { rw [mem_set_of_eq, ring_hom.map_zero], exact J.val.zero_mem }, { intros a b ha hb, rw [mem_set_of_eq, ring_hom.map_add], exact J.val.add_mem ha hb }, { intros c x hx, rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul, ← algebra.smul_def], exact J.val.smul_mem c hx }, { ext x, split, { rintros ⟨y, hy, eq_y⟩, rwa ← eq_y }, { intro hx, obtain ⟨y, eq_x⟩ := (fractional_ideal.mem_one_iff S).mp (hJ hx), rw ← eq_x at *, exact ⟨y, hx, rfl⟩ } } }, { rintro ⟨I, hI⟩, rw ← hI, apply coe_ideal_le_one }, end end order variables {P' : Type*} [comm_ring P'] [algebra R P'] [loc' : is_localization S P'] variables {P'' : Type*} [comm_ring P''] [algebra R P''] [loc'' : is_localization S P''] lemma fractional_map (g : P →ₐ[R] P') (I : fractional_ideal S P) : is_fractional S (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'] end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : P →ₐ[R] P') : fractional_ideal S P → fractional_ideal S P' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp, norm_cast] lemma coe_map (g : P →ₐ[R] P') (I : fractional_ideal S P) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma mem_map {I : fractional_ideal S P} {g : P →ₐ[R] P'} {y : P'} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := submodule.mem_map variables (I J : fractional_ideal S P) (g : P →ₐ[R] P') @[simp] lemma map_id : I.map (alg_hom.id _ _) = I := coe_injective (submodule.map_id I.1) @[simp] lemma map_comp (g' : P' →ₐ[R] P'') : I.map (g'.comp g) = (I.map g).map g' := coe_injective (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp, norm_cast] lemma map_coe_ideal (I : ideal R) : (I : fractional_ideal S P).map g = I := begin ext x, simp only [mem_coe_ideal], split, { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩, exact ⟨y, hy, (g.commutes y).symm⟩ }, { rintro ⟨y, hy, rfl⟩, exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ }, end @[simp] lemma map_one : (1 : fractional_ideal S P).map g = 1 := map_coe_ideal g 1 @[simp] lemma map_zero : (0 : fractional_ideal S P).map g = 0 := map_coe_ideal g 0 @[simp] lemma map_add : (I + J).map g = I.map g + J.map g := coe_injective (submodule.map_sup _ _ _) @[simp] lemma map_mul : (I * J).map g = I.map g * J.map g := coe_injective (submodule.map_mul _ _ _) @[simp] lemma map_map_symm (g : P ≃ₐ[R] P') : (I.map (g : P →ₐ[R] P')).map (g.symm : P' →ₐ[R] P) = I := by rw [←map_comp, g.symm_comp, map_id] @[simp] lemma map_symm_map (I : fractional_ideal S P') (g : P ≃ₐ[R] P') : (I.map (g.symm : P' →ₐ[R] P)).map (g : P →ₐ[R] P') = I := by rw [←map_comp, g.comp_symm, map_id] /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : P ≃ₐ[R] P') : fractional_ideal S P ≃+* fractional_ideal S P' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma coe_fun_map_equiv (g : P ≃ₐ[R] P') : (map_equiv g : fractional_ideal S P → fractional_ideal S P') = map g := rfl @[simp] lemma map_equiv_apply (g : P ≃ₐ[R] P') (I : fractional_ideal S P) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_symm (g : P ≃ₐ[R] P') : ((map_equiv g).symm : fractional_ideal S P' ≃+* _) = map_equiv g.symm := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal S P) := ring_equiv.ext (λ x, by simp) lemma is_fractional_span_iff {s : set P} : is_fractional S (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → is_integer R (a • b) := ⟨λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (by { rw smul_zero, exact is_integer_zero }) (λ x y hx hy, by { rw smul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw smul_comm, exact is_integer_smul hx })⟩⟩ include loc lemma is_fractional_of_fg {I : submodule R P} (hI : I.fg) : is_fractional S I := begin rcases hI with ⟨I, rfl⟩, rcases exist_integer_multiples_of_finset S I with ⟨⟨s, hs1⟩, hs⟩, rw is_fractional_span_iff, exact ⟨s, hs1, hs⟩, end variables (S P P') include loc' /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `P` and in `P'` -/ @[irreducible] noncomputable def canonical_equiv : fractional_ideal S P ≃+* fractional_ideal S P' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _, ..ring_equiv_of_ring_equiv P P' (ring_equiv.refl R) (show S.map _ = S, by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } @[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal S P} {x : P'} : x ∈ canonical_equiv S P P' I ↔ ∃ y ∈ I, is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) (y : P) = x := begin rw [canonical_equiv, map_equiv_apply, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ end @[simp] lemma canonical_equiv_symm : (canonical_equiv S P P').symm = canonical_equiv S P' P := ring_equiv.ext $ λ I, fractional_ideal.ext_iff.mp $ λ x, by { erw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ } @[simp] lemma canonical_equiv_flip (I) : canonical_equiv S P P' (canonical_equiv S P' P I) = I := by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply] end semiring section is_fraction_ring /-! ### `is_fraction_ring` section This section concerns fractional ideals in the field of fractions, i.e. the type `fractional_ideal R⁰ K` where `is_fraction_ring R K`. -/ variables {K K' : Type*} [field K] [field K'] variables [algebra R K] [is_fraction_ring R K] [algebra R K'] [is_fraction_ring R K'] variables {I J : fractional_ideal R⁰ K} (h : K →ₐ[R] K') /-- Nonzero fractional ideals contain a nonzero integer. -/ lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) : ∃ x ≠ (0 : R), algebra_map R K x ∈ I := begin obtain ⟨y, y_mem, y_not_mem⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr hI), have y_ne_zero : y ≠ 0 := by simpa using y_not_mem, obtain ⟨z, ⟨x, hx⟩⟩ := exists_integer_multiple R⁰ y, refine ⟨x, _, _⟩, { rw [ne.def, ← @is_fraction_ring.to_map_eq_zero_iff R _ K, hx, algebra.smul_def], exact mul_ne_zero (is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors z.2) y_ne_zero }, { rw hx, exact smul_mem _ _ y_mem } end lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := begin obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI, contrapose! x_ne_zero with map_eq_zero, refine is_fraction_ring.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)), exact ⟨algebra_map R K x, hx, h.commutes x⟩, end @[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨imp_of_not_imp_not _ _ (map_ne_zero _), λ hI, hI.symm ▸ map_zero h⟩ end is_fraction_ring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] variables [algebra R₁ K] [frac : is_fraction_ring R₁ K] instance : nontrivial (fractional_ideal R₁⁰ K) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal R₁⁰ K) := by { rw ← (algebra_map R₁ K).map_one, simpa only [h] using coe_mem_one R₁⁰ 1 }, one_ne_zero ((mem_zero_iff _).mp this)⟩⟩ include frac lemma fractional_div_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : is_fractional R₁⁰ (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := set_like.exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : algebra_map R₁ K aJ * y = 0, { rw [← algebra.smul_def, ←hy', y'_eq_zero, ring_hom.map_zero] }, have y_zero := (mul_eq_zero.mp this).resolve_left (mt ((algebra_map R₁ K).injective_iff.1 (is_fraction_ring.injective _ _) _) (mem_non_zero_divisors_iff_ne_zero.mp haJ)), exact not_mem_zero ((mem_zero_iff R₁⁰).mpr y_zero) }, intros b hb, convert hI _ (hb _ (submodule.smul_mem _ aJ mem_J)) using 1, rw [← hy', mul_comm b, ← algebra.smul_def, mul_smul] end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal R₁⁰ K) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ variables {I J : fractional_ideal R₁⁰ K} [ J ≠ 0 ] @[simp] lemma div_zero {I : fractional_ideal R₁⁰ K} : I / 0 = 0 := dif_pos rfl lemma div_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] lemma coe_div {I J : fractional_ideal R₁⁰ K} (hJ : J ≠ 0) : (↑(I / J) : submodule R₁ K) = ↑I / (↑J : submodule R₁ K) := begin unfold has_div.div, simp only [dif_neg hJ, coe_mk, val_eq_coe], end lemma mem_div_iff_of_nonzero {I J : fractional_ideal R₁⁰ K} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem } lemma mul_one_div_le_one {I : fractional_ideal R₁⁰ K} : I * (1 / I) ≤ 1 := begin by_cases hI : I = 0, { rw [hI, div_zero, mul_zero], exact zero_le 1 }, { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one], apply submodule.mul_one_div_le_one }, end lemma le_self_mul_one_div {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * (1 / I) := begin by_cases hI_nz : I = 0, { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 }, { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one], rw [← coe_le_coe, coe_one] at hI, exact submodule.le_self_mul_one_div hI }, end lemma le_div_iff_of_nonzero {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J := ⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx), λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩ lemma le_div_iff_mul_le {I J J' : fractional_ideal R₁⁰ K} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := begin rw div_nonzero hJ', convert submodule.le_div_iff_mul_le using 1, rw [val_eq_coe, val_eq_coe, ←coe_mul], refl, end @[simp] lemma div_one {I : fractional_ideal R₁⁰ K} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal R₁⁰ K) _ _)], ext, split; intro h, { simpa using mem_div_iff_forall_mul_mem.mp h 1 ((algebra_map R₁ K).map_one ▸ coe_mem_one R₁⁰ 1) }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, rfl⟩, rw mul_comm, convert submodule.smul_mem _ y' h, exact (algebra.smul_def _ _).symm } end omit frac lemma ne_zero_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal R₁⁰ K) _ _ (by { convert h, simp [hI], }) include frac theorem eq_one_div_of_mul_eq_one (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = 1 / I := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply mul_left_mono I, apply (le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact mul_mem_mul hx hy, end theorem mul_div_self_cancel_iff {I : fractional_ideal R₁⁰ K} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one I J hJ]⟩ variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_div (I J : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I / J).map (h : K →ₐ[R₁] K') = I.map h / J.map h := begin by_cases H : J = 0, { rw [H, div_zero, map_zero, div_zero] }, { apply coe_injective, simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] } end @[simp] lemma map_one_div (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (1 / I).map (h : K →ₐ[R₁] K') = 1 / I.map h := by rw [map_div, map_one] end quotient section principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] variables [algebra R₁ K] [is_fraction_ring R₁ K] open_locale classical open submodule submodule.is_principal include loc lemma is_fractional_span_singleton (x : P) : is_fractional S (span R {x} : submodule R P) := let ⟨a, ha⟩ := exists_integer_multiple S x in is_fractional_span_iff.mpr ⟨a, a.2, λ x' hx', (set.mem_singleton_iff.mp hx').symm ▸ ha⟩ variables (S) /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ @[irreducible] def span_singleton (x : P) : fractional_ideal S P := ⟨span R {x}, is_fractional_span_singleton x⟩ local attribute [semireducible] span_singleton @[simp] lemma coe_span_singleton (x : P) : (span_singleton S x : submodule R P) = span R {x} := rfl @[simp] lemma mem_span_singleton {x y : P} : x ∈ span_singleton S y ↔ ∃ (z : R), z • y = x := submodule.mem_span_singleton lemma mem_span_singleton_self (x : P) : x ∈ span_singleton S x := (mem_span_singleton S).mpr ⟨1, one_smul _ _⟩ variables {S} lemma eq_span_singleton_of_principal (I : fractional_ideal S P) [is_principal (I : submodule R P)] : I = span_singleton S (generator (I : submodule R P)) := coe_injective (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal S P) : is_principal (I : submodule R P) ↔ ∃ x, I = span_singleton S x := ⟨λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton _ x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton S (0 : P) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : P} : span_singleton S y = 0 ↔ y = 0 := ⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ lemma span_singleton_ne_zero_iff {y : P} : span_singleton S y ≠ 0 ↔ y ≠ 0 := not_congr span_singleton_eq_zero_iff @[simp] lemma span_singleton_one : span_singleton S (1 : P) = 1 := begin ext, refine (mem_span_singleton S).trans ((exists_congr _).trans (mem_one_iff S).symm), intro x', rw [algebra.smul_def, mul_one] end @[simp] lemma span_singleton_mul_span_singleton (x y : P) : span_singleton S x * span_singleton S y = span_singleton S (x * y) := begin apply coe_injective, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal S P) = span_singleton S (algebra_map R P x) := begin ext y, refine (mem_coe_ideal S).trans (iff.trans _ (mem_span_singleton S).symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy', use x', rw [smul_eq_mul, ring_hom.map_mul, algebra.smul_def] }, { rintros ⟨y', rfl⟩, refine ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, _⟩, rw [ring_hom.map_mul, algebra.smul_def] } end @[simp] lemma canonical_equiv_span_singleton {P'} [comm_ring P'] [algebra R P'] [is_localization S P'] (x : P) : canonical_equiv S P P' (span_singleton S x) = span_singleton S (is_localization.map P' (ring_hom.id R) (λ y (hy : y ∈ S), show ring_hom.id R y ∈ S, from hy) x) := begin apply ext_iff.mp, intro y, split; intro h, { rw mem_span_singleton, obtain ⟨x', hx', rfl⟩ := (mem_canonical_equiv_apply _ _ _).mp h, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp hx', use z, rw is_localization.map_smul, refl }, { rw mem_canonical_equiv_apply, obtain ⟨z, rfl⟩ := (mem_span_singleton _).mp h, use z • x, use (mem_span_singleton _).mpr ⟨z, rfl⟩, simp [is_localization.map_smul] } end lemma mem_singleton_mul {x y : P} {I : fractional_ideal S P} : y ∈ span_singleton S x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply fractional_ideal.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := (mem_span_singleton S).mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul ((mem_span_singleton S).mpr ⟨1, one_smul _ _⟩) hy' } end omit loc lemma one_div_span_singleton (x : K) : 1 / span_singleton R₁⁰ x = span_singleton R₁⁰ (x⁻¹) := if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one _ _ (by simp [h])).symm @[simp] lemma div_span_singleton (J : fractional_ideal R₁⁰ K) (d : K) : J / span_singleton R₁⁰ d = span_singleton R₁⁰ (d⁻¹) * J := begin rw ← one_div_span_singleton, by_cases hd : d = 0, { simp only [hd, span_singleton_zero, div_zero, zero_mul] }, have h_spand : span_singleton R₁⁰ d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd, apply le_antisymm, { intros x hx, rw [val_eq_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx, specialize hx d (mem_span_singleton_self R₁⁰ d), have h_xd : x = d⁻¹ * (x * d), { field_simp }, rw [val_eq_coe, coe_mul, one_div_span_singleton, h_xd], exact submodule.mul_mem_mul (mem_span_singleton_self R₁⁰ _) hx }, { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton, span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one], exact le_refl J }, end lemma exists_eq_span_singleton_mul (I : fractional_ideal R₁⁰ K) : ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton R₁⁰ (algebra_map R₁ K a)⁻¹ * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero : algebra_map R₁ K a_inv ≠ 0 := mt is_fraction_ring.to_map_eq_zero_iff.mp nonzero, refine ⟨a_inv, (span_singleton R₁⁰ (algebra_map R₁ K a_inv) * I).1.comap (algebra.linear_map R₁ K), nonzero, ext (λ x, iff.trans ⟨_, _⟩ mem_singleton_mul.symm)⟩, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, rw algebra.smul_def at hx', refine ⟨algebra_map R₁ K x', (mem_coe_ideal _).mpr ⟨x', mem_singleton_mul.mpr _, rfl⟩, _⟩, { exact ⟨x, hx, hx'⟩ }, { rw [hx', ← mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := (mem_coe_ideal _).mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw algebra.linear_map_apply at hx', rwa [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] [algebra R K] [is_fraction_ring R K] (I : fractional_ideal R⁰ K) : (I : submodule R K).is_principal := begin obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I, use (algebra_map R K a)⁻¹ * algebra_map R K (generator aI), suffices : I = span_singleton R⁰ ((algebra_map R K a)⁻¹ * algebra_map R K (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end end principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] variables {K : Type*} [field K] [algebra R₁ K] [frac : is_fraction_ring R₁ K] local attribute [instance] classical.prop_decidable lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal R₁⁰ K) := is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal R₁⁰ K)), by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot }) lemma is_noetherian_iff {I : fractional_ideal R₁⁰ K} : is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ K).fg := is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩ lemma is_noetherian_coe_to_fractional_ideal [_root_.is_noetherian_ring R₁] (I : ideal R₁) : is_noetherian R₁ (I : fractional_ideal R₁⁰ K) := begin rw is_noetherian_iff, intros J hJ, obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one), exact fg_map (is_noetherian.noetherian J), end include frac lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal R₁⁰ K} (hI : is_noetherian R₁ I) : is_noetherian R₁ (span_singleton R₁⁰ (algebra_map R₁ K x)⁻¹ * I : fractional_ideal R₁⁰ K) := begin by_cases hx : x = 0, { rw [hx, ring_hom.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul], exact is_noetherian_zero }, have h_gx : algebra_map R₁ K x ≠ 0, from mt ((algebra_map R₁ K).injective_iff.mp (is_fraction_ring.injective _ _) x) hx, have h_spanx : span_singleton R₁⁰ (algebra_map R₁ K x) ≠ 0, from span_singleton_ne_zero_iff.mpr h_gx, rw is_noetherian_iff at ⊢ hI, intros J hJ, rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ, obtain ⟨s, hs⟩ := hI _ hJ, use s * {(algebra_map R₁ K x)⁻¹}, rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton R₁⁰, ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx, span_singleton_one, mul_one], end /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem is_noetherian [_root_.is_noetherian_ring R₁] (I : fractional_ideal R₁⁰ K) : is_noetherian R₁ I := begin obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I, apply is_noetherian_span_singleton_inv_to_map_mul, apply is_noetherian_coe_to_fractional_ideal, end end fractional_ideal end ring
dfc5dca8773d6c6b324328e7700c12ad2aef5728
39c5aa4cf3be4a2dfd294cd2becd0848ff4cad97
/src/FreshNames.lean
11e44d8946ab31038c68859bdf39b9758789c32c
[]
no_license
anfelor/coc-lean
70d489ae1d34932d33bcf211b4ef8d1fe557e1d3
fdd967d2b7bc349202a1deabbbce155eed4db73a
refs/heads/master
1,617,867,588,097
1,587,224,804,000
1,587,224,804,000
248,754,643
5
0
null
null
null
null
UTF-8
Lean
false
false
4,879
lean
import data.finset import tactic.norm_num import Terms /-! This file deals with the generation of fresh variable names -/ /-- The pigeonhole principle for finsets -/ lemma pigeonhole : Π (ys : finset string) (xs : finset string), (finset.card ys < finset.card xs) → finset.nonempty (xs \ ys) | ys := λ xs h, if h2 : finset.card ys = 0 then begin have h3 : xs = xs \ ys := by { rw [finset.ext], intro, rw [finset.mem_sdiff], apply iff.intro, { intro, split, assumption, rw [finset.card_eq_zero] at h2, simp [h2], }, intro, cases a_1, assumption, }, rw [h2, finset.card_pos, h3] at h, assumption, end else begin -- we will rewrite h2 later and keep this as a save have h6 : finset.card ys ≠ 0 := by assumption, rw [finset.card_eq_zero, eq.symm (ne.def _ _)] at h2, rw [finset.nonempty_iff_ne_empty.symm] at h2, cases h2.bex, have h' : finset.card (finset.erase ys w) < finset.card (finset.erase xs w) := by { cases finset.decidable_mem w xs, { rw [finset.erase_eq_of_not_mem h_2], have h7 : finset.card ys > 0 := nat.pos_of_ne_zero h6, rw [finset.card_erase_of_mem h_1], rw [(nat.succ_pred_eq_of_pos h7).symm] at h, exact nat.lt_of_succ_lt h, }, rw [finset.card_erase_of_mem h_1, finset.card_erase_of_mem h_2], exact nat.pred_lt_pred h6 h, }, let wf_erase : finset.erase ys w ⊂ ys := finset.erase_ssubset h_1, let ne := pigeonhole (finset.erase ys w) (finset.erase xs w) h', cases ne.bex, have h4 : w_1 ∈ xs \ ys, { rw [finset.mem_sdiff] at h_2, cases h_2, simp [finset.mem_of_mem_erase] at h_2_left, cases h_2_left with neq inxs, let h5 : w_1 ∉ ys := mt (finset.mem_erase_of_ne_of_mem neq) h_2_right, simp, exact ⟨inxs, h5⟩, }, exact ⟨w_1, h4⟩, end using_well_founded { rel_tac := λ e es, `[exact ⟨_,(@finset.lt_wf string)⟩], dec_tac := `[assumption] } /-- We will create fresh names by appending primes which has the advantage of having a short injectivity proof. A real-world compiler should append digits though (also injective but harder to prove). -/ def mk_name (x : string) : nat → string | 0 := x | (n+1) := (mk_name n) ++ "'" lemma string.length_append (x y : string) : (x ++ y).length = x.length + y.length := begin cases x, cases y, simp [(++), string.append, string.length], from list.length_append x y, end lemma mk_name_len (x : string) (n : nat) : (mk_name x n).length = x.length + n := begin induction n, simp [mk_name], simp [mk_name, string.length_append, n_ih], have h : string.length "'" = 1 := by refl, rw [h, nat.succ_eq_add_one], end lemma mk_name_inj (x : string) : function.injective (mk_name x) := begin intros a1 a2 h, have h2 : (mk_name x a1).length = (mk_name x a2).length, from eq.rec_on h (eq.refl (mk_name x a1).length), simp [mk_name_len] at h2, from h2, end /-- Find a fresh name that is close to x but not in xs -/ def fresh (xs : finset string) (x : string) : string := let fresh_names := finset.image (mk_name x) (finset.range (nat.succ (finset.card xs))) in finset.min' (fresh_names \ xs) (pigeonhole xs fresh_names begin rw [finset.card_image_of_injective, finset.card_range], exact nat.lt_succ_self (finset.card xs), exact (mk_name_inj x), end) lemma fresh_is_fresh {xs x b} (h : b ∈ xs) : fresh xs x ≠ b := begin simp [fresh], intro, have h1 : b ∉ xs, from and.elim_right (iff.elim_left finset.mem_sdiff (eq.mp (by rw [a]) (finset.min'_mem _ _))), from absurd h h1, end lemma fresh_not_mem {xs x} : fresh xs x ∉ xs := λ e, absurd (eq.refl _) (fresh_is_fresh e) lemma fresh_avoids_capture_help {x b xs} (h : free_vars b ⊆ xs) (n : nat) : abstract_help (fresh xs x) (instantiate_help (Exp.free (fresh xs x)) b n) n = b := begin induction b generalizing n, simp, cases eq.decidable (fresh xs x) b, simp [h_1], simp at h, from absurd h_1 (fresh_is_fresh h), cases eq.decidable b n, iterate 2 { simp [h_1] }, simp, simp at h, let h_a := finset.subset.trans (finset.subset_union_left _ _) h, let h_a_1 := finset.subset.trans (finset.subset_union_right _ _) h, simp [b_ih_a h_a, b_ih_a_1 h_a_1], iterate 2 { simp at h, let h_a_1 := finset.subset.trans (finset.subset_union_left _ _) h, let h_a_2 := finset.subset.trans (finset.subset_union_right _ _) h, simp [b_ih_a h_a_1, b_ih_a_1 h_a_2], }, end /-- Instantiating a fresh variable and then abstracting it is the identity. -/ lemma fresh_avoids_capture {x b xs} (h : free_vars b ⊆ xs) : abstract (fresh xs x) (instantiate (Exp.free (fresh xs x)) b) = b := fresh_avoids_capture_help h 0 /-- Top-level one-step beta reduction. -/ def head_reduce : Exp → Exp | (Exp.app a b) := match a with Exp.lam _ _ d := instantiate b d, _ := Exp.app a b end | e := e
9323b9fcb8d39d35360fcbe1e6cae83ab93cd33f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/gcd/big_operators.lean
98c199b46373865c29f148b4c79781ae1a7cadc5
[ "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
1,093
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 -/ import data.nat.gcd.basic import algebra.big_operators.basic /-! # Lemmas about coprimality with big products. These lemmas are kept separate from `data.nat.gcd.basic` in order to minimize imports. -/ namespace nat open_locale big_operators /-- See `is_coprime.prod_left` for the corresponding lemma about `is_coprime` -/ lemma coprime_prod_left {ι : Type*} {x : ℕ} {s : ι → ℕ} {t : finset ι} : (∀ (i : ι), i ∈ t → coprime (s i) x) → coprime (∏ (i : ι) in t, s i) x := finset.prod_induction s (λ y, y.coprime x) (λ a b, coprime.mul) (by simp) /-- See `is_coprime.prod_right` for the corresponding lemma about `is_coprime` -/ lemma coprime_prod_right {ι : Type*} {x : ℕ} {s : ι → ℕ} {t : finset ι} : (∀ (i : ι), i ∈ t → coprime x (s i)) → coprime x (∏ (i : ι) in t, s i) := finset.prod_induction s (λ y, x.coprime y) (λ a b, coprime.mul_right) (by simp) end nat
e8bb0278f03c379ba972657f1966df54b041a6b3
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/ematch_partial_apps.lean
7c15c4c3860073efeb29a6a33bbc8559bda2759c
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
777
lean
open tactic set_option trace.smt.ematch true example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, ematch_using [list.map], ematch_using [list.map], ematch_using [list.map] end example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, repeat {ematch_using [list.map], try { close }}, end attribute [ematch] list.map example (a : list nat) (f : nat → nat) : a = [1, 2] → a^.map f = [f 1, f 2] := begin [smt] intros, eblast end constant f : nat → nat → nat constant g : nat → nat → nat axiom fgx : ∀ x y, (: f x :) = (λ y, y) ∧ (: g y :) = λ x, 0 attribute [ematch] fgx example (a b c : nat) : f a b = b ∧ g b c = 0 := begin [smt] ematch end
284fa4aad429dc8f28f04c679614167391e4d2de
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/mason_stothers_v2.lean
8d00defe06fedb7442811a40a919ba160e20de32
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
54,976
lean
-- the to be Mason-Stother formalization -- Authors Johannes & Jens --Defining the gcd import poly --import euclidean_domain --Need to fix an admit in UFD, for the ...multiset lemma import unique_factorization_domain import data.finsupp import algebraically_closed_field import poly_over_UFD import poly_over_field import poly_derivative noncomputable theory local infix ^ := monoid.pow local notation `d[`a`]` := polynomial.derivative a local notation Σ := finset.sume local notation Π := finset.prod local notation `Π₀` := finsupp.prod local notation `~`a:=polynomial a local notation a `~ᵤ` b : 50 := associated a b open polynomial open associated open classical local attribute [instance] prop_decidable -- TODO: there is some problem with the module instances for module.to_add_comm_group ... -- force ring.to_add_comm_group to be stronger attribute [instance] ring.to_add_comm_group universe u attribute [instance] field.to_unique_factorization_domain --correct? variable {β : Type u} variables [field β] open classical multiset section mason_stothers --It might be good to remove the attribute to domain of integral domain? def rad (p : polynomial β) : polynomial β := p.factors.erase_dup.prod lemma rad_ne_zero {p : polynomial β} : rad p ≠ 0 := begin rw [rad], apply multiset.prod_ne_zero_of_forall_mem_ne_zero, intros x h1, have h2 : irreducible x, { rw mem_erase_dup at h1, exact p.factors_irred x h1, }, exact h2.1, end --naming --Where do we use this? lemma degree_rad_eq_sum_support_degree {f : polynomial β} : degree (rad f) = sum (map degree f.factors.erase_dup) := begin rw rad, have h1 : finset.prod (to_finset (polynomial.factors f)) id ≠ 0, { apply polynomial.prod_ne_zero_of_forall_mem_ne_zero, intros x h1, have : irreducible x, { rw mem_to_finset at h1, exact f.factors_irred x h1, }, exact and.elim_left this, }, rw ←to_finset_val f.factors, exact calc degree (prod ((to_finset (polynomial.factors f)).val)) = degree (prod (map id (to_finset (polynomial.factors f)).val)) : by rw map_id_eq ... = sum (map degree ((to_finset (polynomial.factors f)).val)) : degree_prod_eq_sum_degree_of_prod_ne_zero h1, end private lemma mem_factors_of_mem_factors_sub_factors_erase_dup (f : polynomial β) (x : polynomial β) (h : x ∈ (f.factors)-(f.factors.erase_dup)) : x ∈ f.factors := begin have : ((f.factors)-(f.factors.erase_dup)) ≤ f.factors, from multiset.sub_le_self _ _, exact mem_of_le this h, end --naming lemma prod_pow_min_on_ne_zero {f : polynomial β} : ((f.factors)-(f.factors.erase_dup)).prod ≠ 0 := begin apply multiset.prod_ne_zero_of_forall_mem_ne_zero, intros x h, have h1 : x ∈ f.factors, from mem_factors_of_mem_factors_sub_factors_erase_dup f x h, have : irreducible x, from f.factors_irred x h1, exact this.1, end lemma degree_factors_prod_eq_degree_factors_sub_erase_dup_add_degree_rad {f : polynomial β} : degree (f.factors.prod) = degree ((f.factors)-(f.factors.erase_dup)).prod + degree (rad f) := begin rw [← sub_erase_dup_add_erase_dup_eq f.factors] {occs := occurrences.pos [1]}, rw [←prod_mul_prod_eq_add_prod], apply degree_mul_eq_add_of_mul_ne_zero, exact mul_ne_zero prod_pow_min_on_ne_zero rad_ne_zero, end lemma ne_zero_of_dvd_ne_zero {γ : Type u}{a b : γ} [comm_semiring γ] (h1 : a ∣ b) (h2 : b ≠ 0) : a ≠ 0 := begin simp only [has_dvd.dvd] at h1, let c := some h1, have h3: b = a * c, from some_spec h1, by_contradiction h4, rw not_not at h4, rw h4 at h3, simp at h3, contradiction end open polynomial --Why here? private lemma Mason_Stothers_lemma_aux_1 (f : polynomial β): ∀x ∈ f.factors, x^(count x f.factors - 1) ∣ d[f.factors.prod] := begin rw [derivative_prod_multiset], intros x h, apply multiset.dvd_sum, intros y hy, rw multiset.mem_map at hy, rcases hy with ⟨z, hz⟩, have : y = d[z] * prod (erase (factors f) z), from hz.2.symm, subst this, apply dvd_mul_of_dvd_right, rcases (exists_cons_of_mem hz.1) with ⟨t, ht⟩, rw ht, by_cases h1 : x = z, { subst h1, simp, apply forall_pow_count_dvd_prod, }, { simp [count_cons_of_ne h1], refine dvd_trans _ (forall_pow_count_dvd_prod t x), apply pow_count_sub_one_dvd_pow_count, }, end private lemma count_factors_sub_one (f x : polynomial β) : (count x f.factors - 1) = count x (factors f - erase_dup (factors f)) := begin rw count_sub, by_cases h1 : x ∈ f.factors, { have : count x (erase_dup (factors f)) = 1, { have h2: 0 < count x (erase_dup (factors f)), { rw [count_pos, mem_erase_dup], exact h1 }, have h3: count x (erase_dup (factors f)) ≤ 1, { have : nodup (erase_dup (factors f)), from nodup_erase_dup _, rw nodup_iff_count_le_one at this, exact this x, }, have : 1 ≤ count x (erase_dup (factors f)), from h2, exact nat.le_antisymm h3 this, }, rw this, }, { rw ←count_eq_zero at h1, simp *, } end private lemma Mason_Stothers_lemma_aux_2 (f : polynomial β) (h_dvd : ∀x ∈ f.factors, x^(count x f.factors - 1) ∣ gcd f d[f]): (f.factors - f.factors.erase_dup).prod ∣ gcd f d[f] := begin apply facs_to_pow_prod_dvd_multiset, intros x h, have h1 : x ∈ f.factors, from mem_factors_of_mem_factors_sub_factors_erase_dup f x h, split, { exact f.factors_irred x h1, }, split, { rw ←count_factors_sub_one, exact h_dvd x h1, }, { intros y hy h2, have : y ∈ f.factors, from mem_factors_of_mem_factors_sub_factors_erase_dup f y hy, have h3: monic x, from f.factors_monic x h1, have h4: monic y, from f.factors_monic y this, rw associated_iff_eq_of_monic_of_monic h3 h4, exact h2, } end private lemma degree_factors_prod (f : polynomial β) (h : f ≠ 0): degree (f.factors.prod) = degree f := begin rw [f.factors_eq] {occs := occurrences.pos [2]}, rw [degree_mul_eq_add_of_mul_ne_zero, degree_C], simp, rw ←f.factors_eq, exact h, end --make private? --in theses as degree_le lemma Mason_Stothers_lemma (f : polynomial β) : degree f ≤ degree (gcd f (derivative f )) + degree (rad f) := --I made degree radical from this one begin by_cases hf : (f = 0), { simp [hf, nat.zero_le]}, { have h_dvd_der : ∀x ∈ f.factors, x^(count x f.factors - 1) ∣ d[f], { rw [f.factors_eq] {occs := occurrences.pos [3]}, rw [derivative_C_mul], intros x h, exact dvd_mul_of_dvd_right (Mason_Stothers_lemma_aux_1 f x h) _, }, have h_dvd_f : ∀x ∈ f.factors, x^(count x f.factors - 1) ∣ f, { rw [f.factors_eq] {occs := occurrences.pos [3]}, intros x hx, --We have intros x hx a lot here, duplicate? apply dvd_mul_of_dvd_right, exact dvd_trans (pow_count_sub_one_dvd_pow_count _ _) (forall_pow_count_dvd_prod _ x), --Duplicate 2 lines with Mason_Stothers_lemma_aux_1 }, have h_dvd_gcd_f_der : ∀x ∈ f.factors, x^(count x f.factors - 1) ∣ gcd f d[f], { intros x hx, exact gcd_min (h_dvd_f x hx) (h_dvd_der x hx), }, have h_prod_dvd_gcd_f_der : (f.factors - f.factors.erase_dup).prod ∣ gcd f d[f], from Mason_Stothers_lemma_aux_2 _ h_dvd_gcd_f_der, have h_gcd : gcd f d[f] ≠ 0, { rw [ne.def, gcd_eq_zero_iff_eq_zero_and_eq_zero], simp [hf] }, have h1 : degree ((f.factors - f.factors.erase_dup).prod) ≤ degree (gcd f d[f]), from degree_dvd h_prod_dvd_gcd_f_der h_gcd, have h2 : degree f = degree ((f.factors)-(f.factors.erase_dup)).prod + degree (rad f), { rw ←degree_factors_prod, exact degree_factors_prod_eq_degree_factors_sub_erase_dup_add_degree_rad, exact hf, }, rw h2, apply add_le_add_right, exact h1, } end lemma Mason_Stothers_lemma' (f : polynomial β) : degree f - degree (gcd f (derivative f )) ≤ degree (rad f) := begin have h1 : degree f - degree (gcd f (derivative f )) ≤ degree (gcd f (derivative f )) + degree (rad f) - degree (gcd f (derivative f )), { apply nat.sub_le_sub_right, apply Mason_Stothers_lemma, }, have h2 : degree (gcd f d[f]) + degree (rad f) - degree (gcd f d[f]) = degree (rad f), { rw [add_comm _ (degree (rad f)), nat.add_sub_assoc, nat.sub_self, nat.add_zero], exact nat.le_refl _, }, rw h2 at h1, exact h1, end lemma eq_zero_of_le_pred {n : ℕ} (h : n ≤ nat.pred n) : n = 0 := begin cases n, simp, simp at h, have h1 : nat.succ n = n, from le_antisymm h (nat.le_succ n), have h2 : nat.succ n ≠ n, from nat.succ_ne_self n, contradiction, end lemma derivative_eq_zero_of_dvd_derivative_self {a : polynomial β} (h : a ∣ d[a]) : d[a] = 0 := begin by_contradiction hc, have h1 : degree d[a] ≤ degree a - 1, from degree_derivative_le, have h2 : degree a ≤ degree d[a], from degree_dvd h hc, have h3 : degree a = 0, { have h3 : degree a ≤ degree a - 1, from le_trans h2 h1, exact eq_zero_of_le_pred h3, }, rw ←is_constant_iff_degree_eq_zero at h3, have h5 : d[a] = 0, from derivative_eq_zero_of_is_constant h3, contradiction, end --In MS detailed I call this zero wronskian lemma derivative_eq_zero_and_derivative_eq_zero_of_coprime_of_wron_eq_zero {a b : polynomial β} (h1 : coprime a b) (h2 : d[a] * b - a * d[b] = 0) : d[a] = 0 ∧ d[b] = 0 := begin have h3 : d[a] * b = a * d[b], { exact calc d[a] * b = d[a] * b + (-a * d[b] + a * d[b]) : by simp ... = d[a] * b - (a * d[b]) + a * d[b] : by simp [add_assoc] ... = 0 + a * d[b] : by rw [h2] ... = _ : by simp }, have h4 : a ∣ d[a] * b, from dvd.intro _ h3.symm, rw mul_comm at h4, have h5 : a ∣ d[a], exact dvd_of_dvd_mul_of_coprime h4 h1, have h6 : d[a] = 0, from derivative_eq_zero_of_dvd_derivative_self h5, --duplication rw mul_comm at h3, have h7 : b ∣ a * d[b], from dvd.intro _ h3, have h8 : b ∣ d[b], exact dvd_of_dvd_mul_of_coprime h7 (h1.symm), have h9 : d[b] = 0, from derivative_eq_zero_of_dvd_derivative_self h8, exact ⟨h6, h9⟩, end --Lemma coprime_gcd in MS_detailed lemma coprime_gcd_derivative_gcd_derivative_of_coprime {a b : polynomial β} (h : coprime a b) (c d : polynomial β) : coprime (gcd a c) (gcd b d) := begin rw coprime, by_contradiction h1, let e := (gcd (gcd a c) (gcd b d)), have ha : e ∣ a, { have h2a: e ∣ (gcd a c), from gcd_left, have h2b : (gcd a c) ∣ a, from gcd_left, exact dvd_trans h2a h2b, }, have hb : e ∣ b, { have h2a: e ∣ (gcd b d), from gcd_right, have h2b : (gcd b d) ∣ b, from gcd_left, exact dvd_trans h2a h2b, }, have he: e ∣ (gcd a b), from gcd_min ha hb, have h2 : ¬is_unit (gcd a b), from not_is_unit_of_not_is_unit_dvd h1 he, rw coprime at h, exact h2 h, end lemma degree_gcd_derivative_le_degree {a : polynomial β}: degree (gcd a d[a]) ≤ degree a := begin by_cases h : (a = 0), { simp * at *, }, { apply degree_gcd_le_left, exact h, } end lemma degree_gcd_derivative_lt_degree_of_degree_ne_zero {a : polynomial β} (h : degree a ≠ 0) (h_char : characteristic_zero β) : degree (gcd a d[a]) < degree a := begin have h1 : degree (gcd a d[a]) ≤ degree d[a], { apply degree_dvd, apply gcd_right, rw [ne.def, derivative_eq_zero_iff_is_constant, is_constant_iff_degree_eq_zero], exact h, exact h_char, }, have h2 : ∃ n, degree a = nat.succ n, from nat.exists_eq_succ_of_ne_zero h, let n := some h2, have h3 : degree a = nat.succ n, from some_spec h2, exact calc degree (gcd a d[a]) ≤ degree d[a] : h1 ... ≤ degree a - 1 : degree_derivative_le ... ≤ nat.succ n - 1 : by rw h3 ... = n : rfl ... < nat.succ n : nat.lt_succ_self _ ... = degree a : eq.symm h3, end open associated lemma not_zero_mem_factors {a : polynomial β} : (0 : polynomial β) ∉ a.factors := begin by_contradiction h1, have : irreducible (0 : polynomial β), from a.factors_irred 0 h1, have : ¬ irreducible (0 : polynomial β), { simp}, contradiction, end lemma c_fac_eq_zero_iff_eq_zero {a : polynomial β} : a.c_fac = 0 ↔ a = 0 := begin split, { intro h, rw a.factors_eq, simp *, }, { intro h, rw [a.factors_eq, mul_eq_zero_iff_eq_zero_or_eq_zero] at h, cases h, { rw C_eq_zero_iff_eq_zero at h, exact h, }, { rw prod_eq_zero_iff_zero_mem' at h, have : (0 : polynomial β) ∉ a.factors, from not_zero_mem_factors, contradiction, } } end --Not used private lemma mk_C_c_fac_eq_one_of_ne_zero {a : polynomial β} (h : a ≠ 0) : mk (C a.c_fac) = 1 := begin rw [ne.def, ←c_fac_eq_zero_iff_eq_zero] at h, have h1 : is_unit a.c_fac, from for_all_is_unit_of_not_zero h, have h2 : is_unit (C a.c_fac), from is_unit_of_is_unit h1, rw mk_eq_one_iff_is_unit, exact h2, end --a and b can be implicit lemma factors_inter_factors_eq_zero_of_coprime (a b : polynomial β) (h : coprime a b) : a.factors ∩ b.factors = 0 := begin by_cases ha: a = 0, { subst ha, simp, }, by_cases hb: b = 0, { subst hb, simp, }, --I already have a similar lemma for coprime rw [coprime_iff_mk_inf_mk_eq_one, a.factors_eq, b.factors_eq, mul_mk, mul_mk] at h, --we go to the quotient structure with respect to units. rw inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one at h, --We probably can do without going to the quotient, because we have the lemmas for coprime let h1 := h.2, rw mul_inf_eq_one_iff_inf_eq_one_and_inf_eq_one at h1, let h2 := h1.2, rw [mk_def, mk_def, ←prod_mk, ←prod_mk] at h2, rw prod_inf_prod_eq_one_iff_forall_forall_inf_eq_one at h2, rw [inter_eq_zero_iff_disjoint, disjoint_iff_ne], { intros x hx y hy, have h3 : mk x ⊓ mk y = 1, { apply h2, { rw mem_map, exact ⟨x, hx, rfl⟩, }, { rw mem_map, exact ⟨y, hy, rfl⟩, }, }, rw [←coprime_iff_mk_inf_mk_eq_one, coprime_iff_not_associated_of_irreducible_of_irreducible] at h3, rw [associated_iff_eq_of_monic_of_monic] at h3, exact h3, exact a.factors_monic x hx, exact b.factors_monic y hy, exact a.factors_irred x hx, exact b.factors_irred y hy, } end open associated private lemma monic_prod_factors (a : polynomial β) : monic a.factors.prod := monic_prod_of_forall_mem_monic a.factors_monic lemma c_fac_eq_leading_coeff (a : polynomial β) : a.c_fac = leading_coeff a := begin by_cases ha : a = 0, { simp * at *, }, { have h1 : a = (C a.c_fac) * a.factors.prod, from a.factors_eq, rw [h1] {occs := occurrences.pos[2]}, rw leading_coeff_mul_eq_mul_leading_coef, let h3 := monic_prod_factors a, rw monic at h3, simp [h3], } end private lemma C_inv_c_fac_mul_eq_prod_factors {a : polynomial β} (ha : a ≠ 0): (C a.c_fac⁻¹) * a = a.factors.prod := begin have h1 : a = (C a.c_fac) * a.factors.prod, from a.factors_eq, rw [ne.def, ←c_fac_eq_zero_iff_eq_zero] at ha, exact calc (C a.c_fac⁻¹) * a = (C a.c_fac⁻¹) * (C (c_fac a) * prod (factors a)) : by rw [←h1] ... = _ : by rw [←mul_assoc, ←C_mul_C, inv_mul_cancel ha, C_1, one_mul], end lemma factors_eq_map_monic_out_to_multiset_mk (a : polynomial β) : a.factors = map monic_out (associated.to_multiset (associated.mk a)) := begin by_cases ha : a = 0, { simp * at *, }, { have h1 : a = C (a.c_fac) * a.factors.prod, from a.factors_eq, have h2 : C (a.c_fac⁻¹) * a = a.factors.prod, from C_inv_c_fac_mul_eq_prod_factors ha, have h3: a.factors.prod = (map monic_out (to_multiset (mk a))).prod, { rw prod_map_monic_out_eq_monic_out_prod, rw ←h2, rw ←associated_iff_eq_of_monic_of_monic, rw to_multiset_prod_eq, have h4 : (a ~ᵤ (monic_out (mk a))), from (monic_out_mk_associated a).symm, --It can no longer elaborate it?? After I refactored all the files have h5 : (C (c_fac a)⁻¹ * a ~ᵤ a), { have h5a : (c_fac a)⁻¹ ≠ 0, { rw ←c_fac_eq_zero_iff_eq_zero at ha, apply inv_ne_zero, exact ha, }, have h5b : (C (c_fac a)⁻¹) ≠ 0, --Is this used? { rw [ne.def, C_eq_zero_iff_eq_zero], exact h5a, }, have h5c: is_unit (C (c_fac a)⁻¹), from is_unit_C_of_ne_zero h5a, rcases h5c with ⟨u, hu⟩, exact ⟨u, by simp *⟩, }, exact associated.trans h5 h4, rwa [ne.def, mk_eq_zero_iff_eq_zero], { rw c_fac_eq_leading_coeff, exact leading_coeff_inv_mul_monic_of_ne_zero ha, }, { apply monic_monic_out_of_ne_zero, rw [to_multiset_prod_eq],--Wrong naminG!! rw ←mk_eq_zero_iff_eq_zero at ha, --Duplicate exact ha, rw ←mk_eq_zero_iff_eq_zero at ha, exact ha, } }, have h4a: ∀ (x : ~β), x ∈ map monic_out (to_multiset (mk a)) → irreducible x, { intros x h, rw mem_map at h, rcases h with ⟨y, hy⟩, rw hy.2.symm, apply irreducible_monic_out_of_irred, apply to_multiset_irred _ y hy.1, }, have h4 : rel_multiset associated a.factors (map monic_out (to_multiset (mk a))), from unique_factorization_domain.unique a.factors_irred h4a h3, apply eq_of_rel_multiset_associated_of_forall_mem_monic_of_forall_mem_monic, exact h4, exact a.factors_monic, { intros x h, rw mem_map at h, rcases h with ⟨y, hy⟩, rw hy.2.symm, apply monic_monic_out_of_ne_zero, { have : irred y, from to_multiset_irred _ y hy.1, exact ne_zero_of_irred this, } } } end --aux --I already have to_multiset_mul, how can I reuse that here?? How to make the connection between monic and associated?? lemma factors_mul_eq_factors_add_factors {a b : polynomial β} (ha : a ≠ 0) (hb : b ≠ 0) : factors (a * b) = a.factors + b.factors := begin rw [factors_eq_map_monic_out_to_multiset_mk, factors_eq_map_monic_out_to_multiset_mk, factors_eq_map_monic_out_to_multiset_mk], rw [mul_mk, to_multiset_mul], simp, simp [mk_eq_zero_iff_eq_zero, *], simp [mk_eq_zero_iff_eq_zero, *], end @[simp] lemma rad_zero : rad (0 : polynomial β ) = 1 := begin simp [rad], end lemma rad_mul_eq_rad_mul_rad_of_coprime {a b : polynomial β} (ha : a ≠ 0) (hb : b ≠ 0) (h : coprime a b) : rad (a * b) = (rad a) * (rad b) := begin simp only [rad], rw prod_mul_prod_eq_add_prod, apply congr_arg, rw factors_mul_eq_factors_add_factors ha hb, --Might be good to go to nodup rw multiset.ext, intros x, by_cases h1 : x ∈ (a.factors + b.factors), { have h2 : count x (erase_dup (factors a + factors b)) = 1, { apply count_eq_one_of_mem, exact nodup_erase_dup _, rwa mem_erase_dup, }, rw mem_add at h1, have h3 : x ∈ a.factors ∩ b.factors ↔ x ∈ a.factors ∧ x ∈ b.factors, from mem_inter, have h4: a.factors ∩ b.factors = 0, from factors_inter_factors_eq_zero_of_coprime _ _ h, cases h1, { have : x ∉ b.factors, { simp * at *, }, rw ←mem_erase_dup at h1, have h1a : count x (erase_dup (factors a)) = 1, from count_eq_one_of_mem (nodup_erase_dup _) h1, rw ←mem_erase_dup at this, have h1b : count x (erase_dup (factors b)) = 0, { rwa count_eq_zero, }, rw count_add, simp * at *, }, { --Strong duplication have : x ∉ a.factors, { simp * at *, }, rw ←mem_erase_dup at h1, have h1a : count x (erase_dup (factors b)) = 1, from count_eq_one_of_mem (nodup_erase_dup _) h1, rw ←mem_erase_dup at this, have h1b : count x (erase_dup (factors a)) = 0, { rwa count_eq_zero, }, rw count_add, simp * at *, } }, { have h2 : count x (erase_dup (factors a + factors b)) = 0, { rwa [count_eq_zero, mem_erase_dup], }, rw [mem_add, not_or_distrib] at h1, have h3 : count x (erase_dup (factors a)) = 0, { rw [count_eq_zero, mem_erase_dup], exact h1.1, }, have h4 : count x (erase_dup (factors b)) = 0, { rw [count_eq_zero, mem_erase_dup], exact h1.2, }, simp * at *, }, end --We will need extra conditions here --We only need this one lemma degree_rad_add {a b: polynomial β} (ha : a ≠ 0) (hb : b ≠ 0) (hab : coprime a b): degree (rad a) + degree (rad b) ≤ degree (rad (a * b)) := begin rw rad_mul_eq_rad_mul_rad_of_coprime ha hb hab, rw degree_mul_eq_add_of_mul_ne_zero, apply _root_.mul_ne_zero, { apply multiset.prod_ne_zero_of_forall_mem_ne_zero, intros x h, rw mem_erase_dup at h, exact (a.factors_irred _ h).1 --Anoying setup for factors_irred }, { apply multiset.prod_ne_zero_of_forall_mem_ne_zero, intros x h, rw mem_erase_dup at h, exact (b.factors_irred _ h).1 --Anoying setup for factors_irred }, end private lemma h_rad_add {a b c: polynomial β} (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (hab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) : degree(rad(a))+degree(rad(b))+degree(rad(c)) ≤ degree(rad(a*b*c)) := begin have habc : coprime (a*b) c, { have h1: ((gcd (a * b) c) ~ᵤ (gcd b c)), from gcd_mul_cancel h_coprime_ca.symm, exact is_unit_of_associated h_coprime_bc h1.symm, }, have h1 : a * b ≠ 0, from mul_ne_zero ha hb, have h3 : degree (rad a) + degree (rad b) ≤ degree (rad (a * b)), from degree_rad_add ha hb hab, exact calc degree(rad(a))+degree(rad(b))+degree(rad(c)) ≤ degree (rad (a * b)) + degree (rad c) : add_le_add_right h3 _ ... ≤ _ : degree_rad_add h1 hc habc end lemma gt_zero_of_ne_zero {n : ℕ} (h : n ≠ 0) : n > 0 := begin have h1 : ∃ m : ℕ, n = nat.succ m, from nat.exists_eq_succ_of_ne_zero h, let m := some h1, have h2 : n = nat.succ m, from some_spec h1, rw h2, exact nat.zero_lt_succ _, end lemma MS_aux_1a {c : polynomial β} (h3 : ¬degree c = 0)(h_char : characteristic_zero β) : 1 ≤ (degree c - degree (gcd c d[c])) := begin have h4 : degree c - degree (gcd c d[c]) > 0, { rw [nat.pos_iff_ne_zero, ne.def, nat.sub_eq_zero_iff_le], simp, exact degree_gcd_derivative_lt_degree_of_degree_ne_zero h3 h_char, }, exact h4, end --should be in poly lemma MS_aux_1b {a b c : polynomial β} (h_char : characteristic_zero β) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) (h1 : is_constant b) (h2 : ¬is_constant a) : ¬ is_constant c := begin rw [is_constant_iff_degree_eq_zero] at *, have h3 : c (degree a) ≠ 0, { rw ← h_add, simp, have h3 : b (degree a) = 0, { apply eq_zero_of_gt_degree, rw h1, exact gt_zero_of_ne_zero h2, }, rw h3, simp, have h4 : leading_coeff a = 0 ↔ a = 0, from leading_coef_eq_zero_iff_eq_zero, rw leading_coeff at h4, rw h4, by_contradiction h5, rw h5 at h2, simp at h2, exact h2, }, have h4 : degree a ≤ degree c, from le_degree h3, by_contradiction h5, rw h5 at h4, have : degree a = 0, from nat.eq_zero_of_le_zero h4, contradiction, end lemma MS_aux_1 {a b c : polynomial β} (h_char : characteristic_zero β) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : 1 ≤ degree b - degree (gcd b d[b]) + (degree c - degree (gcd c d[c])) := begin by_cases h1 : (is_constant b), { by_cases h2 : (is_constant a), { have h3 : is_constant c, from is_constant_add h2 h1 h_add, simp * at *, }, { have h3 : ¬ is_constant c, { exact MS_aux_1b h_char h_add h_constant h1 h2, }, rw [is_constant_iff_degree_eq_zero] at h3, have h4 : 1 ≤ (degree c - degree (gcd c d[c])), from MS_aux_1a h3 h_char, apply nat.le_trans h4, simp, exact nat.zero_le _, } }, { rw [is_constant_iff_degree_eq_zero] at h1, have h2 : 1 ≤ degree b - degree (gcd b d[b]), from MS_aux_1a h1 h_char, apply nat.le_trans h2, simp, exact nat.zero_le _, } end ---Very likely that the lemmas on rad are overcomplicated, they should use erase_dup_more lemma dvd_of_mem_factors (f : polynomial β) (x : polynomial β) (h : x ∈ f.factors) : x ∣ f := begin rw f.factors_eq, have : x ∣ f.factors.prod, from dvd_prod_of_mem f.factors h, exact dvd_mul_of_dvd_right this _, end lemma not_is_unit_prod_factors_of_factors_ne_zero (a : polynomial β) (h : a.factors ≠ 0) : ¬ is_unit (a.factors.prod) := begin exact not_is_unit_prod_of_ne_zero_of_forall_mem_irreducible h a.factors_irred, end @[simp] lemma factors_C (c : β) : (C c).factors = 0 := begin by_cases h1 : C c = 0, { simp *, }, { by_contradiction h2, rcases (exists_mem_of_ne_zero h2) with ⟨x, hx⟩, have h2 : x ∣ C c, --The part below could be a separate lemma { exact dvd_of_mem_factors (C c) x hx, }, have h3: irreducible x, from (C c).factors_irred x hx, have h4: ¬is_unit x, from not_is_unit_of_irreducible h3, have h5: ¬is_unit (C c), from not_is_unit_of_not_is_unit_dvd h4 h2, have h6 : is_constant (C c), {simp}, rw is_constant_iff_eq_zero_or_is_unit at h6, simp * at *, } end lemma is_constant_iff_factors_eq_zero (a : polynomial β) : is_constant a ↔ a.factors = 0 := begin split, { intro h, rcases h with ⟨c, hc⟩, subst hc, simp, }, { intro h, rw a.factors_eq, simp * at *, } end --lemma factors_eq_zero_iff_rad_eq_zero (a : polynomial β) lemma rad_dvd_prod_factors (a : polynomial β) : (rad a) ∣ a.factors.prod := begin rw rad, apply prod_dvd_prod_of_le, exact erase_dup_le _, end lemma rad_dvd (a : polynomial β) : (rad a) ∣ a := begin rw [a.factors_eq] {occs := occurrences.pos [2]}, apply dvd_mul_of_dvd_right, exact rad_dvd_prod_factors _, end lemma degree_rad_le (a : polynomial β) : degree (rad a) ≤ degree a := begin by_cases h1 : a = 0, { subst h1, simp, }, { apply degree_dvd, exact rad_dvd _, exact h1, } end lemma is_unit_rad_iff_factors_eq_zero (a : polynomial β) : is_unit (rad a) ↔ a.factors = 0 := begin split, { intro h, rw ←erase_dup_eq_zero_iff_eq_zero, by_contradiction h1, have : ¬is_unit (rad a), { apply not_is_unit_prod_of_ne_zero_of_forall_mem_irreducible h1, intros x h, rw mem_erase_dup at h, exact a.factors_irred x h, }, simp * at *, }, { intro h, rw ←erase_dup_eq_zero_iff_eq_zero at h, rw rad, simp *, } end lemma degree_rad_eq_zero_iff_is_constant (a : polynomial β) : degree (rad a) = 0 ↔ is_constant a := begin split, { intro h, rw is_constant_iff_factors_eq_zero, rw [←is_constant_iff_degree_eq_zero, is_constant_iff_eq_zero_or_is_unit] at h, cases h, { have : rad a ≠ 0, from rad_ne_zero, contradiction, }, { rw ←is_unit_rad_iff_factors_eq_zero, exact h, }, }, { intro h, rw is_constant_iff_factors_eq_zero at h, apply degree_eq_zero_of_is_unit, rw is_unit_rad_iff_factors_eq_zero, exact h, } end --Strong duplication with MS_aux_1 lemma MS_aux_2 {a b c : polynomial β} (h_char : characteristic_zero β) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : 1 ≤ degree (rad a) + (degree c - degree (gcd c d[c])) := begin by_cases h1 : is_constant b, { by_cases h2 : is_constant a, { have h3 : is_constant c, from is_constant_add h2 h1 h_add, simp * at *, }, { have h3 : ¬ is_constant c, { rw [is_constant_iff_degree_eq_zero] at *, have h3 : c (degree a) ≠ 0, { rw ← h_add, simp, have h3 : b (degree a) = 0, { apply eq_zero_of_gt_degree, rw h1, exact gt_zero_of_ne_zero h2, }, rw h3, simp, have h4 : leading_coeff a = 0 ↔ a = 0, from leading_coef_eq_zero_iff_eq_zero, rw leading_coeff at h4, rw h4, by_contradiction h5, rw h5 at h2, simp at h2, exact h2, }, have h4 : degree a ≤ degree c, from le_degree h3, by_contradiction h5, rw h5 at h4, have : degree a = 0, from nat.eq_zero_of_le_zero h4, contradiction, }, rw [is_constant_iff_degree_eq_zero] at h3, have h4 : 1 ≤ (degree c - degree (gcd c d[c])), from MS_aux_1a h3 h_char, apply nat.le_trans h4, simp, exact nat.zero_le _, } }, { by_cases h2 : (is_constant a), { rw add_comm at h_add, have h_constant' : ¬(is_constant b ∧ is_constant a ∧ is_constant c), {simp [*, and_comm]}, have h3 : ¬is_constant c, from MS_aux_1b h_char h_add h_constant' h2 h1, rw [is_constant_iff_degree_eq_zero] at h3, have h4 : 1 ≤ (degree c - degree (gcd c d[c])), from MS_aux_1a h3 h_char, apply nat.le_trans h4, simp, exact nat.zero_le _, }, { have : degree a ≠ 0, { rw [ne.def, ←is_constant_iff_degree_eq_zero], exact h2, }, rw [ne.def, ←is_constant_iff_degree_eq_zero, ←degree_rad_eq_zero_iff_is_constant] at this, have h3: 1 ≤ degree (rad a), { rcases (nat.exists_eq_succ_of_ne_zero this) with ⟨n, hn⟩, simp * at *, rw nat.succ_le_succ_iff, exact nat.zero_le _, }, apply nat.le_trans h3, exact nat.le_add_right _ _, } } end private lemma rw_aux_1a [field β] (a b c : polynomial β) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : degree a ≠ 0 ∨ degree b ≠ 0 := begin rw [not_and_distrib, not_and_distrib] at h_constant, cases h_constant, { rw is_constant_iff_degree_eq_zero at h_constant, simp *, }, { cases h_constant, { rw is_constant_iff_degree_eq_zero at h_constant, simp *, }, { rw is_constant_iff_degree_eq_zero at h_constant, have : degree (a + b) ≤ max (degree a) (degree b), from degree_add, simp * at *, rw le_max_iff at this, rcases (nat.exists_eq_succ_of_ne_zero h_constant) with ⟨n, hn⟩, simp * at *, cases this with h, { have : ¬degree a = 0, { by_contradiction h1, simp * at *, exact nat.not_succ_le_zero _ h, }, simp *, }, { have : ¬degree b = 0, { by_contradiction h1, simp * at *, exact nat.not_succ_le_zero _ this, }, simp *, } } } end private lemma rw_aux_1b [field β] (a b c : polynomial β) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : 1 ≤ degree a + degree b := begin have : degree a ≠ 0 ∨ degree b ≠ 0, from rw_aux_1a a b c h_add h_constant, cases this with h h ; { rcases (nat.exists_eq_succ_of_ne_zero h) with ⟨n, hn⟩, simp * at *, have : 1 ≤ nat.succ n, { rw nat.succ_le_succ_iff, exact nat.zero_le _, }, apply nat.le_trans this, apply nat.le_add_right, }, end --h_deg_c_le_1 lemma rw_aux_1 [field β] --(h_char : characteristic_zero β) (a b c : polynomial β) --(h_coprime_ab : coprime a b) --(h_coprime_bc : coprime b c) --(h_coprime_ca : coprime c a) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) (h_deg_add_le : degree (gcd a d[a]) + degree (gcd b d[b]) + degree (gcd c d[c]) ≤ degree a + degree b - 1) : degree c ≤ (degree a - degree (gcd a d[a])) + (degree b - degree (gcd b d[b])) + (degree c - degree (gcd c d[c])) - 1 := have 1 ≤ degree a + degree b, from rw_aux_1b a b c h_add h_constant, have h : ∀p:polynomial β, degree (gcd p d[p]) ≤ degree p, from (λ p, @degree_gcd_derivative_le_degree _ _ p), have (degree (gcd a d[a]) : ℤ) + (degree (gcd b d[b]) : ℤ) + (degree (gcd c d[c]) : ℤ) ≤ (degree a : ℤ) + (degree b : ℤ) - 1, by rwa [← int.coe_nat_add, ← int.coe_nat_add, ← int.coe_nat_add, ← int.coe_nat_one, ← int.coe_nat_sub this, int.coe_nat_le], have (degree c : ℤ) ≤ ((degree a : ℤ) - (degree (gcd a d[a]) : ℤ)) + ((degree b : ℤ) - (degree (gcd b d[b]) : ℤ)) + ((degree c : ℤ) - (degree (gcd c d[c]) : ℤ)) - 1, from calc (degree c : ℤ) ≤ ((degree c : ℤ) + ((degree a : ℤ) + (degree b : ℤ) - 1)) - ((degree (gcd a d[a]) : ℤ) + (degree (gcd b d[b]) : ℤ) + (degree (gcd c d[c]) : ℤ)) : le_sub_iff_add_le.mpr $ add_le_add_left this _ ... = _ : by simp, have 1 + (degree c : ℤ) ≤ ((degree a : ℤ) - (degree (gcd a d[a]) : ℤ)) + ((degree b : ℤ) - (degree (gcd b d[b]) : ℤ)) + ((degree c : ℤ) - (degree (gcd c d[c]) : ℤ)), from add_le_of_le_sub_left this, nat.le_sub_left_of_add_le $ by rwa [← int.coe_nat_sub (h _), ← int.coe_nat_sub (h _), ← int.coe_nat_sub (h _), ← int.coe_nat_add, ← int.coe_nat_add, ← int.coe_nat_one, ← int.coe_nat_add, int.coe_nat_le] at this /- lemma Mason_Stothers_lemma (f : polynomial β) : degree f ≤ degree (gcd f (derivative f )) + degree (rad f) -/ /- lemma Mason_Stothers_lemma' (f : polynomial β) : degree f - degree (gcd f (derivative f )) ≤ degree (rad f) := -/ /- --We will need extra conditions here lemma degree_rad_add {a b c : polynomial β}: degree (rad a) + degree (rad b) + degree (rad c) ≤ degree (rad (a * b * c)) := begin admit, end-/ lemma nat.add_mono{a b c d : ℕ} (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin exact calc a + c ≤ a + d : nat.add_le_add_left hcd _ ... ≤ b + d : nat.add_le_add_right hab _ end --h_le_rad lemma rw_aux_2 [field β] --We want to use the Mason Stothers lemmas here {a b c : polynomial β} (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) : degree a - degree (gcd a d[a]) + (degree b - degree (gcd b d[b])) + (degree c - degree (gcd c d[c])) - 1 ≤ degree (rad (a * b * c)) - 1:= begin apply nat.sub_le_sub_right, have h_rad: degree(rad(a))+degree(rad(b))+degree(rad(c)) ≤ degree(rad(a*b*c)), from h_rad_add ha hb hc h_coprime_ab h_coprime_bc h_coprime_ca, refine nat.le_trans _ h_rad, apply nat.add_mono _ (Mason_Stothers_lemma' c), apply nat.add_mono (Mason_Stothers_lemma' a) (Mason_Stothers_lemma' b), end private lemma h_dvd_wron_a (a b c : polynomial β): gcd a d[a] ∣ d[a] * b - a * d[b] := begin have h1 : gcd a d[a] ∣ d[a] * b, { apply dvd_trans gcd_right, apply dvd_mul_of_dvd_left, simp }, have h2 : gcd a d[a] ∣ a * d[b], { apply dvd_trans gcd_left, apply dvd_mul_of_dvd_left, simp }, exact dvd_sub h1 h2, end private lemma h_dvd_wron_b (a b c : polynomial β): gcd b d[b] ∣ d[a] * b - a * d[b] := begin have h1 : gcd b d[b] ∣ d[a] * b, { apply dvd_trans gcd_left, apply dvd_mul_of_dvd_right, simp }, have h2 : gcd b d[b] ∣ a * d[b], { apply dvd_trans gcd_right, apply dvd_mul_of_dvd_right, simp }, exact dvd_sub h1 h2, end private lemma h_dvd_wron_c (a b c : polynomial β) (h_wron : d[a] * b - a * d[b] = d[a] * c - a * d[c]) : gcd c d[c] ∣ d[a] * b - a * d[b] := begin rw h_wron, have h1 : gcd c d[c] ∣ a * d[c], { apply dvd_trans gcd_right, apply dvd_mul_of_dvd_right, simp }, have h2 : gcd c d[c] ∣ d[a] * c, { apply dvd_trans gcd_left, apply dvd_mul_of_dvd_right, simp }, exact dvd_sub h2 h1, end private lemma one_le_of_ne_zero {n : ℕ } (h : n ≠ 0) : 1 ≤ n := begin let m := some (nat.exists_eq_succ_of_ne_zero h), have h1 : n = nat.succ m, from some_spec (nat.exists_eq_succ_of_ne_zero h), rw [h1, nat.succ_le_succ_iff], exact nat.zero_le _, end /- Todo can we remove the a = 0, b = 0 cases? lemma degree_wron_le {a b : polynomial β} : degree (d[a] * b - a * d[b]) ≤ degree a + degree b - 1 := begin by_cases h1 : (a = 0), { simp *, exact nat.zero_le _, }, { by_cases h2 : (degree a = 0), { by_cases h3 : (b = 0), { rw h3, simp, exact nat.zero_le _, }, { simp [*], by_cases h4 : (degree b = 0), { simp *, rw [←is_constant_iff_degree_eq_zero] at *, have h5 : derivative a = 0, from derivative_eq_zero_of_is_constant h2, have h6 : derivative b = 0, from derivative_eq_zero_of_is_constant h4, simp *, }, { have h2a : degree a = 0, from h2, rw [←is_constant_iff_degree_eq_zero] at h2, have h5 : derivative a = 0, from derivative_eq_zero_of_is_constant h2, simp *, by_cases h6 : (derivative b = 0), { simp *, exact nat.zero_le _, }, { --rw [degree_neg], apply nat.le_trans degree_mul, simp *, exact degree_derivative_le, } }, } }, { by_cases h3 : (b = 0), { simp *, exact nat.zero_le _, }, { by_cases h4 : (degree b = 0), { simp *, rw [←is_constant_iff_degree_eq_zero] at h4, have h5 : derivative b = 0, from derivative_eq_zero_of_is_constant h4, simp *, apply nat.le_trans degree_mul, rw [is_constant_iff_degree_eq_zero] at h4, simp *, exact degree_derivative_le, }, { apply nat.le_trans degree_sub, have h5 : degree (d[a] * b) ≤ degree a + degree b - 1, { apply nat.le_trans degree_mul, rw [add_comm _ (degree b), add_comm _ (degree b), nat.add_sub_assoc], apply add_le_add_left, exact degree_derivative_le, exact polynomial.one_le_of_ne_zero h2, --Can I remove this from polynomial?? }, have h6 : (degree (a * d[b])) ≤ degree a + degree b - 1, { apply nat.le_trans degree_mul, rw [nat.add_sub_assoc], apply add_le_add_left, exact degree_derivative_le, exact polynomial.one_le_of_ne_zero h4, }, exact max_le h5 h6, } } } } end-/ lemma degree_wron_le {a b : polynomial β} : degree (d[a] * b - a * d[b]) ≤ degree a + degree b - 1 := begin by_cases h2 : (degree a = 0), { simp [is_constant_iff_degree_eq_zero, derivative_eq_zero_of_is_constant, *] at *, by_cases h6 : (derivative b = 0), { simp [nat.zero_le, *]}, { apply nat.le_trans degree_mul, simp [degree_derivative_le, *], } }, { by_cases h4 : (degree b = 0), --This case distinction shouldnn't be needed { simp [is_constant_iff_degree_eq_zero, derivative_eq_zero_of_is_constant, *] at *, apply nat.le_trans degree_mul, simp [degree_derivative_le, *], }, { apply nat.le_trans degree_sub, have h5 : degree (d[a] * b) ≤ degree a + degree b - 1, { apply nat.le_trans degree_mul, rw [add_comm _ (degree b), add_comm _ (degree b), nat.add_sub_assoc (polynomial.one_le_of_ne_zero h2)], apply add_le_add_left degree_derivative_le, }, have h6 : (degree (a * d[b])) ≤ degree a + degree b - 1, { apply nat.le_trans degree_mul, rw [nat.add_sub_assoc (polynomial.one_le_of_ne_zero h4)], apply add_le_add_left degree_derivative_le, }, exact max_le h5 h6, } } end private lemma h_wron_ne_zero (a b c : polynomial β) (h_coprime_ab : coprime a b) (h_coprime_ca : coprime c a) (h_der_not_all_zero : ¬(d[a] = 0 ∧ d[b] = 0 ∧ d[c] = 0)) (h_wron : d[a] * b - a * d[b] = d[a] * c - a * d[c]): d[a] * b - a * d[b] ≠ 0 := begin by_contradiction h1, rw not_not at h1, have h_a_b : d[a] = 0 ∧ d[b] = 0, from derivative_eq_zero_and_derivative_eq_zero_of_coprime_of_wron_eq_zero h_coprime_ab h1, have h2 : d[a] * c - a * d[c] = 0, {rw [←h_wron, h1]}, have h_a_c : d[a] = 0 ∧ d[c] = 0, from derivative_eq_zero_and_derivative_eq_zero_of_coprime_of_wron_eq_zero (h_coprime_ca.symm) h2, have h3 : (d[a] = 0 ∧ d[b] = 0 ∧ d[c] = 0), exact ⟨and.elim_left h_a_b, and.elim_right h_a_b, and.elim_right h_a_c⟩, contradiction end private lemma h_deg_add (a b c : polynomial β) (h_wron_ne_zero : d[a] * b - a * d[b] ≠ 0) (h_gcds_dvd : (gcd a d[a]) * (gcd b d[b]) * (gcd c d[c]) ∣ d[a] * b - a * d[b]): degree (gcd a d[a] * gcd b d[b] * gcd c d[c]) = degree (gcd a d[a]) + degree (gcd b d[b]) + degree (gcd c d[c]) := begin have h1 : gcd a d[a] * gcd b d[b] * gcd c d[c] ≠ 0, from ne_zero_of_dvd_ne_zero h_gcds_dvd h_wron_ne_zero, have h2 : degree (gcd a d[a] * gcd b d[b] * gcd c d[c]) = degree (gcd a d[a] * gcd b d[b]) + degree (gcd c d[c]), from degree_mul_eq_add_of_mul_ne_zero h1, have h3 : gcd a d[a] * gcd b d[b] ≠ 0, from ne_zero_of_mul_ne_zero_right h1, have h4 : degree (gcd a d[a] * gcd b d[b]) = degree (gcd a d[a]) + degree (gcd b d[b]), from degree_mul_eq_add_of_mul_ne_zero h3, rw [h2, h4], end private lemma h_wron (a b c : polynomial β) (h_add : a + b = c) (h_der : d[a] + d[b] = d[c]) : d[a] * b - a * d[b] = d[a] * c - a * d[c] := begin have h1 : d[a] * a + d[a] * b = d[a] * c, exact calc d[a] * a + d[a] * b = d[a] * (a + b) : by rw [mul_add] ... = _ : by rw h_add, have h2 : a * d[a] + a * d[b] = a * d[c], exact calc a * d[a] + a * d[b] = a * (d[a] + d[b]) : by rw [mul_add] ... = _ : by rw h_der, have h3 : d[a] * b - a * d[b] = d[a] * c - a * d[c], exact calc d[a] * b - a * d[b] = d[a] * b + (d[a] * a - d[a] * a) - a * d[b] : by simp ... = d[a] * b + d[a] * a - d[a] * a - a * d[b] : by simp ... = d[a] * c - (d[a] * a + a * d[b]) : by simp [h1] ... = d[a] * c - (a * d[a] + a * d[b]) : by rw [mul_comm _ a] ... = _ : by rw h2, exact h3 end private lemma h_gcds_dvd (a b c : polynomial β) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_dvd_wron_a : gcd a d[a] ∣ d[a] * b - a * d[b]) (h_dvd_wron_b : gcd b d[b] ∣ d[a] * b - a * d[b]) (h_dvd_wron_c : gcd c d[c] ∣ d[a] * b - a * d[b]): (gcd a d[a]) * (gcd b d[b]) * (gcd c d[c]) ∣ d[a] * b - a * d[b] := begin apply mul_dvd_of_dvd_of_dvd_of_coprime, apply coprime_mul_of_coprime_of_coprime_of_coprime, exact coprime_gcd_derivative_gcd_derivative_of_coprime (h_coprime_ca.symm) _ _, exact coprime_gcd_derivative_gcd_derivative_of_coprime h_coprime_bc _ _, apply mul_dvd_of_dvd_of_dvd_of_coprime, exact coprime_gcd_derivative_gcd_derivative_of_coprime h_coprime_ab _ _, exact h_dvd_wron_a, exact h_dvd_wron_b, exact h_dvd_wron_c end private lemma degree_rad_pos (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : degree (rad (a*b*c)) > 0 := begin apply gt_zero_of_ne_zero, rw [ne.def, degree_rad_eq_zero_iff_is_constant], simp only [not_and_distrib] at *, have : a * b ≠ 0, from mul_ne_zero ha hb, cases h_constant, { simp [not_is_constant_mul_of_not_is_constant_of_ne_zero, *]}, cases h_constant, { simp [mul_comm a, not_is_constant_mul_of_not_is_constant_of_ne_zero, *]}, { simp [mul_comm _ c, not_is_constant_mul_of_not_is_constant_of_ne_zero, *]} end theorem Mason_Stothers_special [field β] (h_char : characteristic_zero β) (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_add : a + b = c) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)) : degree c < degree ( rad (a*b*c)) := begin have h_der_not_all_zero : ¬(d[a] = 0 ∧ d[b] = 0 ∧ d[c] = 0), { rw [derivative_eq_zero_iff_is_constant h_char, derivative_eq_zero_iff_is_constant h_char, derivative_eq_zero_iff_is_constant h_char], exact h_constant, }, have h_der : d[a] + d[b] = d[c], { rw [←h_add, derivative_add], }, have h_wron : d[a] * b - a * d[b] = d[a] * c - a * d[c], from h_wron a b c h_add h_der, have h_dvd_wron_a : gcd a d[a] ∣ d[a] * b - a * d[b], from h_dvd_wron_a a b c, have h_dvd_wron_b : gcd b d[b] ∣ d[a] * b - a * d[b], from h_dvd_wron_b a b c, have h_dvd_wron_c : gcd c d[c] ∣ d[a] * b - a * d[b], from h_dvd_wron_c a b c h_wron, have h_gcds_dvd : (gcd a d[a]) * (gcd b d[b]) * (gcd c d[c]) ∣ d[a] * b - a * d[b], from h_gcds_dvd a b c h_coprime_ab h_coprime_bc h_coprime_ca h_dvd_wron_a h_dvd_wron_b h_dvd_wron_c, have h_wron_ne_zero : d[a] * b - a * d[b] ≠ 0, from h_wron_ne_zero a b c h_coprime_ab h_coprime_ca h_der_not_all_zero h_wron, have h_deg_add : degree (gcd a d[a] * gcd b d[b] * gcd c d[c]) = degree (gcd a d[a]) + degree (gcd b d[b]) + degree (gcd c d[c]), from h_deg_add a b c h_wron_ne_zero h_gcds_dvd, have h_deg_add_le : degree (gcd a d[a]) + degree (gcd b d[b]) + degree (gcd c d[c]) ≤ degree a + degree b - 1, { rw [←h_deg_add], have h1 : degree (gcd a d[a] * gcd b d[b] * gcd c d[c]) ≤ degree (d[a] * b - a * d[b]), from degree_dvd h_gcds_dvd h_wron_ne_zero, exact nat.le_trans h1 (degree_wron_le), }, have h_deg_c_le_1 : degree c ≤ (degree a - degree (gcd a d[a])) + (degree b - degree (gcd b d[b])) + (degree c - degree (gcd c d[c])) - 1, from rw_aux_1 a b c h_add h_constant h_deg_add_le, have h_le_rad : degree a - degree (gcd a d[a]) + (degree b - degree (gcd b d[b])) + (degree c - degree (gcd c d[c])) - 1 ≤ degree (rad (a * b * c)) - 1, from rw_aux_2 ha hb hc h_coprime_ab h_coprime_bc h_coprime_ca, have h_ms : degree c ≤ degree ( rad (a*b*c)) - 1, from nat.le_trans h_deg_c_le_1 h_le_rad, have h_eq : degree ( rad (a*b*c)) - 1 + 1 = degree ( rad (a*b*c)), { have h_pos : degree ( rad (a*b*c)) > 0, from degree_rad_pos a b c ha hb hc h_constant, apply nat.succ_pred_eq_of_pos h_pos, }, exact show degree c < degree ( rad (a*b*c)), from calc degree c + 1 ≤ degree ( rad (a*b*c) ) - 1 + 1 : by simp [h_ms] ... = degree ( rad (a*b*c)) : h_eq end --place in to_multiset private lemma cons_ne_zero {γ : Type u}(a : γ)(s : multiset γ): a :: s ≠ 0 := begin intro h, have : a ∈ a :: s, { simp, }, simp * at *, end --place in to_multiset --private? private lemma map_eq_zero_iff_eq_zero {γ ζ : Type u} (s : multiset γ)(f: γ → ζ): map f s = 0 ↔ s = 0 := begin apply multiset.induction_on s, { simp * at *, }, { intros a s h, split, { intro h1, simp * at *, have h2 : false, from cons_ne_zero _ _ h1, contradiction, }, { intro h1, simp * at *, }, } end --structure? lemma factors_eq_factors_of_associated {a b : polynomial β} (h : (a ~ᵤ b)): a.factors = b.factors := begin rw [factors_eq_map_monic_out_to_multiset_mk, factors_eq_map_monic_out_to_multiset_mk], rw [associated_iff_mk_eq_mk] at *, simp * at *, end @[simp] lemma rad_neg_eq_rad [field β] (p : polynomial β) : rad (-p) = rad p := begin have hp : (p ~ᵤ (-p)), from associated_neg _, have h1 : p.factors = (-p).factors, from factors_eq_factors_of_associated hp, rw [rad, rad, h1], end @[simp] lemma coprime_neg_iff_coprime_left {a b : polynomial β} : coprime (-a) b ↔ coprime a b := begin split, { intro h, apply coprime_of_coprime_of_associated_left h (associated_neg _), }, { intro h, apply coprime_of_coprime_of_associated_left h (associated_neg a).symm, --again elaborator does no longer find placeholder } end @[simp] lemma coprime_neg_iff_coprime_right {a b : polynomial β} : coprime a (-b) ↔ coprime a b := begin split, { intro h, apply coprime_of_coprime_of_associated_right h (associated_neg _), }, { intro h, apply coprime_of_coprime_of_associated_right h (associated_neg b).symm, } end private lemma neg_eq_zero_iff_eq_zero {a : polynomial β} : -a = 0 ↔ a = 0 := begin split, { intro h, exact calc a = -(-a) : by simp ... = - (0) : by rw h ... = _ : by simp }, { intro h, simp *, } end private lemma neg_ne_zero_iff_ne_zero {a : polynomial β} : -a ≠ 0 ↔ a ≠ 0 := not_iff_not_of_iff neg_eq_zero_iff_eq_zero local attribute [simp] is_constant_neg_iff_is_constant theorem Mason_Stothers_case_c [field β] (h_char : characteristic_zero β) (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_add : a + b + c = 0) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)): --You can do this one by cc? simpa [and.comm, and.left_comm, and.assoc] using h_constant degree c < degree ( rad (a*b*c)) := begin have h_c : degree (-c) < degree ( rad (a*b*(-c))), { have h_add : a + b = - c, { exact calc a + b = a + b + (c - c) : by simp ... = a + b + c - c : by simp ... = 0 - c : by rw [h_add] ... = _ : by simp, }, rw ←(is_constant_neg_iff_is_constant c) at h_constant, --The argument should not have been implicit apply Mason_Stothers_special h_char _ _ _ ha hb _ h_coprime_ab _ _ h_add h_constant,--We need relPrime.symm in general { simp [neg_ne_zero_iff_ne_zero, *], }, have : coprime b (-c),--Rather as rw, rather as simp rule, coprime a -c = coprime a c from coprime_neg_iff_coprime_right.2 h_coprime_bc, exact this, have : coprime (-c) a, from coprime_neg_iff_coprime_left.2 h_coprime_ca, exact this, }, have h_neg_abc: a * b * -c = - (a * b * c), { simp, }, rw [degree_neg, h_neg_abc, rad_neg_eq_rad] at h_c, exact h_c, end theorem Mason_Stothers_case_a [field β] (h_char : characteristic_zero β) (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_add : a + b + c = 0) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)): degree a < degree (rad (a*b*c)) := /- suffices degree a < degree (rad (c*b*a)), from Mason_Stothers_case_c h_char c b a hc hb ha _ _ _ _ _, _ -/ begin have h_a : degree (-a) < degree ( rad (b*c*(-a))), { have h_add_1 : b + c + a = 0, { simpa [add_comm, add_assoc] using h_add, }, have h_add_2 : b + c = - a, { exact calc b + c = b + c + (a - a) : by simp ... = b + c + a - a : by simp ... = 0 - a : by rw [h_add_1] ... = _ : by simp, }, have h_constant_2 : ¬(is_constant b ∧ is_constant c ∧ is_constant (-a)), { simpa [(is_constant_neg_iff_is_constant a), and_comm, and_assoc] using h_constant, intros h1 h2, simp *, }, apply Mason_Stothers_special h_char b c (-a) hb hc (neg_ne_zero_iff_ne_zero.2 ha) h_coprime_bc _ _ h_add_2 h_constant_2, { simp *, }, { simp *, }, }, have h_neg_abc: b * c * -a = - (a * b * c), { simp, exact calc b * c * a = b * (a * c) : by rw [mul_assoc, mul_comm c a] ... = _ : by rw [←mul_assoc, mul_comm b a], }, rw [degree_neg, h_neg_abc, rad_neg_eq_rad] at h_a, exact h_a, end theorem Mason_Stothers_case_b [field β] (h_char : characteristic_zero β) (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_add : a + b + c = 0) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)): degree b < degree ( rad (a*b*c)) := begin have h_b : degree (-b) < degree ( rad (a*c*(-b))), { have h_add_1 : a + c + b = 0, { simpa [add_comm, add_assoc] using h_add, }, have h_add_2 : a + c = - b, { exact calc a + c = a + c + (b - b) : by simp ... = a + c + b - b : by simp ... = 0 - b : by rw [h_add_1] ... = _ : by simp, }, have h_constant_2 : ¬(is_constant a ∧ is_constant c ∧ is_constant (-b)), { simpa [(is_constant_neg_iff_is_constant b), and_comm, and_assoc] using h_constant, }, apply Mason_Stothers_special h_char a c (-b) ha hc (neg_ne_zero_iff_ne_zero.2 hb) h_coprime_ca.symm _ _ h_add_2 h_constant_2, { simp [h_coprime_bc.symm, *], }, { simp [h_coprime_ab.symm, *], } }, have h_neg_abc: a * c * -b = - (a * b * c), { simp, exact calc a * c * b = a * (b * c) : by rw [mul_assoc, mul_comm c b] ... = _ : by rw [←mul_assoc], }, rw [degree_neg, h_neg_abc, rad_neg_eq_rad] at h_b, exact h_b, end theorem Mason_Stothers [field β] (h_char : characteristic_zero β) (a b c : polynomial β) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (h_coprime_ab : coprime a b) (h_coprime_bc : coprime b c) (h_coprime_ca : coprime c a) (h_add : a + b + c = 0) (h_constant : ¬(is_constant a ∧ is_constant b ∧ is_constant c)): max (degree a) (max (degree b) (degree c)) < degree ( rad (a*b*c)) := begin have h_a: degree a < degree ( rad (a*b*c)), from Mason_Stothers_case_a h_char a b c ha hb hc h_coprime_ab h_coprime_bc h_coprime_ca h_add h_constant, have h_b: degree b < degree ( rad (a*b*c)), from Mason_Stothers_case_b h_char a b c ha hb hc h_coprime_ab h_coprime_bc h_coprime_ca h_add h_constant, have h_c: degree c < degree ( rad (a*b*c)), from Mason_Stothers_case_c h_char a b c ha hb hc h_coprime_ab h_coprime_bc h_coprime_ca h_add h_constant, apply max_lt h_a, apply max_lt h_b h_c, end end mason_stothers
c2d858aa53ee95f83e729955181870a0a4c9160c
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/pp.lean
144942e54976329fe52ee8231ec4a9816817d8d5
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
420
lean
prelude check λ {A : Type.{1}} (B : Type.{1}) (a : A) (b : B), a check λ {A : Type.{1}} {B : Type.{1}} (a : A) (b : B), a check λ (A : Type.{1}) {B : Type.{1}} (a : A) (b : B), a check λ (A : Type.{1}) (B : Type.{1}) (a : A) (b : B), a check λ [A : Type.{1}] (B : Type.{1}) (a : A) (b : B), a check λ {{A : Type.{1}}} {B : Type.{1}} (a : A) (b : B), a check λ {{A : Type.{1}}} {{B : Type.{1}}} (a : A) (b : B), a
2a4671744f094a4275847ecc903819f47030981a
65b579fba1b0b66add04cccd4529add645eff597
/expression2.lean
c3c4b76475d12e8b9823477e379e1c8d0bd09cd0
[]
no_license
teodorov/sf_lean
ba637ca8ecc538aece4d02c8442d03ef713485db
cd4832d6bee9c606014c977951f6aebc4c8d611b
refs/heads/master
1,632,890,232,054
1,543,005,745,000
1,543,005,745,000
108,566,115
1
0
null
null
null
null
UTF-8
Lean
false
false
2,720
lean
-- inspired from https://github.com/UlfNorell/agda-summer-school/blob/OPLSS/lectures/Day1.agda open nat inductive EType | enat | ebool open EType def Ctx := list EType --debrujin indices, a fancy natural number inductive IN {A : Type} : A → list A → Type | Zero : ∀ {x xs}, IN x (x::xs) | Succ : ∀ {x y xs}, IN x (x::xs) → IN x (y::xs) --notation a ` ∈ ` b := IN a b -- the environment which has elements of different types -- at different indices, corresponding to the types in Γ inductive All {A : Type} (P : A → Type) : list A → Type | empty : All [] | cons : ∀ {x xs}, P x → All xs → All (x::xs) open All inductive Any {A : Type} (P : A → Prop) : list A → Type | zero : ∀ {x xs}, P x → Any (x::xs) | succ : ∀ {x xs}, Any xs → Any (x::xs). def IN' {A : Type} (x : A) (xs : list A) : Type := Any (λ y, eq x y) xs inductive Expr : Ctx → EType → Type | evar {α Γ} : IN' α Γ → Expr Γ α | elit {Γ} : ℕ → Expr Γ enat | ett {Γ} : Expr Γ ebool | eff {Γ} : Expr Γ ebool | eless {Γ} (a b : Expr Γ enat) : Expr Γ ebool | eplus {Γ} (a b : Expr Γ enat) : Expr Γ enat | eif {α Γ} (a : Expr Γ ebool) (b c : Expr Γ α) : Expr Γ α open Expr def Value : EType → Type | enat := nat | ebool := bool def lookup : ∀ {A} { P : A → Type} {x xs}, IN' x xs → All P xs → P x | _ _ _ _ (Any.zero (eq.refl _)) (cons w ps) := w | _ _ _ _ (Any.succ i) (cons w ps) := lookup i ps def Env : Ctx → Type := λ Γ, All Value Γ set_option eqn_compiler.lemmas false def eval : ∀ {α Γ}, Env Γ → Expr Γ α → Value α | _ _ env (evar x) := lookup x env | _ _ env (elit n) := n | _ _ env (ett) := true | _ _ env (eff) := false | _ _ env (eless e₁ e₂) := nat.lt (eval env e₁) (eval env e₂) | _ _ env (eplus e₁ e₂) := nat.add (eval env e₁) (eval env e₂) | _ _ env (eif e₁ e₂ e₃) := if (eval env e₁ = true) then (eval env e₂) else (eval env e₃) def Γ : Ctx := enat :: ebool :: []. def ex_env : Env Γ := (cons (5:ℕ) (cons ff (empty Value))). def ex_lit : Expr Γ enat := elit 2 def ex_ett : Expr Γ ebool := ett def ex_eff : Expr Γ ebool := eff def ex_expr0 : Expr Γ ebool := eless (elit 2) (elit 3) def ex_expr1 : Expr Γ ebool := eif (eless (elit 2) (elit 3)) (ett) (eff) def inxxx : Any (λ y, eq enat y) Γ := Any.zero (eq.refl _) def zero : IN' enat Γ := Any.zero (eq.refl _) def one : IN' ebool Γ := Any.succ (Any.zero (eq.refl _)) def ex_var0 : Expr Γ enat := evar (Any.zero (eq.refl _)) def ex_var1 : Expr Γ ebool := evar (Any.succ (Any.zero (eq.refl _))) def ex_expr : Expr Γ enat := eif (evar one) (evar zero) (eplus (elit 4) (evar zero)) #reduce eval ex_env ex_expr
5fea936a13a0d2a004fa57222b7227e0b7b07f45
fe25de614feb5587799621c41487aaee0d083b08
/src/Lean/Expr.lean
d0f71ca6fc8cb92fae238822231978ebc2e77fd2
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,280
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Level namespace Lean inductive Literal where | natVal (val : Nat) | strVal (val : String) deriving Inhabited, BEq, Repr protected def Literal.hash : Literal → UInt64 | Literal.natVal v => hash v | Literal.strVal v => hash v instance : Hashable Literal := ⟨Literal.hash⟩ def Literal.lt : Literal → Literal → Bool | Literal.natVal _, Literal.strVal _ => true | Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂ | Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂ | _, _ => false instance : LT Literal := ⟨fun a b => a.lt b⟩ instance (a b : Literal) : Decidable (a < b) := inferInstanceAs (Decidable (a.lt b)) inductive BinderInfo where | default | implicit | strictImplicit | instImplicit | auxDecl deriving Inhabited, BEq def BinderInfo.hash : BinderInfo → UInt64 | BinderInfo.default => 947 | BinderInfo.implicit => 1019 | BinderInfo.strictImplicit => 1087 | BinderInfo.instImplicit => 1153 | BinderInfo.auxDecl => 1229 def BinderInfo.isExplicit : BinderInfo → Bool | BinderInfo.implicit => false | BinderInfo.strictImplicit => false | BinderInfo.instImplicit => false | _ => true instance : Hashable BinderInfo := ⟨BinderInfo.hash⟩ def BinderInfo.isInstImplicit : BinderInfo → Bool | BinderInfo.instImplicit => true | _ => false def BinderInfo.isImplicit : BinderInfo → Bool | BinderInfo.implicit => true | _ => false def BinderInfo.isAuxDecl : BinderInfo → Bool | BinderInfo.auxDecl => true | _ => false abbrev MData := KVMap abbrev MData.empty : MData := {} /-- Cached hash code, cached results, and other data for `Expr`. hash : 32-bits hasFVar : 1-bit hasExprMVar : 1-bit hasLevelMVar : 1-bit hasLevelParam : 1-bit nonDepLet : 1-bit binderInfo : 3-bits looseBVarRange : 24-bits -/ def Expr.Data := UInt64 instance: Inhabited Expr.Data := inferInstanceAs (Inhabited UInt64) def Expr.Data.hash (c : Expr.Data) : UInt64 := c.toUInt32.toUInt64 instance : BEq Expr.Data where beq (a b : UInt64) := a == b def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 := (c.shiftRight 40).toUInt32 def Expr.Data.hasFVar (c : Expr.Data) : Bool := ((c.shiftRight 32).land 1) == 1 def Expr.Data.hasExprMVar (c : Expr.Data) : Bool := ((c.shiftRight 33).land 1) == 1 def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool := ((c.shiftRight 34).land 1) == 1 def Expr.Data.hasLevelParam (c : Expr.Data) : Bool := ((c.shiftRight 35).land 1) == 1 def Expr.Data.nonDepLet (c : Expr.Data) : Bool := ((c.shiftRight 36).land 1) == 1 @[extern c inline "(uint8_t)((#1 << 24) >> 61)"] def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo := let bi := (c.shiftLeft 24).shiftRight 61 if bi == 0 then BinderInfo.default else if bi == 1 then BinderInfo.implicit else if bi == 2 then BinderInfo.strictImplicit else if bi == 3 then BinderInfo.instImplicit else BinderInfo.auxDecl @[extern c inline "(uint64_t)#1"] def BinderInfo.toUInt64 : BinderInfo → UInt64 | BinderInfo.default => 0 | BinderInfo.implicit => 1 | BinderInfo.strictImplicit => 2 | BinderInfo.instImplicit => 3 | BinderInfo.auxDecl => 4 @[inline] private def Expr.mkDataCore (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo) : Expr.Data := if looseBVarRange > Nat.pow 2 24 - 1 then panic! "bound variable index is too big" else let r : UInt64 := h.toUInt32.toUInt64 + hasFVar.toUInt64.shiftLeft 32 + hasExprMVar.toUInt64.shiftLeft 33 + hasLevelMVar.toUInt64.shiftLeft 34 + hasLevelParam.toUInt64.shiftLeft 35 + nonDepLet.toUInt64.shiftLeft 36 + bi.toUInt64.shiftLeft 37 + looseBVarRange.toUInt64.shiftLeft 40 r def Expr.mkData (h : UInt64) (looseBVarRange : Nat := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data := Expr.mkDataCore h looseBVarRange hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default open Expr abbrev MVarId := Name abbrev FVarId := Name /- We use the `E` suffix (short for `Expr`) to avoid collision with keywords. We considered using «...», but it is too inconvenient to use. -/ inductive Expr where | bvar : Nat → Data → Expr -- bound variables | fvar : FVarId → Data → Expr -- free variables | mvar : MVarId → Data → Expr -- meta variables | sort : Level → Data → Expr -- Sort | const : Name → List Level → Data → Expr -- constants | app : Expr → Expr → Data → Expr -- application | lam : Name → Expr → Expr → Data → Expr -- lambda abstraction | forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow | letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions | lit : Literal → Data → Expr -- literals | mdata : MData → Expr → Data → Expr -- metadata | proj : Name → Nat → Expr → Data → Expr -- projection deriving Inhabited namespace Expr @[inline] def data : Expr → Data | bvar _ d => d | fvar _ d => d | mvar _ d => d | sort _ d => d | const _ _ d => d | app _ _ d => d | lam _ _ _ d => d | forallE _ _ _ d => d | letE _ _ _ _ d => d | lit _ d => d | mdata _ _ d => d | proj _ _ _ d => d def ctorName : Expr → String | bvar _ _ => "bvar" | fvar _ _ => "fvar" | mvar _ _ => "mvar" | sort _ _ => "sort" | const _ _ _ => "const" | app _ _ _ => "app" | lam _ _ _ _ => "lam" | forallE _ _ _ _ => "forallE" | letE _ _ _ _ _ => "letE" | lit _ _ => "lit" | mdata _ _ _ => "mdata" | proj _ _ _ _ => "proj" protected def hash (e : Expr) : UInt64 := e.data.hash instance : Hashable Expr := ⟨Expr.hash⟩ def hasFVar (e : Expr) : Bool := e.data.hasFVar def hasExprMVar (e : Expr) : Bool := e.data.hasExprMVar def hasLevelMVar (e : Expr) : Bool := e.data.hasLevelMVar def hasMVar (e : Expr) : Bool := let d := e.data d.hasExprMVar || d.hasLevelMVar def hasLevelParam (e : Expr) : Bool := e.data.hasLevelParam def looseBVarRange (e : Expr) : Nat := e.data.looseBVarRange.toNat def binderInfo (e : Expr) : BinderInfo := e.data.binderInfo @[export lean_expr_hash] def hashEx : Expr → UInt64 := hash @[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar @[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar @[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar @[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar @[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam @[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange @[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo end Expr def mkConst (n : Name) (lvls : List Level := []) : Expr := Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam) def Literal.type : Literal → Expr | Literal.natVal _ => mkConst `Nat | Literal.strVal _ => mkConst `String @[export lean_lit_type] def Literal.typeEx : Literal → Expr := Literal.type def mkBVar (idx : Nat) : Expr := Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1) def mkSort (lvl : Level) : Expr := Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 false false lvl.hasMVar lvl.hasParam def mkFVar (fvarId : FVarId) : Expr := Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 true def mkMVar (fvarId : MVarId) : Expr := Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 false true def mkMData (d : MData) (e : Expr) : Expr := Expr.mdata d e $ mkData (mixHash 19 $ hash e) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkProj (s : Name) (i : Nat) (e : Expr) : Expr := Expr.proj s i e $ mkData (mixHash 23 $ mixHash (hash s) $ mixHash (hash i) (hash e)) e.looseBVarRange e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkApp (f a : Expr) : Expr := Expr.app f a $ mkData (mixHash 29 $ mixHash (hash f) (hash a)) (Nat.max f.looseBVarRange a.looseBVarRange) (f.hasFVar || a.hasFVar) (f.hasExprMVar || a.hasExprMVar) (f.hasLevelMVar || a.hasLevelMVar) (f.hasLevelParam || a.hasLevelParam) def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes Expr.lam x t b $ mkDataForBinder (mixHash 31 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := -- let x := x.eraseMacroScopes Expr.forallE x t b $ mkDataForBinder (mixHash 37 $ mixHash (hash t) (hash b)) (Nat.max t.looseBVarRange (b.looseBVarRange - 1)) (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi /- Return `Unit -> type`. Do not confuse with `Thunk type` -/ def mkSimpleThunkType (type : Expr) : Expr := mkForall Name.anonymous BinderInfo.default (Lean.mkConst `Unit) type /- Return `fun (_ : Unit), e` -/ def mkSimpleThunk (type : Expr) : Expr := mkLambda `_ BinderInfo.default (Lean.mkConst `Unit) type def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr := -- let x := x.eraseMacroScopes Expr.letE x t v b $ mkDataForLet (mixHash 41 $ mixHash (hash t) $ mixHash (hash v) (hash b)) (Nat.max (Nat.max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1)) (t.hasFVar || v.hasFVar || b.hasFVar) (t.hasExprMVar || v.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || v.hasLevelParam || b.hasLevelParam) nonDep def mkAppB (f a b : Expr) := mkApp (mkApp f a) b def mkApp2 (f a b : Expr) := mkAppB f a b def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂ def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃ def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆ def mkLit (l : Literal) : Expr := Expr.lit l $ mkData (mixHash 3 (hash l)) def mkRawNatLit (n : Nat) : Expr := mkLit (Literal.natVal n) def mkNatLit (n : Nat) : Expr := let r := mkRawNatLit n mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r) def mkStrLit (s : String) : Expr := mkLit (Literal.strVal s) @[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar @[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar @[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar @[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort @[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls @[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp @[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b @[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b @[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b @[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit @[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData @[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj def mkAppN (f : Expr) (args : Array Expr) : Expr := args.foldl mkApp f private partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr := if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e /-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/ def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr := mkAppRangeAux j args i f def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr := revArgs.foldr (fun a r => mkApp r a) fn namespace Expr -- TODO: implement it in Lean @[extern "lean_expr_dbg_to_string"] constant dbgToString (e : @& Expr) : String @[extern "lean_expr_quick_lt"] constant quickLt (a : @& Expr) (b : @& Expr) : Bool @[extern "lean_expr_lt"] constant lt (a : @& Expr) (b : @& Expr) : Bool /- Return true iff `a` and `b` are alpha equivalent. Binder annotations are ignored. -/ @[extern "lean_expr_eqv"] constant eqv (a : @& Expr) (b : @& Expr) : Bool instance : BEq Expr where beq := Expr.eqv /- Return true iff `a` and `b` are equal. Binder names and annotations are taking into account. -/ @[extern "lean_expr_equal"] constant equal (a : @& Expr) (b : @& Expr) : Bool def isSort : Expr → Bool | sort _ _ => true | _ => false def isProp : Expr → Bool | sort (Level.zero ..) _ => true | _ => false def isBVar : Expr → Bool | bvar _ _ => true | _ => false def isMVar : Expr → Bool | mvar _ _ => true | _ => false def isFVar : Expr → Bool | fvar _ _ => true | _ => false def isApp : Expr → Bool | app .. => true | _ => false def isProj : Expr → Bool | proj .. => true | _ => false def isConst : Expr → Bool | const .. => true | _ => false def isConstOf : Expr → Name → Bool | const n _ _, m => n == m | _, _ => false def isForall : Expr → Bool | forallE .. => true | _ => false def isLambda : Expr → Bool | lam .. => true | _ => false def isBinding : Expr → Bool | lam .. => true | forallE .. => true | _ => false def isLet : Expr → Bool | letE .. => true | _ => false def isMData : Expr → Bool | mdata .. => true | _ => false def isLit : Expr → Bool | lit .. => true | _ => false def getForallBody : Expr → Expr | forallE _ _ b .. => getForallBody b | e => e def getAppFn : Expr → Expr | app f a _ => getAppFn f | e => e def getAppNumArgsAux : Expr → Nat → Nat | app f a _, n => getAppNumArgsAux f (n+1) | e, n => n def getAppNumArgs (e : Expr) : Nat := getAppNumArgsAux e 0 private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr | app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1) | _, as, _ => as @[inline] def getAppArgs (e : Expr) : Array Expr := let dummy := mkSort levelZero let nargs := e.getAppNumArgs getAppArgsAux e (mkArray nargs dummy) (nargs-1) private def getAppRevArgsAux : Expr → Array Expr → Array Expr | app f a _, as => getAppRevArgsAux f (as.push a) | _, as => as @[inline] def getAppRevArgs (e : Expr) : Array Expr := getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs) @[specialize] def withAppAux (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α | app f a _, as, i => withAppAux k f (as.set! i a) (i-1) | f, as, i => k f as @[inline] def withApp (e : Expr) (k : Expr → Array Expr → α) : α := let dummy := mkSort levelZero let nargs := e.getAppNumArgs withAppAux k e (mkArray nargs dummy) (nargs-1) @[specialize] private def withAppRevAux (k : Expr → Array Expr → α) : Expr → Array Expr → α | app f a _, as => withAppRevAux k f (as.push a) | f, as => k f as @[inline] def withAppRev (e : Expr) (k : Expr → Array Expr → α) : α := withAppRevAux k e (Array.mkEmpty e.getAppNumArgs) def getRevArgD : Expr → Nat → Expr → Expr | app f a _, 0, _ => a | app f _ _, i+1, v => getRevArgD f i v | _, _, v => v def getRevArg! : Expr → Nat → Expr | app f a _, 0 => a | app f _ _, i+1 => getRevArg! f i | _, _ => panic! "invalid index" @[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := getRevArg! e (n - i - 1) @[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr := getRevArgD e (n - i - 1) v₀ def isAppOf (e : Expr) (n : Name) : Bool := match e.getAppFn with | const c _ _ => c == n | _ => false def isAppOfArity : Expr → Name → Nat → Bool | const c _ _, n, 0 => c == n | app f _ _, n, a+1 => isAppOfArity f n a | _, _, _ => false def appFn! : Expr → Expr | app f _ _ => f | _ => panic! "application expected" def appArg! : Expr → Expr | app _ a _ => a | _ => panic! "application expected" def isNatLit : Expr → Bool | lit (Literal.natVal _) _ => true | _ => false def natLit? : Expr → Option Nat | lit (Literal.natVal v) _ => v | _ => none def isStringLit : Expr → Bool | lit (Literal.strVal _) _ => true | _ => false def isCharLit (e : Expr) : Bool := e.isAppOfArity `Char.ofNat 1 && e.appArg!.isNatLit def constName! : Expr → Name | const n _ _ => n | _ => panic! "constant expected" def constName? : Expr → Option Name | const n _ _ => some n | _ => none def constLevels! : Expr → List Level | const _ ls _ => ls | _ => panic! "constant expected" def bvarIdx! : Expr → Nat | bvar idx _ => idx | _ => panic! "bvar expected" def fvarId! : Expr → FVarId | fvar n _ => n | _ => panic! "fvar expected" def mvarId! : Expr → MVarId | mvar n _ => n | _ => panic! "mvar expected" def bindingName! : Expr → Name | forallE n _ _ _ => n | lam n _ _ _ => n | _ => panic! "binding expected" def bindingDomain! : Expr → Expr | forallE _ d _ _ => d | lam _ d _ _ => d | _ => panic! "binding expected" def bindingBody! : Expr → Expr | forallE _ _ b _ => b | lam _ _ b _ => b | _ => panic! "binding expected" def bindingInfo! : Expr → BinderInfo | forallE _ _ _ c => c.binderInfo | lam _ _ _ c => c.binderInfo | _ => panic! "binding expected" def letName! : Expr → Name | letE n _ _ _ _ => n | _ => panic! "let expression expected" def consumeMData : Expr → Expr | mdata _ e _ => consumeMData e | e => e def hasLooseBVars (e : Expr) : Bool := e.looseBVarRange > 0 /- Remark: the following function assumes `e` does not have loose bound variables. -/ def isArrow (e : Expr) : Bool := match e with | forallE _ _ b _ => !b.hasLooseBVars | _ => false @[extern "lean_expr_has_loose_bvar"] constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool /-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/ def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool | Expr.forallE _ d b c, bvarIdx, tryRange => (c.binderInfo.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange | e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx /-- Lower the loose bound variables `>= s` in `e` by `d`. That is, a loose bound variable `bvar i`. `i >= s` is mapped into `bvar (i-d)`. Remark: if `s < d`, then result is `e` -/ @[extern "lean_expr_lower_loose_bvars"] constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- Lift loose bound variables `>= s` in `e` by `d`. -/ @[extern "lean_expr_lift_loose_bvars"] constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- `inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type. It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or the resulting type if `considerRange == true`. Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections. When the `{}` annotation is used in these commands, we set `considerRange == false`. -/ def inferImplicit : Expr → Nat → Bool → Expr | Expr.forallE n d b c, i+1, considerRange => let b := inferImplicit b i considerRange let newInfo := if c.binderInfo.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else c.binderInfo mkForall n newInfo d b | e, 0, _ => e | e, _, _ => e /-- Instantiate the loose bound variables in `e` using `subst`. That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/ @[extern "lean_expr_instantiate"] constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr @[extern "lean_expr_instantiate1"] constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr /-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/ @[extern "lean_expr_instantiate_rev"] constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr /-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_range"] constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_rev_range"] constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Replace free variables `xs` with loose bound variables. -/ @[extern "lean_expr_abstract"] constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr /-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/ @[extern "lean_expr_abstract_range"] constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr /-- Replace occurrences of the free variable `fvar` in `e` with `v` -/ def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr := (e.abstract #[fvar]).instantiate1 v /-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/ def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr := replaceFVar e (mkFVar fvarId) v /-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/ def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr := (e.abstract fvars).instantiateRev vs instance : ToString Expr where toString := Expr.dbgToString def isAtomic : Expr → Bool | Expr.const _ _ _ => true | Expr.sort _ _ => true | Expr.bvar _ _ => true | Expr.lit _ _ => true | Expr.mvar _ _ => true | Expr.fvar _ _ => true | _ => false end Expr def mkDecIsTrue (pred proof : Expr) := mkAppB (mkConst `Decidable.isTrue) pred proof def mkDecIsFalse (pred proof : Expr) := mkAppB (mkConst `Decidable.isFalse) pred proof open Std (HashMap HashSet PHashMap PHashSet) abbrev ExprMap (α : Type) := HashMap Expr α abbrev PersistentExprMap (α : Type) := PHashMap Expr α abbrev ExprSet := HashSet Expr abbrev PersistentExprSet := PHashSet Expr abbrev PExprSet := PersistentExprSet /- Auxiliary type for forcing `==` to be structural equality for `Expr` -/ structure ExprStructEq where val : Expr deriving Inhabited instance : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩ namespace ExprStructEq protected def beq : ExprStructEq → ExprStructEq → Bool | ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂ protected def hash : ExprStructEq → UInt64 | ⟨e⟩ => e.hash instance : BEq ExprStructEq := ⟨ExprStructEq.beq⟩ instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩ instance : ToString ExprStructEq := ⟨fun e => toString e.val⟩ end ExprStructEq abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α namespace Expr private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr := if i == start then b else let i := i - 1 mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i /-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/ def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr := mkAppRevRangeAux revArgs beginIdx f endIdx private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr | Expr.lam _ _ b _, i => if i + 1 < sz then betaRevAux revArgs sz b (i+1) else let n := sz - (i + 1) mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs | Expr.mdata _ b _, i => betaRevAux revArgs sz b i | b, i => let n := sz - i mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs /-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`. This function is often used with `getAppRev` or `withAppRev`. Examples: - `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y` - `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y` - `betaRev (fun x y => t x y) #[a, b]` ==> t b a` - `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a` Suppose `t` is `(fun x y => t x y) a b c d`, then `args := t.getAppRev` is `#[d, c, b, a]`, and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/ def betaRev (f : Expr) (revArgs : Array Expr) : Expr := if revArgs.size == 0 then f else betaRevAux revArgs revArgs.size f 0 def isHeadBetaTargetFn : Expr → Bool | Expr.lam _ _ _ _ => true | Expr.mdata _ b _ => isHeadBetaTargetFn b | _ => false def headBeta (e : Expr) : Expr := let f := e.getAppFn if f.isHeadBetaTargetFn then betaRev f e.getAppRevArgs else e def isHeadBetaTarget (e : Expr) : Bool := e.getAppFn.isHeadBetaTargetFn private def etaExpandedBody : Expr → Nat → Nat → Option Expr | app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none | _, n+1, _ => none | f, 0, _ => if f.hasLooseBVars then none else some f private def etaExpandedAux : Expr → Nat → Option Expr | lam _ _ b _, n => etaExpandedAux b (n+1) | e, n => etaExpandedBody e n 0 /-- If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`, then return `some f`. Otherwise, return `none`. It assumes `e` does not have loose bound variables. Remark: `ₙ` may be 0 -/ def etaExpanded? (e : Expr) : Option Expr := etaExpandedAux e 0 /-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/ def etaExpandedStrict? : Expr → Option Expr | lam _ _ b _ => etaExpandedAux b 1 | _ => none def getOptParamDefault? (e : Expr) : Option Expr := if e.isAppOfArity `optParam 2 then some e.appArg! else none def getAutoParamTactic? (e : Expr) : Option Expr := if e.isAppOfArity `autoParam 2 then some e.appArg! else none def isOptParam (e : Expr) : Bool := e.isAppOfArity `optParam 2 def isAutoParam (e : Expr) : Bool := e.isAppOfArity `autoParam 2 /-- Return true iff `e` contains a free variable which statisfies `p`. -/ @[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool := let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else match e with | Expr.forallE _ d b _ => visit d || visit b | Expr.lam _ d b _ => visit d || visit b | Expr.mdata _ e _ => visit e | Expr.letE _ t v b _ => visit t || visit v || visit b | Expr.app f a _ => visit f || visit a | Expr.proj _ _ e _ => visit e | e@(Expr.fvar fvarId _) => p fvarId | e => false visit e def containsFVar (e : Expr) (fvarId : FVarId) : Bool := e.hasAnyFVar (· == fvarId) /- The update functions here are defined using C code. They will try to avoid allocating new values using pointer equality. The hypotheses `(h : e.is...)` are used to ensure Lean will not crash at runtime. The `update*!` functions are inlined and provide a convenient way of using the update proofs without providing proofs. Note that if they are used under a match-expression, the compiler will eliminate the double-match. -/ @[extern "lean_expr_update_app"] def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp) : Expr := mkApp newFn newArg @[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr := match e with | app fn arg c => updateApp (app fn arg c) newFn newArg rfl | _ => panic! "application expected" @[extern "lean_expr_update_const"] def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst) : Expr := mkConst e.constName! newLevels @[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr := match e with | const n ls c => updateConst (const n ls c) newLevels rfl | _ => panic! "constant expected" @[extern "lean_expr_update_sort"] def updateSort (e : Expr) (newLevel : Level) (h : e.isSort) : Expr := mkSort newLevel @[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr := match e with | sort l c => updateSort (sort l c) newLevel rfl | _ => panic! "level expected" @[extern "lean_expr_update_proj"] def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj) : Expr := match e with | proj s i _ _ => mkProj s i newExpr | _ => e -- unreachable because of `h` @[extern "lean_expr_update_mdata"] def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData) : Expr := match e with | mdata d _ _ => mkMData d newExpr | _ => e -- unreachable because of `h` @[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr := match e with | mdata d e c => updateMData (mdata d e c) newExpr rfl | _ => panic! "mdata expected" @[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr := match e with | proj s i e c => updateProj (proj s i e c) newExpr rfl | _ => panic! "proj expected" @[extern "lean_expr_update_forall"] def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall) : Expr := mkForall e.bindingName! newBinfo newDomain newBody @[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl | _ => panic! "forall expected" @[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "forall expected" @[extern "lean_expr_update_lambda"] def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda) : Expr := mkLambda e.bindingName! newBinfo newDomain newBody @[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl | _ => panic! "lambda expected" @[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "lambda expected" @[extern "lean_expr_update_let"] def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet) : Expr := mkLet e.letName! newType newVal newBody @[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr := match e with | letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl | _ => panic! "let expression expected" def updateFn : Expr → Expr → Expr | e@(app f a _), g => e.updateApp! (updateFn f g) a | _, g => g partial def eta (e : Expr) : Expr := match e with | Expr.lam _ d b _ => let b' := b.eta match b' with | Expr.app f (Expr.bvar 0 _) _ => if !f.hasLooseBVar 0 then f.lowerLooseBVars 1 1 else e.updateLambdaE! d b' | _ => e.updateLambdaE! d b' | _ => e /- Instantiate level parameters -/ @[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr := let rec @[specialize] visit (e : Expr) : Expr := if !e.hasLevelParam then e else match e with | lam n d b _ => e.updateLambdaE! (visit d) (visit b) | forallE n d b _ => e.updateForallE! (visit d) (visit b) | letE n t v b _ => e.updateLet! (visit t) (visit v) (visit b) | app f a _ => e.updateApp! (visit f) (visit a) | proj _ _ s _ => e.updateProj! (visit s) | mdata _ b _ => e.updateMData! (visit b) | const _ us _ => e.updateConst! (us.map (fun u => u.instantiateParams s)) | sort u _ => e.updateSort! (u.instantiateParams s) | e => e visit e private def getParamSubst : List Name → List Level → Name → Option Level | p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p' | _, _, _ => none def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := instantiateLevelParamsCore (getParamSubst paramNames lvls) e private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level := if h : i < ps.size then let p := ps.get ⟨i, h⟩ if h : i < us.size then let u := us.get ⟨i, h⟩ if p == p' then some u else getParamSubstArray ps us p' (i+1) else none else none def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr := instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e /- Annotate `e` with the given option. -/ def setOption (e : Expr) (optionName : Name) [KVMap.Value α] (val : α) : Expr := mkMData (MData.empty.set optionName val) e /- Annotate `e` with `pp.explicit := true` The delaborator uses `pp` options. -/ def setPPExplicit (e : Expr) (flag : Bool) := e.setOption `pp.explicit flag def setPPUniverses (e : Expr) (flag : Bool) := e.setOption `pp.universes flag /- If `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`, and annotate `e` with `pp.explicit := true`. -/ def setAppPPExplicit (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map (·.setPPExplicit false) mkAppN f args |>.setPPExplicit true | _ => e /- Similar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if `e` does not contain metavariables. -/ def setAppPPExplicitForExposingMVars (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false mkAppN f args |>.setPPExplicit true | _ => e end Expr def mkAnnotation (kind : Name) (e : Expr) : Expr := mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e def annotation? (kind : Name) (e : Expr) : Option Expr := match e with | Expr.mdata d b _ => if d.size == 1 && d.getBool kind false then some b else none | _ => none def mkFreshFVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId def mkFreshMVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := mkFreshId end Lean
dd9c12fd5e8bf18b6b481490e8ae6e2af93e1bd7
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/331.lean
4e5a7040798f4cd94b332570c47fae027ce5ca28
[ "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
318
lean
namespace nat inductive less (a : nat) : nat → Prop := | base : less a (succ a) | step : Π {b}, less a b → less a (succ b) end nat open nat check less.rec_on namespace foo1 protected definition foo2.bar : nat := 10 end foo1 example : foo1.foo2.bar = 10 := rfl open foo1 example : foo2.bar = 10 := rfl
fdb3d298a52a24928f3d92ca5306f743503d1ba1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/manifold/local_invariant_properties.lean
f4ee2b421d5ade228a7f520797fea61c3026e369
[ "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
30,211
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, Floris van Doorn -/ import geometry.manifold.charted_space /-! # Local properties invariant under a groupoid We study properties of a triple `(g, s, x)` where `g` is a function between two spaces `H` and `H'`, `s` is a subset of `H` and `x` is a point of `H`. Our goal is to register how such a property should behave to make sense in charted spaces modelled on `H` and `H'`. The main examples we have in mind are the properties "`g` is differentiable at `x` within `s`", or "`g` is smooth at `x` within `s`". We want to develop general results that, when applied in these specific situations, say that the notion of smooth function in a manifold behaves well under restriction, intersection, is local, and so on. ## Main definitions * `local_invariant_prop G G' P` says that a property `P` of a triple `(g, s, x)` is local, and invariant under composition by elements of the groupoids `G` and `G'` of `H` and `H'` respectively. * `charted_space.lift_prop_within_at` (resp. `lift_prop_at`, `lift_prop_on` and `lift_prop`): given a property `P` of `(g, s, x)` where `g : H → H'`, define the corresponding property for functions `M → M'` where `M` and `M'` are charted spaces modelled respectively on `H` and `H'`. We define these properties within a set at a point, or at a point, or on a set, or in the whole space. This lifting process (obtained by restricting to suitable chart domains) can always be done, but it only behaves well under locality and invariance assumptions. Given `hG : local_invariant_prop G G' P`, we deduce many properties of the lifted property on the charted spaces. For instance, `hG.lift_prop_within_at_inter` says that `P g s x` is equivalent to `P g (s ∩ t) x` whenever `t` is a neighborhood of `x`. ## Implementation notes We do not use dot notation for properties of the lifted property. For instance, we have `hG.lift_prop_within_at_congr` saying that if `lift_prop_within_at P g s x` holds, and `g` and `g'` coincide on `s`, then `lift_prop_within_at P g' s x` holds. We can't call it `lift_prop_within_at.congr` as it is in the namespace associated to `local_invariant_prop`, not in the one for `lift_prop_within_at`. -/ noncomputable theory open_locale classical manifold topological_space open set filter variables {H M H' M' X : Type*} variables [topological_space H] [topological_space M] [charted_space H M] variables [topological_space H'] [topological_space M'] [charted_space H' M'] variables [topological_space X] namespace structure_groupoid variables (G : structure_groupoid H) (G' : structure_groupoid H') /-- Structure recording good behavior of a property of a triple `(f, s, x)` where `f` is a function, `s` a set and `x` a point. Good behavior here means locality and invariance under given groupoids (both in the source and in the target). Given such a good behavior, the lift of this property to charted spaces admitting these groupoids will inherit the good behavior. -/ structure local_invariant_prop (P : (H → H') → (set H) → H → Prop) : Prop := (is_local : ∀ {s x u} {f : H → H'}, is_open u → x ∈ u → (P f s x ↔ P f (s ∩ u) x)) (right_invariance' : ∀ {s x f} {e : local_homeomorph H H}, e ∈ G → x ∈ e.source → P f s x → P (f ∘ e.symm) (e.symm ⁻¹' s) (e x)) (congr_of_forall : ∀ {s x} {f g : H → H'}, (∀ y ∈ s, f y = g y) → f x = g x → P f s x → P g s x) (left_invariance' : ∀ {s x f} {e' : local_homeomorph H' H'}, e' ∈ G' → s ⊆ f ⁻¹' e'.source → f x ∈ e'.source → P f s x → P (e' ∘ f) s x) variables {G G'} {P : (H → H') → (set H) → H → Prop} {s t u : set H} {x : H} variable (hG : G.local_invariant_prop G' P) include hG namespace local_invariant_prop lemma congr_set {s t : set H} {x : H} {f : H → H'} (hu : s =ᶠ[𝓝 x] t) : P f s x ↔ P f t x := begin obtain ⟨o, host, ho, hxo⟩ := mem_nhds_iff.mp hu.mem_iff, simp_rw [subset_def, mem_set_of, ← and.congr_left_iff, ← mem_inter_iff, ← set.ext_iff] at host, rw [hG.is_local ho hxo, host, ← hG.is_local ho hxo] end lemma is_local_nhds {s u : set H} {x : H} {f : H → H'} (hu : u ∈ 𝓝[s] x) : P f s x ↔ P f (s ∩ u) x := hG.congr_set $ mem_nhds_within_iff_eventually_eq.mp hu lemma congr_iff_nhds_within {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g) (h2 : f x = g x) : P f s x ↔ P g s x := by { simp_rw [hG.is_local_nhds h1], exact ⟨hG.congr_of_forall (λ y hy, hy.2) h2, hG.congr_of_forall (λ y hy, hy.2.symm) h2.symm⟩ } lemma congr_nhds_within {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g) (h2 : f x = g x) (hP : P f s x) : P g s x := (hG.congr_iff_nhds_within h1 h2).mp hP lemma congr_nhds_within' {s : set H} {x : H} {f g : H → H'} (h1 : f =ᶠ[𝓝[s] x] g) (h2 : f x = g x) (hP : P g s x) : P f s x := (hG.congr_iff_nhds_within h1 h2).mpr hP lemma congr_iff {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) : P f s x ↔ P g s x := hG.congr_iff_nhds_within (mem_nhds_within_of_mem_nhds h) (mem_of_mem_nhds h : _) lemma congr {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) (hP : P f s x) : P g s x := (hG.congr_iff h).mp hP lemma congr' {s : set H} {x : H} {f g : H → H'} (h : f =ᶠ[𝓝 x] g) (hP : P g s x) : P f s x := hG.congr h.symm hP lemma left_invariance {s : set H} {x : H} {f : H → H'} {e' : local_homeomorph H' H'} (he' : e' ∈ G') (hfs : continuous_within_at f s x) (hxe' : f x ∈ e'.source) : P (e' ∘ f) s x ↔ P f s x := begin have h2f := hfs.preimage_mem_nhds_within (e'.open_source.mem_nhds hxe'), have h3f := (((e'.continuous_at hxe').comp_continuous_within_at hfs).preimage_mem_nhds_within $ e'.symm.open_source.mem_nhds $ e'.maps_to hxe'), split, { intro h, rw [hG.is_local_nhds h3f] at h, have h2 := hG.left_invariance' (G'.symm he') (inter_subset_right _ _) (by exact e'.maps_to hxe') h, rw [← hG.is_local_nhds h3f] at h2, refine hG.congr_nhds_within _ (e'.left_inv hxe') h2, exact eventually_of_mem h2f (λ x', e'.left_inv) }, { simp_rw [hG.is_local_nhds h2f], exact hG.left_invariance' he' (inter_subset_right _ _) hxe' } end lemma right_invariance {s : set H} {x : H} {f : H → H'} {e : local_homeomorph H H} (he : e ∈ G) (hxe : x ∈ e.source) : P (f ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P f s x := begin refine ⟨λ h, _, hG.right_invariance' he hxe⟩, have := hG.right_invariance' (G.symm he) (e.maps_to hxe) h, rw [e.symm_symm, e.left_inv hxe] at this, refine hG.congr _ ((hG.congr_set _).mp this), { refine eventually_of_mem (e.open_source.mem_nhds hxe) (λ x' hx', _), simp_rw [function.comp_apply, e.left_inv hx'] }, { rw [eventually_eq_set], refine eventually_of_mem (e.open_source.mem_nhds hxe) (λ x' hx', _), simp_rw [mem_preimage, e.left_inv hx'] }, end end local_invariant_prop end structure_groupoid namespace charted_space /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property in a charted space, by requiring that it holds at the preferred chart at this point. (When the property is local and invariant, it will in fact hold using any chart, see `lift_prop_within_at_indep_chart`). We require continuity in the lifted property, as otherwise one single chart might fail to capture the behavior of the function. -/ def lift_prop_within_at (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) (x : M) : Prop := continuous_within_at f s x ∧ P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) ((chart_at H x).symm ⁻¹' s) (chart_at H x x) /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of functions on sets in a charted space, by requiring that it holds around each point of the set, in the preferred charts. -/ def lift_prop_on (P : (H → H') → set H → H → Prop) (f : M → M') (s : set M) := ∀ x ∈ s, lift_prop_within_at P f s x /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function at a point in a charted space, by requiring that it holds in the preferred chart. -/ def lift_prop_at (P : (H → H') → set H → H → Prop) (f : M → M') (x : M) := lift_prop_within_at P f univ x lemma lift_prop_at_iff {P : (H → H') → set H → H → Prop} {f : M → M'} {x : M} : lift_prop_at P f x ↔ continuous_at f x ∧ P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) univ (chart_at H x x) := by rw [lift_prop_at, lift_prop_within_at, continuous_within_at_univ, preimage_univ] /-- Given a property of germs of functions and sets in the model space, then one defines a corresponding property of a function in a charted space, by requiring that it holds in the preferred chart around every point. -/ def lift_prop (P : (H → H') → set H → H → Prop) (f : M → M') := ∀ x, lift_prop_at P f x lemma lift_prop_iff {P : (H → H') → set H → H → Prop} {f : M → M'} : lift_prop P f ↔ continuous f ∧ ∀ x, P (chart_at H' (f x) ∘ f ∘ (chart_at H x).symm) univ (chart_at H x x) := by simp_rw [lift_prop, lift_prop_at_iff, forall_and_distrib, continuous_iff_continuous_at] end charted_space open charted_space namespace structure_groupoid variables {G : structure_groupoid H} {G' : structure_groupoid H'} {e e' : local_homeomorph M H} {f f' : local_homeomorph M' H'} {P : (H → H') → set H → H → Prop} {g g' : M → M'} {s t : set M} {x : M} {Q : (H → H) → set H → H → Prop} lemma lift_prop_within_at_univ : lift_prop_within_at P g univ x ↔ lift_prop_at P g x := iff.rfl lemma lift_prop_on_univ : lift_prop_on P g univ ↔ lift_prop P g := by simp [lift_prop_on, lift_prop, lift_prop_at] lemma lift_prop_within_at_self {f : H → H'} {s : set H} {x : H} : lift_prop_within_at P f s x ↔ continuous_within_at f s x ∧ P f s x := iff.rfl lemma lift_prop_within_at_self_source {f : H → M'} {s : set H} {x : H} : lift_prop_within_at P f s x ↔ continuous_within_at f s x ∧ P (chart_at H' (f x) ∘ f) s x := iff.rfl lemma lift_prop_within_at_self_target {f : M → H'} : lift_prop_within_at P f s x ↔ continuous_within_at f s x ∧ P (f ∘ (chart_at H x).symm) ((chart_at H x).symm ⁻¹' s) (chart_at H x x) := iff.rfl namespace local_invariant_prop variable (hG : G.local_invariant_prop G' P) include hG /-- `lift_prop_within_at P f s x` is equivalent to a definition where we restrict the set we are considering to the domain of the charts at `x` and `f x`. -/ lemma lift_prop_within_at_iff {f : M → M'} (hf : continuous_within_at f s x) : lift_prop_within_at P f s x ↔ P ((chart_at H' (f x)) ∘ f ∘ (chart_at H x).symm) ((chart_at H x).target ∩ (chart_at H x).symm ⁻¹' (s ∩ f ⁻¹' (chart_at H' (f x)).source)) (chart_at H x x) := begin rw [lift_prop_within_at, iff_true_intro hf, true_and, hG.congr_set], exact local_homeomorph.preimage_eventually_eq_target_inter_preimage_inter hf (mem_chart_source H x) (chart_source_mem_nhds H' (f x)) end lemma lift_prop_within_at_indep_chart_source_aux (g : M → H') (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (he' : e' ∈ G.maximal_atlas M) (xe' : x ∈ e'.source) : P (g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (g ∘ e'.symm) (e'.symm ⁻¹' s) (e' x) := begin rw [← hG.right_invariance (compatible_of_mem_maximal_atlas he he')], swap, { simp only [xe, xe'] with mfld_simps }, simp_rw [local_homeomorph.trans_apply, e.left_inv xe], rw [hG.congr_iff], { refine hG.congr_set _, refine (eventually_of_mem _ $ λ y (hy : y ∈ e'.symm ⁻¹' e.source), _).set_eq, { refine (e'.symm.continuous_at $ e'.maps_to xe').preimage_mem_nhds (e.open_source.mem_nhds _), simp_rw [e'.left_inv xe', xe] }, simp_rw [mem_preimage, local_homeomorph.coe_trans_symm, local_homeomorph.symm_symm, function.comp_apply, e.left_inv hy] }, { refine ((e'.eventually_nhds' _ xe').mpr $ e.eventually_left_inverse xe).mono (λ y hy, _), simp only with mfld_simps, rw [hy] }, end lemma lift_prop_within_at_indep_chart_target_aux2 (g : H → M') {x : H} {s : set H} (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) (hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source) (hgs : continuous_within_at g s x) : P (f ∘ g) s x ↔ P (f' ∘ g) s x := begin have hcont : continuous_within_at (f ∘ g) s x := (f.continuous_at xf).comp_continuous_within_at hgs, rw [← hG.left_invariance (compatible_of_mem_maximal_atlas hf hf') hcont (by simp only [xf, xf'] with mfld_simps)], refine hG.congr_iff_nhds_within _ (by simp only [xf] with mfld_simps), exact (hgs.eventually $ f.eventually_left_inverse xf).mono (λ y, congr_arg f') end lemma lift_prop_within_at_indep_chart_target_aux {g : X → M'} {e : local_homeomorph X H} {x : X} {s : set X} (xe : x ∈ e.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) (hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source) (hgs : continuous_within_at g s x) : P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (f' ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) := begin rw [← e.left_inv xe] at xf xf' hgs, refine hG.lift_prop_within_at_indep_chart_target_aux2 (g ∘ e.symm) hf xf hf' xf' _, exact hgs.comp (e.symm.continuous_at $ e.maps_to xe).continuous_within_at subset.rfl end /-- If a property of a germ of function `g` on a pointed set `(s, x)` is invariant under the structure groupoid (by composition in the source space and in the target space), then expressing it in charted spaces does not depend on the element of the maximal atlas one uses both in the source and in the target manifolds, provided they are defined around `x` and `g x` respectively, and provided `g` is continuous within `s` at `x` (otherwise, the local behavior of `g` at `x` can not be captured with a chart in the target). -/ lemma lift_prop_within_at_indep_chart_aux (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (he' : e' ∈ G.maximal_atlas M) (xe' : x ∈ e'.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) (hf' : f' ∈ G'.maximal_atlas M') (xf' : g x ∈ f'.source) (hgs : continuous_within_at g s x) : P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) ↔ P (f' ∘ g ∘ e'.symm) (e'.symm ⁻¹' s) (e' x) := by rw [hG.lift_prop_within_at_indep_chart_source_aux (f ∘ g) he xe he' xe', hG.lift_prop_within_at_indep_chart_target_aux xe' hf xf hf' xf' hgs] lemma lift_prop_within_at_indep_chart [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) : lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) := and_congr_right $ hG.lift_prop_within_at_indep_chart_aux (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) he xe (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf /-- A version of `lift_prop_within_at_indep_chart`, only for the source. -/ lemma lift_prop_within_at_indep_chart_source [has_groupoid M G] (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) : lift_prop_within_at P g s x ↔ lift_prop_within_at P (g ∘ e.symm) (e.symm ⁻¹' s) (e x) := begin have := e.symm.continuous_within_at_iff_continuous_within_at_comp_right xe, rw [e.symm_symm] at this, rw [lift_prop_within_at_self_source, lift_prop_within_at, ← this], simp_rw [function.comp_app, e.left_inv xe], refine and_congr iff.rfl _, rw hG.lift_prop_within_at_indep_chart_source_aux (chart_at H' (g x) ∘ g) (chart_mem_maximal_atlas G x) (mem_chart_source H x) he xe, end /-- A version of `lift_prop_within_at_indep_chart`, only for the target. -/ lemma lift_prop_within_at_indep_chart_target [has_groupoid M' G'] (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) : lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ lift_prop_within_at P (f ∘ g) s x := begin rw [lift_prop_within_at_self_target, lift_prop_within_at, and.congr_right_iff], intro hg, simp_rw [(f.continuous_at xf).comp_continuous_within_at hg, true_and], exact hG.lift_prop_within_at_indep_chart_target_aux (mem_chart_source _ _) (chart_mem_maximal_atlas _ _) (mem_chart_source _ _) hf xf hg end /-- A version of `lift_prop_within_at_indep_chart`, that uses `lift_prop_within_at` on both sides. -/ lemma lift_prop_within_at_indep_chart' [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ G.maximal_atlas M) (xe : x ∈ e.source) (hf : f ∈ G'.maximal_atlas M') (xf : g x ∈ f.source) : lift_prop_within_at P g s x ↔ continuous_within_at g s x ∧ lift_prop_within_at P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) (e x) := begin rw [hG.lift_prop_within_at_indep_chart he xe hf xf, lift_prop_within_at_self, and.left_comm, iff.comm, and_iff_right_iff_imp], intro h, have h1 := (e.symm.continuous_within_at_iff_continuous_within_at_comp_right xe).mp h.1, have : continuous_at f ((g ∘ e.symm) (e x)), { simp_rw [function.comp, e.left_inv xe, f.continuous_at xf] }, exact this.comp_continuous_within_at h1, end lemma lift_prop_on_indep_chart [has_groupoid M G] [has_groupoid M' G'] (he : e ∈ G.maximal_atlas M) (hf : f ∈ G'.maximal_atlas M') (h : lift_prop_on P g s) {y : H} (hy : y ∈ e.target ∩ e.symm ⁻¹' (s ∩ g ⁻¹' f.source)) : P (f ∘ g ∘ e.symm) (e.symm ⁻¹' s) y := begin convert ((hG.lift_prop_within_at_indep_chart he (e.symm_maps_to hy.1) hf hy.2.2).1 (h _ hy.2.1)).2, rw [e.right_inv hy.1], end lemma lift_prop_within_at_inter' (ht : t ∈ 𝓝[s] x) : lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x := begin rw [lift_prop_within_at, lift_prop_within_at, continuous_within_at_inter' ht, hG.congr_set], simp_rw [eventually_eq_set, mem_preimage, (chart_at H x).eventually_nhds' (λ x, x ∈ s ∩ t ↔ x ∈ s) (mem_chart_source H x)], exact (mem_nhds_within_iff_eventually_eq.mp ht).symm.mem_iff end lemma lift_prop_within_at_inter (ht : t ∈ 𝓝 x) : lift_prop_within_at P g (s ∩ t) x ↔ lift_prop_within_at P g s x := hG.lift_prop_within_at_inter' (mem_nhds_within_of_mem_nhds ht) lemma lift_prop_at_of_lift_prop_within_at (h : lift_prop_within_at P g s x) (hs : s ∈ 𝓝 x) : lift_prop_at P g x := by rwa [← univ_inter s, hG.lift_prop_within_at_inter hs] at h lemma lift_prop_within_at_of_lift_prop_at_of_mem_nhds (h : lift_prop_at P g x) (hs : s ∈ 𝓝 x) : lift_prop_within_at P g s x := by rwa [← univ_inter s, hG.lift_prop_within_at_inter hs] lemma lift_prop_on_of_locally_lift_prop_on (h : ∀ x ∈ s, ∃ u, is_open u ∧ x ∈ u ∧ lift_prop_on P g (s ∩ u)) : lift_prop_on P g s := begin assume x hx, rcases h x hx with ⟨u, u_open, xu, hu⟩, have := hu x ⟨hx, xu⟩, rwa hG.lift_prop_within_at_inter at this, exact is_open.mem_nhds u_open xu, end lemma lift_prop_of_locally_lift_prop_on (h : ∀ x, ∃ u, is_open u ∧ x ∈ u ∧ lift_prop_on P g u) : lift_prop P g := begin rw ← lift_prop_on_univ, apply hG.lift_prop_on_of_locally_lift_prop_on (λ x hx, _), simp [h x], end lemma lift_prop_within_at_congr_of_eventually_eq (h : lift_prop_within_at P g s x) (h₁ : g' =ᶠ[𝓝[s] x] g) (hx : g' x = g x) : lift_prop_within_at P g' s x := begin refine ⟨h.1.congr_of_eventually_eq h₁ hx, _⟩, refine hG.congr_nhds_within' _ (by simp_rw [function.comp_apply, (chart_at H x).left_inv (mem_chart_source H x), hx]) h.2, simp_rw [eventually_eq, function.comp_app, (chart_at H x).eventually_nhds_within' (λ y, chart_at H' (g' x) (g' y) = chart_at H' (g x) (g y)) (mem_chart_source H x)], exact h₁.mono (λ y hy, by rw [hx, hy]) end lemma lift_prop_within_at_congr_iff_of_eventually_eq (h₁ : g' =ᶠ[𝓝[s] x] g) (hx : g' x = g x) : lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x := ⟨λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁.symm hx.symm, λ h, hG.lift_prop_within_at_congr_of_eventually_eq h h₁ hx⟩ lemma lift_prop_within_at_congr_iff (h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) : lift_prop_within_at P g' s x ↔ lift_prop_within_at P g s x := hG.lift_prop_within_at_congr_iff_of_eventually_eq (eventually_nhds_within_of_forall h₁) hx lemma lift_prop_within_at_congr (h : lift_prop_within_at P g s x) (h₁ : ∀ y ∈ s, g' y = g y) (hx : g' x = g x) : lift_prop_within_at P g' s x := (hG.lift_prop_within_at_congr_iff h₁ hx).mpr h lemma lift_prop_at_congr_iff_of_eventually_eq (h₁ : g' =ᶠ[𝓝 x] g) : lift_prop_at P g' x ↔ lift_prop_at P g x := hG.lift_prop_within_at_congr_iff_of_eventually_eq (by simp_rw [nhds_within_univ, h₁]) h₁.eq_of_nhds lemma lift_prop_at_congr_of_eventually_eq (h : lift_prop_at P g x) (h₁ : g' =ᶠ[𝓝 x] g) : lift_prop_at P g' x := (hG.lift_prop_at_congr_iff_of_eventually_eq h₁).mpr h lemma lift_prop_on_congr (h : lift_prop_on P g s) (h₁ : ∀ y ∈ s, g' y = g y) : lift_prop_on P g' s := λ x hx, hG.lift_prop_within_at_congr (h x hx) h₁ (h₁ x hx) lemma lift_prop_on_congr_iff (h₁ : ∀ y ∈ s, g' y = g y) : lift_prop_on P g' s ↔ lift_prop_on P g s := ⟨λ h, hG.lift_prop_on_congr h (λ y hy, (h₁ y hy).symm), λ h, hG.lift_prop_on_congr h h₁⟩ omit hG lemma lift_prop_within_at_mono (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_within_at P g t x) (hst : s ⊆ t) : lift_prop_within_at P g s x := begin refine ⟨h.1.mono hst, _⟩, apply mono (λ y hy, _) h.2, simp only with mfld_simps at hy, simp only [hy, hst _] with mfld_simps, end lemma lift_prop_within_at_of_lift_prop_at (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_at P g x) : lift_prop_within_at P g s x := begin rw ← lift_prop_within_at_univ at h, exact lift_prop_within_at_mono mono h (subset_univ _), end lemma lift_prop_on_mono (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop_on P g t) (hst : s ⊆ t) : lift_prop_on P g s := λ x hx, lift_prop_within_at_mono mono (h x (hst hx)) hst lemma lift_prop_on_of_lift_prop (mono : ∀ ⦃s x t⦄ ⦃f : H → H'⦄, t ⊆ s → P f s x → P f t x) (h : lift_prop P g) : lift_prop_on P g s := begin rw ← lift_prop_on_univ at h, exact lift_prop_on_mono mono h (subset_univ _) end lemma lift_prop_at_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ e.source) : lift_prop_at Q e x := begin simp_rw [lift_prop_at, hG.lift_prop_within_at_indep_chart he hx G.id_mem_maximal_atlas (mem_univ _), (e.continuous_at hx).continuous_within_at, true_and], exact hG.congr' (e.eventually_right_inverse' hx) (hQ _) end lemma lift_prop_on_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) : lift_prop_on Q e e.source := begin assume x hx, apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds (hG.lift_prop_at_of_mem_maximal_atlas hQ he hx), exact is_open.mem_nhds e.open_source hx, end lemma lift_prop_at_symm_of_mem_maximal_atlas [has_groupoid M G] {x : H} (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) (hx : x ∈ e.target) : lift_prop_at Q e.symm x := begin suffices h : Q (e ∘ e.symm) univ x, { have A : e.symm ⁻¹' e.source ∩ e.target = e.target, by mfld_set_tac, have : e.symm x ∈ e.source, by simp only [hx] with mfld_simps, rw [lift_prop_at, hG.lift_prop_within_at_indep_chart G.id_mem_maximal_atlas (mem_univ _) he this], refine ⟨(e.symm.continuous_at hx).continuous_within_at, _⟩, simp only [h] with mfld_simps }, exact hG.congr' (e.eventually_right_inverse hx) (hQ x) end lemma lift_prop_on_symm_of_mem_maximal_atlas [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) (he : e ∈ maximal_atlas M G) : lift_prop_on Q e.symm e.target := begin assume x hx, apply hG.lift_prop_within_at_of_lift_prop_at_of_mem_nhds (hG.lift_prop_at_symm_of_mem_maximal_atlas hQ he hx), exact is_open.mem_nhds e.open_target hx, end lemma lift_prop_at_chart [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_at Q (chart_at H x) x := hG.lift_prop_at_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (mem_chart_source H x) lemma lift_prop_on_chart [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_on Q (chart_at H x) (chart_at H x).source := hG.lift_prop_on_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) lemma lift_prop_at_chart_symm [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_at Q (chart_at H x).symm ((chart_at H x) x) := hG.lift_prop_at_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) (by simp) lemma lift_prop_on_chart_symm [has_groupoid M G] (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop_on Q (chart_at H x).symm (chart_at H x).target := hG.lift_prop_on_symm_of_mem_maximal_atlas hQ (chart_mem_maximal_atlas G x) lemma lift_prop_id (hG : G.local_invariant_prop G Q) (hQ : ∀ y, Q id univ y) : lift_prop Q (id : M → M) := begin simp_rw [lift_prop_iff, continuous_id, true_and], exact λ x, hG.congr' ((chart_at H x).eventually_right_inverse $ mem_chart_target H x) (hQ _) end end local_invariant_prop section local_structomorph variables (G) open local_homeomorph /-- A function from a model space `H` to itself is a local structomorphism, with respect to a structure groupoid `G` for `H`, relative to a set `s` in `H`, if for all points `x` in the set, the function agrees with a `G`-structomorphism on `s` in a neighbourhood of `x`. -/ def is_local_structomorph_within_at (f : H → H) (s : set H) (x : H) : Prop := x ∈ s → ∃ (e : local_homeomorph H H), e ∈ G ∧ eq_on f e.to_fun (s ∩ e.source) ∧ x ∈ e.source /-- For a groupoid `G` which is `closed_under_restriction`, being a local structomorphism is a local invariant property. -/ lemma is_local_structomorph_within_at_local_invariant_prop [closed_under_restriction G] : local_invariant_prop G G (is_local_structomorph_within_at G) := { is_local := begin intros s x u f hu hux, split, { rintros h hx, rcases h hx.1 with ⟨e, heG, hef, hex⟩, have : s ∩ u ∩ e.source ⊆ s ∩ e.source := by mfld_set_tac, exact ⟨e, heG, hef.mono this, hex⟩ }, { rintros h hx, rcases h ⟨hx, hux⟩ with ⟨e, heG, hef, hex⟩, refine ⟨e.restr (interior u), _, _, _⟩, { exact closed_under_restriction' heG (is_open_interior) }, { have : s ∩ u ∩ e.source = s ∩ (e.source ∩ u) := by mfld_set_tac, simpa only [this, interior_interior, hu.interior_eq] with mfld_simps using hef }, { simp only [*, interior_interior, hu.interior_eq] with mfld_simps } } end, right_invariance' := begin intros s x f e' he'G he'x h hx, have hxs : x ∈ s := by simpa only [e'.left_inv he'x] with mfld_simps using hx, rcases h hxs with ⟨e, heG, hef, hex⟩, refine ⟨e'.symm.trans e, G.trans (G.symm he'G) heG, _, _⟩, { intros y hy, simp only with mfld_simps at hy, simp only [hef ⟨hy.1, hy.2.2⟩] with mfld_simps }, { simp only [hex, he'x] with mfld_simps } end, congr_of_forall := begin intros s x f g hfgs hfg' h hx, rcases h hx with ⟨e, heG, hef, hex⟩, refine ⟨e, heG, _, hex⟩, intros y hy, rw [← hef hy, hfgs y hy.1] end, left_invariance' := begin intros s x f e' he'G he' hfx h hx, rcases h hx with ⟨e, heG, hef, hex⟩, refine ⟨e.trans e', G.trans heG he'G, _, _⟩, { intros y hy, simp only with mfld_simps at hy, simp only [hef ⟨hy.1, hy.2.1⟩] with mfld_simps }, { simpa only [hex, hef ⟨hx, hex⟩] with mfld_simps using hfx } end } variables {H₁ : Type*} [topological_space H₁] {H₂ : Type*} [topological_space H₂] {H₃ : Type*} [topological_space H₃] [charted_space H₁ H₂] [charted_space H₂ H₃] {G₁ : structure_groupoid H₁} [has_groupoid H₂ G₁] [closed_under_restriction G₁] (G₂ : structure_groupoid H₂) [has_groupoid H₃ G₂] lemma has_groupoid.comp (H : ∀ e ∈ G₂, lift_prop_on (is_local_structomorph_within_at G₁) (e : H₂ → H₂) e.source) : @has_groupoid H₁ _ H₃ _ (charted_space.comp H₁ H₂ H₃) G₁ := { compatible := begin rintros _ _ ⟨e, f, he, hf, rfl⟩ ⟨e', f', he', hf', rfl⟩, apply G₁.locality, intros x hx, simp only with mfld_simps at hx, have hxs : x ∈ f.symm ⁻¹' (e.symm ≫ₕ e').source, { simp only [hx] with mfld_simps }, have hxs' : x ∈ f.target ∩ (f.symm) ⁻¹' ((e.symm ≫ₕ e').source ∩ (e.symm ≫ₕ e') ⁻¹' f'.source), { simp only [hx] with mfld_simps }, obtain ⟨φ, hφG₁, hφ, hφ_dom⟩ := local_invariant_prop.lift_prop_on_indep_chart (is_local_structomorph_within_at_local_invariant_prop G₁) (G₁.subset_maximal_atlas hf) (G₁.subset_maximal_atlas hf') (H _ (G₂.compatible he he')) hxs' hxs, simp_rw [← local_homeomorph.coe_trans, local_homeomorph.trans_assoc] at hφ, simp_rw [local_homeomorph.trans_symm_eq_symm_trans_symm, local_homeomorph.trans_assoc], have hs : is_open (f.symm ≫ₕ e.symm ≫ₕ e' ≫ₕ f').source := (f.symm ≫ₕ e.symm ≫ₕ e' ≫ₕ f').open_source, refine ⟨_, hs.inter φ.open_source, _, _⟩, { simp only [hx, hφ_dom] with mfld_simps, }, { refine G₁.eq_on_source (closed_under_restriction' hφG₁ hs) _, rw local_homeomorph.restr_source_inter, refine (hφ.mono _).restr_eq_on_source, mfld_set_tac }, end } end local_structomorph end structure_groupoid
2cd6754cf089d7c3781a04e8e46866179f02e60c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/level.lean
553253258c843ecc6ff1c778295abc68016b4458
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
287
lean
import Lean.Level new_frontend open Lean #eval levelZero == levelZero #eval levelZero == mkLevelSucc levelZero #eval mkLevelMax (mkLevelSucc levelZero) levelZero == mkLevelSucc levelZero #eval mkLevelMax (mkLevelSucc levelZero) levelZero == mkLevelMax (mkLevelSucc levelZero) levelZero
4325b75a8f434ca55156ed427156092e057a60df
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/analysis/normed_space/multilinear.lean
8fee3aeef7d052ca4618e81a81c5d2642278911c
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,506
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.normed_space.operator_norm import topology.algebra.multilinear /-! # Operator norm on the space of continuous multilinear maps When `f` is a continuous multilinear map in finitely many variables, we define its norm `∥f∥` as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that it is indeed a norm, and prove its basic properties. ## Main results Let `f` be a multilinear map in finitely many variables. * `exists_bound_of_continuous` asserts that, if `f` is continuous, then there exists `C > 0` with `∥f m∥ ≤ C * ∏ i, ∥m i∥` for all `m`. * `continuous_of_bound`, conversely, asserts that this bound implies continuity. * `mk_continuous` constructs the associated continuous multilinear map. Let `f` be a continuous multilinear map in finitely many variables. * `∥f∥` is its norm, i.e., the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. * `le_op_norm f m` asserts the fundamental inequality `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥`. * `norm_image_sub_le f m₁ m₂` gives a control of the difference `f m₁ - f m₂` in terms of `∥f∥` and `∥m₁ - m₂∥`. We also register isomorphisms corresponding to currying or uncurrying variables, transforming a continuous multilinear function `f` in `n+1` variables into a continuous linear function taking values in continuous multilinear functions in `n` variables, and also into a continuous multilinear function in `n` variables taking values in continuous linear functions. These operations are called `f.curry_left` and `f.curry_right` respectively (with inverses `f.uncurry_left` and `f.uncurry_right`). They induce continuous linear equivalences between spaces of continuous multilinear functions in `n+1` variables and spaces of continuous linear functions into continuous multilinear functions in `n` variables (resp. continuous multilinear functions in `n` variables taking values in continuous linear functions), called respectively `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. ## Implementation notes We mostly follow the API (and the proofs) of `operator_norm.lean`, with the additional complexity that we should deal with multilinear maps in several variables. The currying/uncurrying constructions are based on those in `multilinear.lean`. From the mathematical point of view, all the results follow from the results on operator norm in one variable, by applying them to one variable after the other through currying. However, this is only well defined when there is an order on the variables (for instance on `fin n`) although the final result is independent of the order. While everything could be done following this approach, it turns out that direct proofs are easier and more efficient. -/ noncomputable theory open_locale classical big_operators open finset metric local attribute [instance, priority 1001] add_comm_group.to_add_comm_monoid normed_group.to_add_comm_group normed_space.to_semimodule /-! ### Type variables We use the following type variables in this file: * `𝕜` : a `nondiscrete_normed_field`; * `ι`, `ι'` : finite index types with decidable equality; * `E` : a family of normed vector spaces over `𝕜` indexed by `i : ι`; * `E'` : a family of normed vector spaces over `𝕜` indexed by `i' : ι'`; * `Ei` : a family of normed vector spaces over `𝕜` indexed by `i : fin (nat.succ n)`; * `G`, `G'` : normed vector spaces over `𝕜`. -/ universes u v v' wE wE' wEi wG wG' variables {𝕜 : Type u} {ι : Type v} {ι' : Type v'} {n : ℕ} {E : ι → Type wE} {E' : ι' → Type wE'} {Ei : fin n.succ → Type wEi} {G : Type wG} {G' : Type wG'} [decidable_eq ι] [fintype ι] [decidable_eq ι'] [fintype ι'] [nondiscrete_normed_field 𝕜] [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] [Π i, normed_group (E' i)] [Π i, normed_space 𝕜 (E' i)] [Π i, normed_group (Ei i)] [Π i, normed_space 𝕜 (Ei i)] [normed_group G] [normed_space 𝕜 G] [normed_group G'] [normed_space 𝕜 G'] /-! ### Continuity properties of multilinear maps We relate continuity of multilinear maps to the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, in both directions. Along the way, we prove useful bounds on the difference `∥f m₁ - f m₂∥`. -/ namespace multilinear_map variable (f : multilinear_map 𝕜 E G) /-- If a multilinear map in finitely many variables on normed spaces satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥` on a shell `ε i / ∥c i∥ < ∥m i∥ < ε i` for some positive numbers `ε i` and elements `c i : 𝕜`, `1 < ∥c i∥`, then it satisfies this inequality for all `m`. -/ lemma bound_of_shell {ε : ι → ℝ} {C : ℝ} (hε : ∀ i, 0 < ε i) {c : ι → 𝕜} (hc : ∀ i, 1 < ∥c i∥) (hf : ∀ m : Π i, E i, (∀ i, ε i / ∥c i∥ ≤ ∥m i∥) → (∀ i, ∥m i∥ < ε i) → ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m : Π i, E i) : ∥f m∥ ≤ C * ∏ i, ∥m i∥ := begin rcases em (∃ i, m i = 0) with ⟨i, hi⟩|hm; [skip, push_neg at hm], { simp [f.map_coord_zero i hi, prod_eq_zero (mem_univ i), hi] }, choose δ hδ0 hδm_lt hle_δm hδinv using λ i, rescale_to_shell (hc i) (hε i) (hm i), have hδ0 : 0 < ∏ i, ∥δ i∥, from prod_pos (λ i _, norm_pos_iff.2 (hδ0 i)), simpa [map_smul_univ, norm_smul, prod_mul_distrib, mul_left_comm C, mul_le_mul_left hδ0] using hf (λ i, δ i • m i) hle_δm hδm_lt, end /-- If a multilinear map in finitely many variables on normed spaces is continuous, then it satisfies the inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, for some `C` which can be chosen to be positive. -/ theorem exists_bound_of_continuous (hf : continuous f) : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := begin by_cases hι : nonempty ι, swap, { refine ⟨∥f 0∥ + 1, add_pos_of_nonneg_of_pos (norm_nonneg _) zero_lt_one, λ m, _⟩, obtain rfl : m = 0, from funext (λ i, (hι ⟨i⟩).elim), simp [univ_eq_empty.2 hι, zero_le_one] }, resetI, obtain ⟨ε : ℝ, ε0 : 0 < ε, hε : ∀ m : Π i, E i, ∥m - 0∥ < ε → ∥f m - f 0∥ < 1⟩ := normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one, simp only [sub_zero, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have : 0 < (∥c∥ / ε) ^ fintype.card ι, from pow_pos (div_pos (zero_lt_one.trans hc) ε0) _, refine ⟨_, this, _⟩, refine f.bound_of_shell (λ _, ε0) (λ _, hc) (λ m hcm hm, _), refine (hε m ((pi_norm_lt_iff ε0).2 hm)).le.trans _, rw [← div_le_iff' this, one_div, ← inv_pow', inv_div, fintype.card, ← prod_const], exact prod_le_prod (λ _ _, div_nonneg ε0.le (norm_nonneg _)) (λ i _, hcm i) end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a precise but hard to use version. See `norm_image_sub_le_of_bound` for a less precise but more usable version. The bound reads `∥f m - f m'∥ ≤ C * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`. -/ lemma norm_image_sub_le_of_bound' {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := begin have A : ∀(s : finset ι), ∥f m₁ - f (s.piecewise m₂ m₁)∥ ≤ C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { refine finset.induction (by simp) _, assume i s his Hrec, have I : ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ ≤ C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥, { have A : ((insert i s).piecewise m₂ m₁) = function.update (s.piecewise m₂ m₁) i (m₂ i) := s.piecewise_insert _ _ _, have B : s.piecewise m₂ m₁ = function.update (s.piecewise m₂ m₁) i (m₁ i), { ext j, by_cases h : j = i, { rw h, simp [his] }, { simp [h] } }, rw [B, A, ← f.map_sub], apply le_trans (H _) (mul_le_mul_of_nonneg_left _ hC), refine prod_le_prod (λj hj, norm_nonneg _) (λj hj, _), by_cases h : j = i, { rw h, simp }, { by_cases h' : j ∈ s; simp [h', h, le_refl] } }, calc ∥f m₁ - f ((insert i s).piecewise m₂ m₁)∥ ≤ ∥f m₁ - f (s.piecewise m₂ m₁)∥ + ∥f (s.piecewise m₂ m₁) - f ((insert i s).piecewise m₂ m₁)∥ : by { rw [← dist_eq_norm, ← dist_eq_norm, ← dist_eq_norm], exact dist_triangle _ _ _ } ... ≤ (C * ∑ i in s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) + C * ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : add_le_add Hrec I ... = C * ∑ i in insert i s, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : by simp [his, add_comm, left_distrib] }, convert A univ, simp end /-- If `f` satisfies a boundedness property around `0`, one can deduce a bound on `f m₁ - f m₂` using the multilinearity. Here, we give a usable but not very precise version. See `norm_image_sub_le_of_bound'` for a more precise but less usable version. The bound is `∥f m - f m'∥ ≤ C * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`. -/ lemma norm_image_sub_le_of_bound {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := begin have A : ∀ (i : ι), ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1), { assume i, calc ∏ j, (if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥) ≤ ∏ j : ι, function.update (λ j, max ∥m₁∥ ∥m₂∥) i (∥m₁ - m₂∥) j : begin apply prod_le_prod, { assume j hj, by_cases h : j = i; simp [h, norm_nonneg] }, { assume j hj, by_cases h : j = i, { rw h, simp, exact norm_le_pi_norm (m₁ - m₂) i }, { simp [h, max_le_max, norm_le_pi_norm] } } end ... = ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : by { rw prod_update_of_mem (finset.mem_univ _), simp [card_univ_diff] } }, calc ∥f m₁ - f m₂∥ ≤ C * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ : f.norm_image_sub_le_of_bound' hC H m₁ m₂ ... ≤ C * ∑ i, ∥m₁ - m₂∥ * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) : mul_le_mul_of_nonneg_left (sum_le_sum (λi hi, A i)) hC ... = C * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ : by { rw [sum_const, card_univ, nsmul_eq_mul], ring } end /-- If a multilinear map satisfies an inequality `∥f m∥ ≤ C * ∏ i, ∥m i∥`, then it is continuous. -/ theorem continuous_of_bound (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous f := begin let D := max C 1, have D_pos : 0 ≤ D := le_trans zero_le_one (le_max_right _ _), replace H : ∀ m, ∥f m∥ ≤ D * ∏ i, ∥m i∥, { assume m, apply le_trans (H m) (mul_le_mul_of_nonneg_right (le_max_left _ _) _), exact prod_nonneg (λ(i : ι) hi, norm_nonneg (m i)) }, refine continuous_iff_continuous_at.2 (λm, _), refine continuous_at_of_locally_lipschitz zero_lt_one (D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1)) (λm' h', _), rw [dist_eq_norm, dist_eq_norm], have : 0 ≤ (max ∥m'∥ ∥m∥), by simp, have : (max ∥m'∥ ∥m∥) ≤ ∥m∥ + 1, by simp [zero_le_one, norm_le_of_mem_closed_ball (le_of_lt h'), -add_comm], calc ∥f m' - f m∥ ≤ D * (fintype.card ι) * (max ∥m'∥ ∥m∥) ^ (fintype.card ι - 1) * ∥m' - m∥ : f.norm_image_sub_le_of_bound D_pos H m' m ... ≤ D * (fintype.card ι) * (∥m∥ + 1) ^ (fintype.card ι - 1) * ∥m' - m∥ : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg, nat.cast_nonneg, pow_le_pow_of_le_left] end /-- Constructing a continuous multilinear map from a multilinear map satisfying a boundedness condition. -/ def mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : continuous_multilinear_map 𝕜 E G := { cont := f.continuous_of_bound C H, ..f } @[simp] lemma coe_mk_continuous (C : ℝ) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ⇑(f.mk_continuous C H) = f := rfl /-- Given a multilinear map in `n` variables, if one restricts it to `k` variables putting `z` on the other coordinates, then the resulting restricted function satisfies an inequality `∥f.restr v∥ ≤ C * ∥z∥^(n-k) * Π ∥v i∥` if the original function satisfies `∥f v∥ ≤ C * Π ∥v i∥`. -/ lemma restr_norm_le {k n : ℕ} (f : (multilinear_map 𝕜 (λ i : fin n, G) G' : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) (v : fin k → G) : ∥f.restr s hk z v∥ ≤ C * ∥z∥ ^ (n - k) * ∏ i, ∥v i∥ := begin rw [mul_right_comm, mul_assoc], convert H _ using 2, simp only [apply_dite norm, fintype.prod_dite, prod_const (∥z∥), finset.card_univ, fintype.card_of_subtype sᶜ (λ x, mem_compl), card_compl, fintype.card_fin, hk, mk_coe, ← (s.order_iso_of_fin hk).symm.bijective.prod_comp (λ x, ∥v x∥)], refl end end multilinear_map /-! ### Continuous multilinear maps We define the norm `∥f∥` of a continuous multilinear map `f` in finitely many variables as the smallest number such that `∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥` for all `m`. We show that this defines a normed space structure on `continuous_multilinear_map 𝕜 E G`. -/ namespace continuous_multilinear_map variables (c : 𝕜) (f g : continuous_multilinear_map 𝕜 E G) (m : Πi, E i) theorem bound : ∃ (C : ℝ), 0 < C ∧ (∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) := f.to_multilinear_map.exists_bound_of_continuous f.2 open real /-- The operator norm of a continuous multilinear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} instance has_op_norm : has_norm (continuous_multilinear_map 𝕜 E G) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ (c : ℝ) ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : continuous_multilinear_map 𝕜 E G} : ∃ c, c ∈ {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : continuous_multilinear_map 𝕜 E G} : bdd_below {c | 0 ≤ c ∧ ∀ m, ∥f m∥ ≤ c * ∏ i, ∥m i∥} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm of a continuous multilinear map: `∥f m∥` is bounded by `∥f∥` times the product of the `∥m i∥`. -/ theorem le_op_norm : ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := begin have A : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), cases A.eq_or_lt with h hlt, { rcases prod_eq_zero_iff.1 h.symm with ⟨i, _, hi⟩, rw norm_eq_zero at hi, have : f m = 0 := f.map_coord_zero i hi, rw [this, norm_zero], exact mul_nonneg (op_norm_nonneg f) A }, { rw [← div_le_iff hlt], apply (le_Inf _ bounds_nonempty bounds_bdd_below).2, rintro c ⟨_, hc⟩, rw [div_le_iff hlt], apply hc } end theorem le_of_op_norm_le {C : ℝ} (h : ∥f∥ ≤ C) : ∥f m∥ ≤ C * ∏ i, ∥m i∥ := (f.le_op_norm m).trans $ mul_le_mul_of_nonneg_right h (prod_nonneg $ λ i _, norm_nonneg (m i)) lemma ratio_le_op_norm : ∥f m∥ / ∏ i, ∥m i∥ ≤ ∥f∥ := begin have : 0 ≤ ∏ i, ∥m i∥ := prod_nonneg (λj hj, norm_nonneg _), cases eq_or_lt_of_le this with h h, { simp [h.symm, op_norm_nonneg f] }, { rw div_le_iff h, exact le_op_norm f m } end /-- The image of the unit ball under a continuous multilinear map is bounded. -/ lemma unit_le_op_norm (h : ∥m∥ ≤ 1) : ∥f m∥ ≤ ∥f∥ := calc ∥f m∥ ≤ ∥f∥ * ∏ i, ∥m i∥ : f.le_op_norm m ... ≤ ∥f∥ * ∏ i : ι, 1 : mul_le_mul_of_nonneg_left (prod_le_prod (λi hi, norm_nonneg _) (λi hi, le_trans (norm_le_pi_norm _ _) h)) (op_norm_nonneg f) ... = ∥f∥ : by simp /-- If one controls the norm of every `f x`, then one controls the norm of `f`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ m, ∥f m∥ ≤ M * ∏ i, ∥m i∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := Inf_le _ bounds_bdd_below ⟨add_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw add_mul, exact norm_add_le_of_le (le_op_norm _ _) (le_op_norm _ _) }⟩ /-- A continuous linear map is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := begin split, { assume h, ext m, simpa [h] using f.le_op_norm m }, { rintro rfl, apply le_antisymm (op_norm_le_bound 0 le_rfl (λm, _)) (op_norm_nonneg _), simp } end variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] [normed_space 𝕜' G] [is_scalar_tower 𝕜' 𝕜 G] lemma op_norm_smul_le (c : 𝕜') : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := (c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) begin intro m, erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous multilinear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (continuous_multilinear_map 𝕜 E G) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜' (continuous_multilinear_map 𝕜 E G) := ⟨λ c f, f.op_norm_smul_le c⟩ section restrict_scalars variables [Π i, normed_space 𝕜' (E i)] [∀ i, is_scalar_tower 𝕜' 𝕜 (E i)] @[simp] lemma norm_restrict_scalars : ∥f.restrict_scalars 𝕜'∥ = ∥f∥ := by simp only [norm_def, coe_restrict_scalars] variable (𝕜') /-- `continuous_multilinear_map.restrict_scalars` as a `continuous_multilinear_map`. -/ def restrict_scalars_linear : continuous_multilinear_map 𝕜 E G →L[𝕜'] continuous_multilinear_map 𝕜' E G := linear_map.mk_continuous { to_fun := restrict_scalars 𝕜', map_add' := λ m₁ m₂, rfl, map_smul' := λ c m, rfl } 1 $ λ f, by simp variable {𝕜'} lemma continuous_restrict_scalars : continuous (restrict_scalars 𝕜' : continuous_multilinear_map 𝕜 E G → continuous_multilinear_map 𝕜' E G) := (restrict_scalars_linear 𝕜').continuous end restrict_scalars /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, precise version. For a less precise but more usable version, see `norm_image_sub_le`. The bound reads `∥f m - f m'∥ ≤ ∥f∥ * ∥m 1 - m' 1∥ * max ∥m 2∥ ∥m' 2∥ * max ∥m 3∥ ∥m' 3∥ * ... * max ∥m n∥ ∥m' n∥ + ...`, where the other terms in the sum are the same products where `1` is replaced by any `i`.-/ lemma norm_image_sub_le' (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * ∑ i, ∏ j, if j = i then ∥m₁ i - m₂ i∥ else max ∥m₁ j∥ ∥m₂ j∥ := f.to_multilinear_map.norm_image_sub_le_of_bound' (norm_nonneg _) f.le_op_norm _ _ /-- The difference `f m₁ - f m₂` is controlled in terms of `∥f∥` and `∥m₁ - m₂∥`, less precise version. For a more precise but less usable version, see `norm_image_sub_le'`. The bound is `∥f m - f m'∥ ≤ ∥f∥ * card ι * ∥m - m'∥ * (max ∥m∥ ∥m'∥) ^ (card ι - 1)`.-/ lemma norm_image_sub_le (m₁ m₂ : Πi, E i) : ∥f m₁ - f m₂∥ ≤ ∥f∥ * (fintype.card ι) * (max ∥m₁∥ ∥m₂∥) ^ (fintype.card ι - 1) * ∥m₁ - m₂∥ := f.to_multilinear_map.norm_image_sub_le_of_bound (norm_nonneg _) f.le_op_norm _ _ /-- Applying a multilinear map to a vector is continuous in both coordinates. -/ lemma continuous_eval : continuous (λ p : continuous_multilinear_map 𝕜 E G × Π i, E i, p.1 p.2) := begin apply continuous_iff_continuous_at.2 (λp, _), apply continuous_at_of_locally_lipschitz zero_lt_one ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + ∏ i, ∥p.2 i∥) (λq hq, _), have : 0 ≤ (max ∥q.2∥ ∥p.2∥), by simp, have : 0 ≤ ∥p∥ + 1, by simp [le_trans zero_le_one], have A : ∥q∥ ≤ ∥p∥ + 1 := norm_le_of_mem_closed_ball (le_of_lt hq), have : (max ∥q.2∥ ∥p.2∥) ≤ ∥p∥ + 1 := le_trans (max_le_max (norm_snd_le q) (norm_snd_le p)) (by simp [A, -add_comm, zero_le_one]), have : ∀ (i : ι), i ∈ univ → 0 ≤ ∥p.2 i∥ := λ i hi, norm_nonneg _, calc dist (q.1 q.2) (p.1 p.2) ≤ dist (q.1 q.2) (q.1 p.2) + dist (q.1 p.2) (p.1 p.2) : dist_triangle _ _ _ ... = ∥q.1 q.2 - q.1 p.2∥ + ∥q.1 p.2 - p.1 p.2∥ : by rw [dist_eq_norm, dist_eq_norm] ... ≤ ∥q.1∥ * (fintype.card ι) * (max ∥q.2∥ ∥p.2∥) ^ (fintype.card ι - 1) * ∥q.2 - p.2∥ + ∥q.1 - p.1∥ * ∏ i, ∥p.2 i∥ : add_le_add (norm_image_sub_le _ _ _) ((q.1 - p.1).le_op_norm p.2) ... ≤ (∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) * ∥q - p∥ + ∥q - p∥ * ∏ i, ∥p.2 i∥ : by apply_rules [add_le_add, mul_le_mul, le_refl, le_trans (norm_fst_le q) A, nat.cast_nonneg, mul_nonneg, pow_le_pow_of_le_left, pow_nonneg, norm_snd_le (q - p), norm_nonneg, norm_fst_le (q - p), prod_nonneg] ... = ((∥p∥ + 1) * (fintype.card ι) * (∥p∥ + 1) ^ (fintype.card ι - 1) + (∏ i, ∥p.2 i∥)) * dist q p : by { rw dist_eq_norm, ring } end lemma continuous_eval_left (m : Π i, E i) : continuous (λ p : continuous_multilinear_map 𝕜 E G, p m) := continuous_eval.comp (continuous_id.prod_mk continuous_const) lemma has_sum_eval {α : Type*} {p : α → continuous_multilinear_map 𝕜 E G} {q : continuous_multilinear_map 𝕜 E G} (h : has_sum p q) (m : Π i, E i) : has_sum (λ a, p a m) (q m) := begin dsimp [has_sum] at h ⊢, convert ((continuous_eval_left m).tendsto _).comp h, ext s, simp end open_locale topological_space open filter /-- If the target space is complete, the space of continuous multilinear maps with its norm is also complete. The proof is essentially the same as for the space of continuous linear maps (modulo the addition of `finset.prod` where needed. The duplication could be avoided by deducing the linear case from the multilinear case via a currying isomorphism. However, this would mess up imports, and it is more satisfactory to have the simplest case as a standalone proof. -/ instance [complete_space G] : complete_space (continuous_multilinear_map 𝕜 E G) := begin have nonneg : ∀ (v : Π i, E i), 0 ≤ ∏ i, ∥v i∥ := λ v, finset.prod_nonneg (λ i hi, norm_nonneg _), -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, -- and establish that the evaluation at any point `v : Π i, E i` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∏ i, ∥v i∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (nonneg v) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `G` is complete) -- into a function which we call `F`. choose F hF using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `F` is multilinear, let Fmult : multilinear_map 𝕜 E G := { to_fun := F, map_add' := λ v i x y, begin have A := hF (function.update v i (x + y)), have B := (hF (function.update v i x)).add (hF (function.update v i y)), simp at A B, exact tendsto_nhds_unique A B end, map_smul' := λ v i c x, begin have A := hF (function.update v i (c • x)), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hF (function.update v i x)), simp at A B, exact tendsto_nhds_unique A B end }, -- and that `F` has norm at most `(b 0 + ∥f 0∥)`. have Fnorm : ∀ v, ∥F v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∏ i, ∥v i∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hF v).norm (eventually_of_forall A) }, -- Thus `F` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Fcont := Fmult.mk_continuous _ Fnorm, use Fcont, -- Our last task is to establish convergence to `F` in norm. have : ∀ n, ∥f n - Fcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∏ i, ∥v i∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Fcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hF v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end continuous_multilinear_map /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le (f : multilinear_map 𝕜 E G) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ C := continuous_multilinear_map.op_norm_le_bound _ hC (λm, H m) /-- If a continuous multilinear map is constructed from a multilinear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma multilinear_map.mk_continuous_norm_le' (f : multilinear_map 𝕜 E G) {C : ℝ} (H : ∀ m, ∥f m∥ ≤ C * ∏ i, ∥m i∥) : ∥f.mk_continuous C H∥ ≤ max C 0 := continuous_multilinear_map.op_norm_le_bound _ (le_max_right _ _) $ λ m, (H m).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (prod_nonneg $ λ _ _, norm_nonneg _) namespace continuous_multilinear_map /-- Given a continuous multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k` of these variables, one gets a new continuous multilinear map on `fin k` by varying these variables, and fixing the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that we use is the canonical (increasing) bijection. -/ def restr {k n : ℕ} (f : (G [×n]→L[𝕜] G' : _)) (s : finset (fin n)) (hk : s.card = k) (z : G) : G [×k]→L[𝕜] G' := (f.to_multilinear_map.restr s hk z).mk_continuous (∥f∥ * ∥z∥^(n-k)) $ λ v, multilinear_map.restr_norm_le _ _ _ _ f.le_op_norm _ lemma norm_restr {k n : ℕ} (f : G [×n]→L[𝕜] G') (s : finset (fin n)) (hk : s.card = k) (z : G) : ∥f.restr s hk z∥ ≤ ∥f∥ * ∥z∥ ^ (n - k) := begin apply multilinear_map.mk_continuous_norm_le, exact mul_nonneg (norm_nonneg _) (pow_nonneg (norm_nonneg _) _) end section variables (𝕜 ι) (A : Type*) [normed_comm_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map 𝕜 (λ i : ι, A) A := @multilinear_map.mk_continuous 𝕜 ι (λ i : ι, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra 𝕜 ι A) (if nonempty ι then 1 else ∥(1 : A)∥) $ begin intro m, by_cases hι : nonempty ι, { resetI, simp [hι, norm_prod_le' univ univ_nonempty] }, { simp [eq_empty_of_not_nonempty hι univ, hι] } end variables {A 𝕜 ι} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra 𝕜 ι A m = ∏ i, m i := rfl lemma norm_mk_pi_algebra_le [nonempty ι] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ 1 := calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = _ : if_pos ‹_› lemma norm_mk_pi_algebra_of_empty (h : ¬nonempty ι) : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = ∥(1 : A)∥ := begin apply le_antisymm, calc ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ ≤ if nonempty ι then 1 else ∥(1 : A)∥ : multilinear_map.mk_continuous_norm_le _ (by split_ifs; simp [zero_le_one]) _ ... = ∥(1 : A)∥ : if_neg ‹_›, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp [eq_empty_of_not_nonempty h univ] end @[simp] lemma norm_mk_pi_algebra [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra 𝕜 ι A∥ = 1 := begin by_cases hι : nonempty ι, { resetI, refine le_antisymm norm_mk_pi_algebra_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp }, { simp [norm_mk_pi_algebra_of_empty hι] } end end section variables (𝕜 n) (A : Type*) [normed_ring A] [normed_algebra 𝕜 A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : continuous_multilinear_map 𝕜 (λ i : fin n, A) A := @multilinear_map.mk_continuous 𝕜 (fin n) (λ i : fin n, A) A _ _ _ _ _ _ _ (multilinear_map.mk_pi_algebra_fin 𝕜 n A) (nat.cases_on n ∥(1 : A)∥ (λ _, 1)) $ begin intro m, cases n, { simp }, { have : @list.of_fn A n.succ m ≠ [] := by simp, simpa [← fin.prod_of_fn] using list.norm_prod_le' this } end variables {A 𝕜 n} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A m = (list.of_fn m).prod := rfl lemma norm_mk_pi_algebra_fin_succ_le : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n.succ A∥ ≤ 1 := multilinear_map.mk_continuous_norm_le _ zero_le_one _ lemma norm_mk_pi_algebra_fin_le_of_pos (hn : 0 < n) : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ ≤ 1 := by cases n; [exact hn.false.elim, exact norm_mk_pi_algebra_fin_succ_le] lemma norm_mk_pi_algebra_fin_zero : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 0 A∥ = ∥(1 : A)∥ := begin refine le_antisymm (multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _) _, convert ratio_le_op_norm _ (λ _, 1); [simp, apply_instance] end lemma norm_mk_pi_algebra_fin [norm_one_class A] : ∥continuous_multilinear_map.mk_pi_algebra_fin 𝕜 n A∥ = 1 := begin cases n, { simp [norm_mk_pi_algebra_fin_zero] }, { refine le_antisymm norm_mk_pi_algebra_fin_succ_le _, convert ratio_le_op_norm _ (λ _, 1); [skip, apply_instance], simp } end end variables (𝕜 ι) /-- The canonical continuous multilinear map on `𝕜^ι`, associating to `m` the product of all the `m i` (multiplied by a fixed reference element `z` in the target module) -/ protected def mk_pi_field (z : G) : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G := @multilinear_map.mk_continuous 𝕜 ι (λ(i : ι), 𝕜) G _ _ _ _ _ _ _ (multilinear_map.mk_pi_ring 𝕜 ι z) (∥z∥) (λ m, by simp only [multilinear_map.mk_pi_ring_apply, norm_smul, normed_field.norm_prod, mul_comm]) variables {𝕜 ι} @[simp] lemma mk_pi_field_apply (z : G) (m : ι → 𝕜) : (continuous_multilinear_map.mk_pi_field 𝕜 ι z : (ι → 𝕜) → G) m = (∏ i, m i) • z := rfl lemma mk_pi_field_apply_one_eq_self (f : continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) : continuous_multilinear_map.mk_pi_field 𝕜 ι (f (λi, 1)) = f := to_multilinear_map_inj f.to_multilinear_map.mk_pi_ring_apply_one_eq_self variables (𝕜 ι G) /-- Continuous multilinear maps on `𝕜^n` with values in `G` are in bijection with `G`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a linear equivalence in `continuous_multilinear_map.pi_field_equiv_aux`. The continuous linear equivalence is `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv_aux : G ≃ₗ[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) := { to_fun := λ z, continuous_multilinear_map.mk_pi_field 𝕜 ι z, inv_fun := λ f, f (λi, 1), map_add' := λ z z', by { ext m, simp [smul_add] }, map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] }, left_inv := λ z, by simp, right_inv := λ f, f.mk_pi_field_apply_one_eq_self } /-- Continuous multilinear maps on `𝕜^n` with values in `G` are in bijection with `G`, as such a continuous multilinear map is completely determined by its value on the constant vector made of ones. We register this bijection as a continuous linear equivalence in `continuous_multilinear_map.pi_field_equiv`. -/ protected def pi_field_equiv : G ≃L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : ι), 𝕜) G) := { continuous_to_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G).to_linear_map.continuous_of_bound (1 : ℝ) (λz, _), rw one_mul, change ∥continuous_multilinear_map.mk_pi_field 𝕜 ι z∥ ≤ ∥z∥, exact multilinear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end, continuous_inv_fun := begin refine (continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G).symm.to_linear_map.continuous_of_bound (1 : ℝ) (λf, _), rw one_mul, change ∥f (λi, 1)∥ ≤ ∥f∥, apply @continuous_multilinear_map.unit_le_op_norm 𝕜 ι (λ (i : ι), 𝕜) G _ _ _ _ _ _ _ f, simp [pi_norm_le_iff zero_le_one, le_refl] end, .. continuous_multilinear_map.pi_field_equiv_aux 𝕜 ι G } end continuous_multilinear_map lemma continuous_linear_map.norm_comp_continuous_multilinear_map_le (g : G →L[𝕜] G') (f : continuous_multilinear_map 𝕜 E G) : ∥g.comp_continuous_multilinear_map f∥ ≤ ∥g∥ * ∥f∥ := continuous_multilinear_map.op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) $ λ m, calc ∥g (f m)∥ ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) : g.le_op_norm_of_le $ f.le_op_norm _ ... = _ : (mul_assoc _ _ _).symm namespace multilinear_map /-- Given a map `f : G →ₗ[𝕜] multilinear_map 𝕜 E G'` and an estimate `H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥`, construct a continuous linear map from `G` to `continuous_multilinear_map 𝕜 E G'`. In order to lift, e.g., a map `f : (multilinear_map 𝕜 E G) →ₗ[𝕜] multilinear_map 𝕜 E' G'` to a map `(continuous_multilinear_map 𝕜 E G) →L[𝕜] continuous_multilinear_map 𝕜 E' G'`, one can apply this construction to `f.comp continuous_multilinear_map.to_multilinear_map_linear` which is a linear map from `continuous_multilinear_map 𝕜 E G` to `multilinear_map 𝕜 E' G'`. -/ def mk_continuous_linear (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') (C : ℝ) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : G →L[𝕜] continuous_multilinear_map 𝕜 E G' := linear_map.mk_continuous { to_fun := λ x, (f x).mk_continuous (C * ∥x∥) $ H x, map_add' := λ x y, by { ext1, simp }, map_smul' := λ c x, by { ext1, simp } } (max C 0) $ λ x, ((f x).mk_continuous_norm_le' _).trans_eq $ by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul] lemma mk_continuous_linear_norm_le' (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') (C : ℝ) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : ∥mk_continuous_linear f C H∥ ≤ max C 0 := begin dunfold mk_continuous_linear, exact linear_map.mk_continuous_norm_le _ (le_max_right _ _) _ end lemma mk_continuous_linear_norm_le (f : G →ₗ[𝕜] multilinear_map 𝕜 E G') {C : ℝ} (hC : 0 ≤ C) (H : ∀ x m, ∥f x m∥ ≤ C * ∥x∥ * ∏ i, ∥m i∥) : ∥mk_continuous_linear f C H∥ ≤ C := (mk_continuous_linear_norm_le' f C H).trans_eq (max_eq_left hC) /-- Given a map `f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)` and an estimate `H : ∀ m m', ∥f m m'∥ ≤ C * ∏ i, ∥m i∥ * ∏ i, ∥m' i∥`, upgrade all `multilinear_map`s in the type to `continuous_multilinear_map`s. -/ def mk_continuous_multilinear (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) (C : ℝ) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : continuous_multilinear_map 𝕜 E (continuous_multilinear_map 𝕜 E' G) := mk_continuous { to_fun := λ m, mk_continuous (f m) (C * ∏ i, ∥m i∥) $ H m, map_add' := λ m i x y, by { ext1, simp }, map_smul' := λ m i c x, by { ext1, simp } } (max C 0) $ λ m, ((f m).mk_continuous_norm_le' _).trans_eq $ by { rw [max_mul_of_nonneg, zero_mul], exact prod_nonneg (λ _ _, norm_nonneg _) } @[simp] lemma mk_continuous_multilinear_apply (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) {C : ℝ} (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) (m : Π i, E i) : ⇑(mk_continuous_multilinear f C H m) = f m := rfl lemma mk_continuous_multilinear_norm_le' (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) (C : ℝ) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : ∥mk_continuous_multilinear f C H∥ ≤ max C 0 := begin dunfold mk_continuous_multilinear, exact mk_continuous_norm_le _ (le_max_right _ _) _ end lemma mk_continuous_multilinear_norm_le (f : multilinear_map 𝕜 E (multilinear_map 𝕜 E' G)) {C : ℝ} (hC : 0 ≤ C) (H : ∀ m₁ m₂, ∥f m₁ m₂∥ ≤ C * (∏ i, ∥m₁ i∥) * ∏ i, ∥m₂ i∥) : ∥mk_continuous_multilinear f C H∥ ≤ C := (mk_continuous_multilinear_norm_le' f C H).trans_eq (max_eq_left hC) end multilinear_map section currying /-! ### Currying We associate to a continuous multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two curried functions, named `f.curry_left` (which is a continuous linear map on `E 0` taking values in continuous multilinear maps in `n` variables) and `f.curry_right` (which is a continuous multilinear map in `n` variables taking values in continuous linear maps on `E (last n)`). The inverse operations are called `uncurry_left` and `uncurry_right`. We also register continuous linear equiv versions of these correspondences, in `continuous_multilinear_curry_left_equiv` and `continuous_multilinear_curry_right_equiv`. -/ open fin function lemma continuous_linear_map.norm_map_tail_le (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) (m : Πi, Ei i) : ∥f (m 0) (tail m)∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (m 0) (tail m)∥ ≤ ∥f (m 0)∥ * ∏ i, ∥(tail m) i∥ : (f (m 0)).le_op_norm _ ... ≤ (∥f∥ * ∥m 0∥) * ∏ i, ∥(tail m) i∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (prod_nonneg (λi hi, norm_nonneg _)) ... = ∥f∥ * (∥m 0∥ * ∏ i, ∥(tail m) i∥) : by ring ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_succ, refl } lemma continuous_multilinear_map.norm_map_init_le (f : continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) (m : Πi, Ei i) : ∥f (init m) (m (last n))∥ ≤ ∥f∥ * ∏ i, ∥m i∥ := calc ∥f (init m) (m (last n))∥ ≤ ∥f (init m)∥ * ∥m (last n)∥ : (f (init m)).le_op_norm _ ... ≤ (∥f∥ * (∏ i, ∥(init m) i∥)) * ∥m (last n)∥ : mul_le_mul_of_nonneg_right (f.le_op_norm _) (norm_nonneg _) ... = ∥f∥ * ((∏ i, ∥(init m) i∥) * ∥m (last n)∥) : mul_assoc _ _ _ ... = ∥f∥ * ∏ i, ∥m i∥ : by { rw prod_univ_cast_succ, refl } lemma continuous_multilinear_map.norm_map_cons_le (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (m : Π(i : fin n), Ei i.succ) : ∥f (cons x m)∥ ≤ ∥f∥ * ∥x∥ * ∏ i, ∥m i∥ := calc ∥f (cons x m)∥ ≤ ∥f∥ * ∏ i, ∥cons x m i∥ : f.le_op_norm _ ... = (∥f∥ * ∥x∥) * ∏ i, ∥m i∥ : by { rw prod_univ_succ, simp [mul_assoc] } lemma continuous_multilinear_map.norm_map_snoc_le (f : continuous_multilinear_map 𝕜 Ei G) (m : Π(i : fin n), Ei i.cast_succ) (x : Ei (last n)) : ∥f (snoc m x)∥ ≤ ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ := calc ∥f (snoc m x)∥ ≤ ∥f∥ * ∏ i, ∥snoc m x i∥ : f.le_op_norm _ ... = ∥f∥ * (∏ i, ∥m i∥) * ∥x∥ : by { rw prod_univ_cast_succ, simp [mul_assoc] } /-! #### Left currying -/ /-- Given a continuous linear map `f` from `E 0` to continuous multilinear maps on `n` variables, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (m 0) (tail m)`-/ def continuous_linear_map.uncurry_left (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : continuous_multilinear_map 𝕜 Ei G := (@linear_map.uncurry_left 𝕜 n Ei G _ _ _ _ _ (continuous_multilinear_map.to_multilinear_map_linear.comp f.to_linear_map)).mk_continuous (∥f∥) (λm, continuous_linear_map.norm_map_tail_le f m) @[simp] lemma continuous_linear_map.uncurry_left_apply (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) (m : Πi, Ei i) : f.uncurry_left m = f (m 0) (tail m) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the first variable to obtain a continuous linear map into continuous multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/ def continuous_multilinear_map.curry_left (f : continuous_multilinear_map 𝕜 Ei G) : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G) := linear_map.mk_continuous { -- define a linear map into `n` continuous multilinear maps from an `n+1` continuous multilinear -- map to_fun := λx, (f.to_multilinear_map.curry_left x).mk_continuous (∥f∥ * ∥x∥) (f.norm_map_cons_le x), map_add' := λx y, by { ext m, exact f.cons_add m x y }, map_smul' := λc x, by { ext m, exact f.cons_smul m c x } } -- then register its continuity thanks to its boundedness properties. (∥f∥) (λx, multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _) @[simp] lemma continuous_multilinear_map.curry_left_apply (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (m : Π(i : fin n), Ei i.succ) : f.curry_left x m = f (cons x m) := rfl @[simp] lemma continuous_linear_map.curry_uncurry_left (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : f.uncurry_left.curry_left = f := begin ext m x, simp only [tail_cons, continuous_linear_map.uncurry_left_apply, continuous_multilinear_map.curry_left_apply], rw cons_zero end @[simp] lemma continuous_multilinear_map.uncurry_curry_left (f : continuous_multilinear_map 𝕜 Ei G) : f.curry_left.uncurry_left = f := continuous_multilinear_map.to_multilinear_map_inj $ f.to_multilinear_map.uncurry_curry_left variables (𝕜 Ei G) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), E i` is canonically isomorphic to the space of continuous linear maps from `E 0` to the space of continuous multilinear maps on `Π(i : fin n), E i.succ `, by separating the first variable. We register this isomorphism in `continuous_multilinear_curry_left_equiv 𝕜 E E₂`. The algebraic version (without topology) is given in `multilinear_curry_left_equiv 𝕜 E E₂`. The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_left_equiv : (Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) ≃ₗᵢ[𝕜] (continuous_multilinear_map 𝕜 Ei G) := linear_isometry_equiv.of_bounds { to_fun := continuous_linear_map.uncurry_left, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_left, left_inv := continuous_linear_map.curry_uncurry_left, right_inv := continuous_multilinear_map.uncurry_curry_left } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, linear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables {𝕜 Ei G} @[simp] lemma continuous_multilinear_curry_left_equiv_apply (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.succ) G)) (v : Π i, Ei i) : continuous_multilinear_curry_left_equiv 𝕜 Ei G f v = f (v 0) (tail v) := rfl @[simp] lemma continuous_multilinear_curry_left_equiv_symm_apply (f : continuous_multilinear_map 𝕜 Ei G) (x : Ei 0) (v : Π i : fin n, Ei i.succ) : (continuous_multilinear_curry_left_equiv 𝕜 Ei G).symm f x v = f (cons x v) := rfl @[simp] lemma continuous_multilinear_map.curry_left_norm (f : continuous_multilinear_map 𝕜 Ei G) : ∥f.curry_left∥ = ∥f∥ := (continuous_multilinear_curry_left_equiv 𝕜 Ei G).symm.norm_map f @[simp] lemma continuous_linear_map.uncurry_left_norm (f : Ei 0 →L[𝕜] (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.succ) G)) : ∥f.uncurry_left∥ = ∥f∥ := (continuous_multilinear_curry_left_equiv 𝕜 Ei G).norm_map f /-! #### Right currying -/ /-- Given a continuous linear map `f` from continuous multilinear maps on `n` variables to continuous linear maps on `E 0`, construct the corresponding continuous multilinear map on `n+1` variables obtained by concatenating the variables, given by `m ↦ f (init m) (m (last n))`. -/ def continuous_multilinear_map.uncurry_right (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : continuous_multilinear_map 𝕜 Ei G := let f' : multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →ₗ[𝕜] G) := { to_fun := λ m, (f m).to_linear_map, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in (@multilinear_map.uncurry_right 𝕜 n Ei G _ _ _ _ _ f').mk_continuous (∥f∥) (λm, f.norm_map_init_le m) @[simp] lemma continuous_multilinear_map.uncurry_right_apply (f : continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) (m : Πi, Ei i) : f.uncurry_right m = f (init m) (m (last n)) := rfl /-- Given a continuous multilinear map `f` in `n+1` variables, split the last variable to obtain a continuous multilinear map in `n` variables into continuous linear maps, given by `m ↦ (x ↦ f (snoc m x))`. -/ def continuous_multilinear_map.curry_right (f : continuous_multilinear_map 𝕜 Ei G) : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G) := let f' : multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G) := { to_fun := λm, (f.to_multilinear_map.curry_right m).mk_continuous (∥f∥ * ∏ i, ∥m i∥) $ λx, f.norm_map_snoc_le m x, map_add' := λ m i x y, by { simp, refl }, map_smul' := λ m i c x, by { simp, refl } } in f'.mk_continuous (∥f∥) (λm, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (prod_nonneg (λj hj, norm_nonneg _))) _) @[simp] lemma continuous_multilinear_map.curry_right_apply (f : continuous_multilinear_map 𝕜 Ei G) (m : Π i : fin n, Ei i.cast_succ) (x : Ei (last n)) : f.curry_right m x = f (snoc m x) := rfl @[simp] lemma continuous_multilinear_map.curry_uncurry_right (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : f.uncurry_right.curry_right = f := begin ext m x, simp only [snoc_last, continuous_multilinear_map.curry_right_apply, continuous_multilinear_map.uncurry_right_apply], rw init_snoc end @[simp] lemma continuous_multilinear_map.uncurry_curry_right (f : continuous_multilinear_map 𝕜 Ei G) : f.curry_right.uncurry_right = f := by { ext m, simp } variables (𝕜 Ei G) /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), Ei i` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), Ei i.cast_succ` with values in the space of continuous linear maps on `Ei (last n)`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv 𝕜 Ei G`. The algebraic version (without topology) is given in `multilinear_curry_right_equiv 𝕜 Ei G`. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_right_equiv : (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) ≃ₗᵢ[𝕜] (continuous_multilinear_map 𝕜 Ei G) := linear_isometry_equiv.of_bounds { to_fun := continuous_multilinear_map.uncurry_right, map_add' := λf₁ f₂, by { ext m, refl }, map_smul' := λc f, by { ext m, refl }, inv_fun := continuous_multilinear_map.curry_right, left_inv := continuous_multilinear_map.curry_uncurry_right, right_inv := continuous_multilinear_map.uncurry_curry_right } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables (n G') /-- The space of continuous multilinear maps on `Π(i : fin (n+1)), G` is canonically isomorphic to the space of continuous multilinear maps on `Π(i : fin n), G` with values in the space of continuous linear maps on `G`, by separating the last variable. We register this isomorphism as a continuous linear equiv in `continuous_multilinear_curry_right_equiv' 𝕜 n G G'`. For a version allowing dependent types, see `continuous_multilinear_curry_right_equiv`. When there are no dependent types, use the primed version as it helps Lean a lot for unification. The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_right_equiv' : (G [×n]→L[𝕜] (G →L[𝕜] G')) ≃ₗᵢ[𝕜] (G [×n.succ]→L[𝕜] G') := continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin n.succ), G) G' variables {n 𝕜 G Ei G'} @[simp] lemma continuous_multilinear_curry_right_equiv_apply (f : (continuous_multilinear_map 𝕜 (λ(i : fin n), Ei i.cast_succ) (Ei (last n) →L[𝕜] G))) (v : Π i, Ei i) : (continuous_multilinear_curry_right_equiv 𝕜 Ei G) f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply (f : continuous_multilinear_map 𝕜 Ei G) (v : Π (i : fin n), Ei i.cast_succ) (x : Ei (last n)) : (continuous_multilinear_curry_right_equiv 𝕜 Ei G).symm f v x = f (snoc v x) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_apply' (f : G [×n]→L[𝕜] (G →L[𝕜] G')) (v : Π (i : fin n.succ), G) : continuous_multilinear_curry_right_equiv' 𝕜 n G G' f v = f (init v) (v (last n)) := rfl @[simp] lemma continuous_multilinear_curry_right_equiv_symm_apply' (f : G [×n.succ]→L[𝕜] G') (v : Π (i : fin n), G) (x : G) : (continuous_multilinear_curry_right_equiv' 𝕜 n G G').symm f v x = f (snoc v x) := rfl @[simp] lemma continuous_multilinear_map.curry_right_norm (f : continuous_multilinear_map 𝕜 Ei G) : ∥f.curry_right∥ = ∥f∥ := (continuous_multilinear_curry_right_equiv 𝕜 Ei G).symm.norm_map f @[simp] lemma continuous_multilinear_map.uncurry_right_norm (f : continuous_multilinear_map 𝕜 (λ i : fin n, Ei i.cast_succ) (Ei (last n) →L[𝕜] G)) : ∥f.uncurry_right∥ = ∥f∥ := (continuous_multilinear_curry_right_equiv 𝕜 Ei G).norm_map f /-! #### Currying with `0` variables The space of multilinear maps with `0` variables is trivial: such a multilinear map is just an arbitrary constant (note that multilinear maps in `0` variables need not map `0` to `0`!). Therefore, the space of continuous multilinear maps on `(fin 0) → G` with values in `E₂` is isomorphic (and even isometric) to `E₂`. As this is the zeroth step in the construction of iterated derivatives, we register this isomorphism. -/ variables {𝕜 G G'} /-- Associating to a continuous multilinear map in `0` variables the unique value it takes. -/ def continuous_multilinear_map.uncurry0 (f : continuous_multilinear_map 𝕜 (λ (i : fin 0), G) G') : G' := f 0 variables (𝕜 G) /-- Associating to an element `x` of a vector space `E₂` the continuous multilinear map in `0` variables taking the (unique) value `x` -/ def continuous_multilinear_map.curry0 (x : G') : G [×0]→L[𝕜] G' := { to_fun := λm, x, map_add' := λ m i, fin.elim0 i, map_smul' := λ m i, fin.elim0 i, cont := continuous_const } variable {G} @[simp] lemma continuous_multilinear_map.curry0_apply (x : G') (m : (fin 0) → G) : continuous_multilinear_map.curry0 𝕜 G x m = x := rfl variable {𝕜} @[simp] lemma continuous_multilinear_map.uncurry0_apply (f : G [×0]→L[𝕜] G') : f.uncurry0 = f 0 := rfl @[simp] lemma continuous_multilinear_map.apply_zero_curry0 (f : G [×0]→L[𝕜] G') {x : fin 0 → G} : continuous_multilinear_map.curry0 𝕜 G (f x) = f := by { ext m, simp [(subsingleton.elim _ _ : x = m)] } lemma continuous_multilinear_map.uncurry0_curry0 (f : G [×0]→L[𝕜] G') : continuous_multilinear_map.curry0 𝕜 G (f.uncurry0) = f := by simp variables (𝕜 G) @[simp] lemma continuous_multilinear_map.curry0_uncurry0 (x : G') : (continuous_multilinear_map.curry0 𝕜 G x).uncurry0 = x := rfl @[simp] lemma continuous_multilinear_map.curry0_norm (x : G') : ∥continuous_multilinear_map.curry0 𝕜 G x∥ = ∥x∥ := begin apply le_antisymm, { exact continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp) }, { simpa using (continuous_multilinear_map.curry0 𝕜 G x).le_op_norm 0 } end variables {𝕜 G} @[simp] lemma continuous_multilinear_map.fin0_apply_norm (f : G [×0]→L[𝕜] G') {x : fin 0 → G} : ∥f x∥ = ∥f∥ := begin have : x = 0 := subsingleton.elim _ _, subst this, refine le_antisymm (by simpa using f.le_op_norm 0) _, have : ∥continuous_multilinear_map.curry0 𝕜 G (f.uncurry0)∥ ≤ ∥f.uncurry0∥ := continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λm, by simp [-continuous_multilinear_map.apply_zero_curry0]), simpa end lemma continuous_multilinear_map.uncurry0_norm (f : G [×0]→L[𝕜] G') : ∥f.uncurry0∥ = ∥f∥ := by simp variables (𝕜 G G') /-- The continuous linear isomorphism between elements of a normed space, and continuous multilinear maps in `0` variables with values in this normed space. The direct and inverse maps are `uncurry0` and `curry0`. Use these unless you need the full framework of linear isometric equivs. -/ def continuous_multilinear_curry_fin0 : (G [×0]→L[𝕜] G') ≃ₗᵢ[𝕜] G' := { to_fun := λf, continuous_multilinear_map.uncurry0 f, inv_fun := λf, continuous_multilinear_map.curry0 𝕜 G f, map_add' := λf g, rfl, map_smul' := λc f, rfl, left_inv := continuous_multilinear_map.uncurry0_curry0, right_inv := continuous_multilinear_map.curry0_uncurry0 𝕜 G, norm_map' := continuous_multilinear_map.uncurry0_norm } variables {𝕜 G G'} @[simp] lemma continuous_multilinear_curry_fin0_apply (f : G [×0]→L[𝕜] G') : continuous_multilinear_curry_fin0 𝕜 G G' f = f 0 := rfl @[simp] lemma continuous_multilinear_curry_fin0_symm_apply (x : G') (v : (fin 0) → G) : (continuous_multilinear_curry_fin0 𝕜 G G').symm x v = x := rfl /-! #### With 1 variable -/ variables (𝕜 G G') /-- Continuous multilinear maps from `G^1` to `G'` are isomorphic with continuous linear maps from `G` to `G'`. -/ def continuous_multilinear_curry_fin1 : (G [×1]→L[𝕜] G') ≃ₗᵢ[𝕜] (G →L[𝕜] G') := (continuous_multilinear_curry_right_equiv 𝕜 (λ (i : fin 1), G) G').symm.trans (continuous_multilinear_curry_fin0 𝕜 G (G →L[𝕜] G')) variables {𝕜 G G'} @[simp] lemma continuous_multilinear_curry_fin1_apply (f : G [×1]→L[𝕜] G') (x : G) : continuous_multilinear_curry_fin1 𝕜 G G' f x = f (fin.snoc 0 x) := rfl @[simp] lemma continuous_multilinear_curry_fin1_symm_apply (f : G →L[𝕜] G') (v : (fin 1) → G) : (continuous_multilinear_curry_fin1 𝕜 G G').symm f v = f (v 0) := rfl namespace continuous_multilinear_map variables (𝕜 G G') /-- An equivalence of the index set defines a linear isometric equivalence between the spaces of multilinear maps. -/ def dom_dom_congr (σ : ι ≃ ι') : continuous_multilinear_map 𝕜 (λ _ : ι, G) G' ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 (λ _ : ι', G) G' := linear_isometry_equiv.of_bounds { to_fun := λ f, (multilinear_map.dom_dom_congr σ f.to_multilinear_map).mk_continuous ∥f∥ $ λ m, (f.le_op_norm (λ i, m (σ i))).trans_eq $ by rw [← σ.prod_comp], inv_fun := λ f, (multilinear_map.dom_dom_congr σ.symm f.to_multilinear_map).mk_continuous ∥f∥ $ λ m, (f.le_op_norm (λ i, m (σ.symm i))).trans_eq $ by rw [← σ.symm.prod_comp], left_inv := λ f, ext $ λ m, congr_arg f $ by simp only [σ.symm_apply_apply], right_inv := λ f, ext $ λ m, congr_arg f $ by simp only [σ.apply_symm_apply], map_add' := λ f g, rfl, map_smul' := λ c f, rfl } (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) variables {𝕜 G G'} section variable [decidable_eq (ι ⊕ ι')] /-- A continuous multilinear map with variables indexed by `ι ⊕ ι'` defines a continuous multilinear map with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'`. -/ def curry_sum (f : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G') : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G') := multilinear_map.mk_continuous_multilinear (multilinear_map.curry_sum f.to_multilinear_map) (∥f∥) $ λ m m', by simpa [fintype.prod_sum_type, mul_assoc] using f.le_op_norm (sum.elim m m') @[simp] lemma curry_sum_apply (f : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G') (m : ι → G) (m' : ι' → G) : f.curry_sum m m' = f (sum.elim m m') := rfl /-- A continuous multilinear map with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'` defines a continuous multilinear map with variables indexed by `ι ⊕ ι'`. -/ def uncurry_sum (f : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G')) : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G' := multilinear_map.mk_continuous (to_multilinear_map_linear.comp_multilinear_map f.to_multilinear_map).uncurry_sum (∥f∥) $ λ m, by simpa [fintype.prod_sum_type, mul_assoc] using (f (m ∘ sum.inl)).le_of_op_norm_le (m ∘ sum.inr) (f.le_op_norm _) @[simp] lemma uncurry_sum_apply (f : continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G')) (m : ι ⊕ ι' → G) : f.uncurry_sum m = f (m ∘ sum.inl) (m ∘ sum.inr) := rfl variables (𝕜 ι ι' G G') /-- Linear isometric equivalence between the space of continuous multilinear maps with variables indexed by `ι ⊕ ι'` and the space of continuous multilinear maps with variables indexed by `ι` taking values in the space of continuous multilinear maps with variables indexed by `ι'`. The forward and inverse functions are `continuous_multilinear_map.curry_sum` and `continuous_multilinear_map.uncurry_sum`. Use this definition only if you need some properties of `linear_isometry_equiv`. -/ def curry_sum_equiv : continuous_multilinear_map 𝕜 (λ x : ι ⊕ ι', G) G' ≃ₗᵢ[𝕜] continuous_multilinear_map 𝕜 (λ x : ι, G) (continuous_multilinear_map 𝕜 (λ x : ι', G) G') := linear_isometry_equiv.of_bounds { to_fun := curry_sum, inv_fun := uncurry_sum, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, left_inv := λ f, by { ext m, exact congr_arg f (sum.elim_comp_inl_inr m) }, right_inv := λ f, by { ext m₁ m₂, change f _ _ = f _ _, rw [sum.elim_comp_inl, sum.elim_comp_inr] } } (λ f, multilinear_map.mk_continuous_multilinear_norm_le _ (norm_nonneg f) _) (λ f, multilinear_map.mk_continuous_norm_le _ (norm_nonneg f) _) end section variables (𝕜 G G') {k l : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] /-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality `l`, then the space of continuous multilinear maps `G [×n]→L[𝕜] G'` of `n` variables is isomorphic to the space of continuous multilinear maps `G [×k]→L[𝕜] G [×l]→L[𝕜] G'` of `k` variables taking values in the space of continuous multilinear maps of `l` variables. -/ def curry_fin_finset {k l n : ℕ} {s : finset (fin n)} [decidable_pred (s : set (fin n))] (hk : s.card = k) (hl : sᶜ.card = l) : (G [×n]→L[𝕜] G') ≃ₗᵢ[𝕜] (G [×k]→L[𝕜] G [×l]→L[𝕜] G') := (dom_dom_congr 𝕜 G G' (fin_sum_equiv_of_finset hk hl).symm).trans (curry_sum_equiv 𝕜 (fin k) (fin l) G G') variables {𝕜 G G'} @[simp] lemma curry_fin_finset_apply (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×n]→L[𝕜] G') (mk : fin k → G) (ml : fin l → G) : curry_fin_finset 𝕜 G G' hk hl f mk ml = f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) := rfl @[simp] lemma curry_fin_finset_symm_apply (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (m : fin n → G) : (curry_fin_finset 𝕜 G G' hk hl).symm f m = f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i)) (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) := rfl @[simp] lemma curry_fin_finset_symm_apply_piecewise_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (x y : G) : (curry_fin_finset 𝕜 G G' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) := multilinear_map.curry_fin_finset_symm_apply_piecewise_const hk hl _ x y @[simp] lemma curry_fin_finset_symm_apply_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×k]→L[𝕜] G [×l]→L[𝕜] G') (x : G) : (curry_fin_finset 𝕜 G G' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) := rfl @[simp] lemma curry_fin_finset_apply_const (hk : s.card = k) (hl : sᶜ.card = l) (f : G [×n]→L[𝕜] G') (x y : G) : curry_fin_finset 𝕜 G G' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) := begin refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails rw linear_isometry_equiv.symm_apply_apply end end end continuous_multilinear_map end currying
228bb70e85f91e3480663f6e645fc2ce4e817e26
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/power_series/basic.lean
92c6498aaa774fa6b5c950510d56eb973581a21a
[ "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
64,539
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.mv_polynomial import linear_algebra.std_basis import ring_theory.ideal.local_ring import ring_theory.ideal.operations import ring_theory.multiplicity import ring_theory.algebra_tower import tactic.linarith import algebra.big_operators.nat_antidiagonal /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as `φ`, for all `m ≤ n`, and `0` otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `le_order_add`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `R` as `mv_power_series σ R := (σ →₀ ℕ) → R`. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as `power_series R := mv_power_series unit R`. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by `unit →₀ ℕ`, which is of course canonically isomorphic to `ℕ`. We then build some glue to treat formal power series as if they are indexed by `ℕ`. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical big_operators /-- Multivariate formal power series, where `σ` is the index set of the variables and `R` is the coefficient ring.-/ def mv_power_series (σ : Type*) (R : Type*) := (σ →₀ ℕ) → R namespace mv_power_series open finsupp variables {σ R : Type*} instance [inhabited R] : inhabited (mv_power_series σ R) := ⟨λ _, default _⟩ instance [has_zero R] : has_zero (mv_power_series σ R) := pi.has_zero instance [add_monoid R] : add_monoid (mv_power_series σ R) := pi.add_monoid instance [add_group R] : add_group (mv_power_series σ R) := pi.add_group instance [add_comm_monoid R] : add_comm_monoid (mv_power_series σ R) := pi.add_comm_monoid instance [add_comm_group R] : add_comm_group (mv_power_series σ R) := pi.add_comm_group instance [nontrivial R] : nontrivial (mv_power_series σ R) := function.nontrivial instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (mv_power_series σ A) := pi.module _ _ _ instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (mv_power_series σ A) := pi.is_scalar_tower section semiring variables (R) [semiring R] /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : R →ₗ[R] mv_power_series σ R := linear_map.std_basis R _ n /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ R) →ₗ[R] R := linear_map.proj n variables {R} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ R} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff R n φ = coeff R n ψ) := function.funext_iff lemma monomial_def [decidable_eq σ] (n : σ →₀ ℕ) : monomial R n = linear_map.std_basis R _ n := by convert rfl -- unify the `decidable` arguments lemma coeff_monomial [decidable_eq σ] (m n : σ →₀ ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := by rw [coeff, monomial_def, linear_map.proj_apply, linear_map.std_basis_apply, function.update_apply, pi.zero_apply] @[simp] lemma coeff_monomial_same (n : σ →₀ ℕ) (a : R) : coeff R n (monomial R n a) = a := linear_map.std_basis_same R _ n a lemma coeff_monomial_ne {m n : σ →₀ ℕ} (h : m ≠ n) (a : R) : coeff R m (monomial R n a) = 0 := linear_map.std_basis_ne R _ _ _ h a lemma eq_of_coeff_monomial_ne_zero {m n : σ →₀ ℕ} {a : R} (h : coeff R m (monomial R n a) ≠ 0) : m = n := by_contra $ λ h', h $ coeff_monomial_ne h' a @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff R n (0 : mv_power_series σ R) = 0 := rfl variables (m n : σ →₀ ℕ) (φ ψ : mv_power_series σ R) instance : has_one (mv_power_series σ R) := ⟨monomial R (0 : σ →₀ ℕ) 1⟩ lemma coeff_one [decidable_eq σ] : coeff R n (1 : mv_power_series σ R) = if n = 0 then 1 else 0 := coeff_monomial _ _ _ lemma coeff_zero_one : coeff R (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial_same 0 1 lemma monomial_zero_one : monomial R (0 : σ →₀ ℕ) 1 = 1 := rfl instance : has_mul (mv_power_series σ R) := ⟨λ φ ψ n, ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ⟩ lemma coeff_mul : coeff R n (φ * ψ) = ∑ p in finsupp.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := rfl protected lemma zero_mul : (0 : mv_power_series σ R) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] lemma coeff_monomial_mul (a : R) : coeff R m (monomial R n a * φ) = if n ≤ m then a * coeff R (m - n) φ else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 (monomial R n a) * coeff R p.2 φ ≠ 0 → p.1 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (left_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_fst_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_mul_monomial (a : R) : coeff R m (φ * monomial R n a) = if n ≤ m then coeff R (m - n) φ * a else 0 := begin have : ∀ p ∈ antidiagonal m, coeff R (p : (σ →₀ ℕ) × (σ →₀ ℕ)).1 φ * coeff R p.2 (monomial R n a) ≠ 0 → p.2 = n := λ p _ hp, eq_of_coeff_monomial_ne_zero (right_ne_zero_of_mul hp), rw [coeff_mul, ← finset.sum_filter_of_ne this, antidiagonal_filter_snd_eq, finset.sum_ite_index], simp only [finset.sum_singleton, coeff_monomial_same, finset.sum_empty] end lemma coeff_add_monomial_mul (a : R) : coeff R (m + n) (monomial R m a * φ) = a * coeff R n φ := begin rw [coeff_monomial_mul, if_pos, add_sub_cancel_left], exact le_add_right le_rfl end lemma coeff_add_mul_monomial (a : R) : coeff R (m + n) (φ * monomial R n a) = coeff R m φ * a := begin rw [coeff_mul_monomial, if_pos, add_sub_cancel_right], exact le_add_left le_rfl end protected lemma one_mul : (1 : mv_power_series σ R) * φ = φ := ext $ λ n, by simpa using coeff_add_monomial_mul 0 n φ 1 protected lemma mul_one : φ * 1 = φ := ext $ λ n, by simpa using coeff_add_mul_monomial n 0 φ 1 protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ R) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, linear_map.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, linear_map.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ R) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := begin ext1 n, simp only [coeff_mul, finset.sum_mul, finset.mul_sum, finset.sum_sigma'], refine finset.sum_bij (λ p _, ⟨(p.2.1, p.2.2 + p.1.2), (p.2.2, p.1.2)⟩) _ _ _ _; simp only [mem_antidiagonal, finset.mem_sigma, heq_iff_eq, prod.mk.inj_iff, and_imp, exists_prop], { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩, dsimp only, rintro rfl rfl, simp [add_assoc] }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩, dsimp only, rintro rfl rfl, apply mul_assoc }, { rintros ⟨⟨a, b⟩, ⟨c, d⟩⟩ ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl - rfl rfl - rfl rfl, refl }, { rintro ⟨⟨i, j⟩, ⟨k, l⟩⟩, dsimp only, rintro rfl rfl, refine ⟨⟨(i + k, l), (i, k)⟩, _, _⟩; simp [add_assoc] } end instance : semiring (mv_power_series σ R) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring R] : comm_semiring (mv_power_series σ R) := { mul_comm := λ φ ψ, ext $ λ n, by simpa only [coeff_mul, mul_comm] using sum_antidiagonal_swap n (λ a b, coeff R a φ * coeff R b ψ), .. mv_power_series.semiring } instance [ring R] : ring (mv_power_series σ R) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring R] : comm_ring (mv_power_series σ R) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring R] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : R) : monomial R m a * monomial R n b = monomial R (m + n) (a * b) := begin ext k, simp only [coeff_mul_monomial, coeff_monomial], split_ifs with h₁ h₂ h₃ h₃ h₂; try { refl }, { rw [← h₂, sub_add_cancel_of_le h₁] at h₃, exact (h₃ rfl).elim }, { rw [h₃, add_sub_cancel_right] at h₂, exact (h₂ rfl).elim }, { exact zero_mul b }, { rw h₂ at h₁, exact (h₁ $ le_add_left le_rfl).elim } end variables (σ) (R) /-- The constant multivariate formal power series.-/ def C : R →+* mv_power_series σ R := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, map_zero' := (monomial R (0 : _)).map_zero, .. monomial R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma monomial_zero_eq_C : ⇑(monomial R (0 : σ →₀ ℕ)) = C σ R := rfl lemma monomial_zero_eq_C_apply (a : R) : monomial R (0 : σ →₀ ℕ) a = C σ R a := rfl lemma coeff_C [decidable_eq σ] (n : σ →₀ ℕ) (a : R) : coeff R n (C σ R a) = if n = 0 then a else 0 := coeff_monomial _ _ _ lemma coeff_zero_C (a : R) : coeff R (0 : σ →₀ℕ) (C σ R a) = a := coeff_monomial_same 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ R := monomial R (single s 1) 1 lemma coeff_X [decidable_eq σ] (n : σ →₀ ℕ) (s : σ) : coeff R n (X s : mv_power_series σ R) = if n = (single s 1) then 1 else 0 := coeff_monomial _ _ _ lemma coeff_index_single_X [decidable_eq σ] (s t : σ) : coeff R (single t 1) (X s : mv_power_series σ R) = if t = s then 1 else 0 := by { simp only [coeff_X, single_left_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff R (single s 1) (X s : mv_power_series σ R) = 1 := coeff_monomial_same _ _ lemma coeff_zero_X (s : σ) : coeff R (0 : σ →₀ ℕ) (X s : mv_power_series σ R) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial R (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ R)^n = monomial R (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero, monomial_zero_one] }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow [decidable_eq σ] (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff R m ((X s : mv_power_series σ R)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (φ * C σ R a) = coeff R n φ * a := by simpa using coeff_add_mul_monomial n 0 φ a @[simp] lemma coeff_C_mul (n : σ →₀ ℕ) (φ : mv_power_series σ R) (a : R) : coeff R n (C σ R a * φ) = a * coeff R n φ := by simpa using coeff_add_monomial_mul 0 n φ a lemma coeff_zero_mul_X (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (φ * X s) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_mul_monomial, if_neg this] end lemma coeff_zero_X_mul (φ : mv_power_series σ R) (s : σ) : coeff R (0 : σ →₀ ℕ) (X s * φ) = 0 := begin have : ¬single s 1 ≤ 0, from λ h, by simpa using h s, simp only [X, coeff_monomial_mul, if_neg this] end variables (σ) (R) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ R) →+* R := { to_fun := coeff R (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], map_zero' := linear_map.map_zero _, .. coeff R (0 : σ →₀ ℕ) } variables {σ} {R} @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R (0 : σ →₀ ℕ)) = constant_coeff σ R := rfl lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ R) : coeff R (0 : σ →₀ ℕ) φ = constant_coeff σ R φ := rfl @[simp] lemma constant_coeff_C (a : R) : constant_coeff σ R (C σ R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ R).comp (C σ R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ R 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ R (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ R) (h : is_unit φ) : is_unit (constant_coeff σ R φ) := h.map (constant_coeff σ R).to_monoid_hom @[simp] lemma coeff_smul (f : mv_power_series σ R) (n) (a : R) : coeff _ n (a • f) = a * coeff _ n f := rfl lemma X_inj [nontrivial R] {s t : σ} : (X s : mv_power_series σ R) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff R (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end semiring section map variables {S T : Type*} [semiring R] [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ R →+* mv_power_series σ S := { to_fun := λ φ n, f $ coeff R n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff R n) 1) = (coeff S n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff R n) (φ + ψ)) = f ((coeff R n) φ) + f ((coeff R n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, f.map_sum, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id R) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ R) : coeff S n (map σ f φ) = f (coeff R n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ R) : constant_coeff σ S (map σ f φ) = f (constant_coeff σ R φ) := rfl @[simp] lemma map_monomial (n : σ →₀ ℕ) (a : R) : map σ f (monomial R n a) = monomial S n (f a) := by { ext m, simp [coeff_monomial, apply_ite f] } @[simp] lemma map_C (a : R) : map σ f (C σ R a) = C σ S (f a) := map_monomial _ _ _ @[simp] lemma map_X (s : σ) : map σ f (X s) = X s := by simp [X] end map section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] instance : algebra R (mv_power_series σ A) := { commutes' := λ a φ, by { ext n, simp [algebra.commutes] }, smul_def' := λ a σ, by { ext n, simp [(coeff A n).map_smul_of_tower a, algebra.smul_def] }, to_ring_hom := (mv_power_series.map σ (algebra_map R A)).comp (C σ R), .. mv_power_series.module } theorem C_eq_algebra_map : C σ R = (algebra_map R (mv_power_series σ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (mv_power_series σ A) r = C σ A (algebra_map R A r) := begin change (mv_power_series.map σ (algebra_map R A)).comp (C σ R) r = _, simp, end instance [nonempty σ] [nontrivial R] : nontrivial (subalgebra R (mv_power_series σ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], inhabit σ, refine ⟨X (default σ), _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, not_forall], refine ⟨finsupp.single (default σ) 1, _⟩, simp [algebra_map_apply, coeff_C], end⟩⟩ end algebra section trunc variables [comm_semiring R] (n : σ →₀ ℕ) /-- Auxiliary definition for the truncation function. -/ def trunc_fun (φ : mv_power_series σ R) : mv_polynomial σ R := ∑ m in Iic_finset n, mv_polynomial.monomial m (coeff R m φ) lemma coeff_trunc_fun (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc_fun n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc_fun, mv_polynomial.coeff_sum] variable (R) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ R →+ mv_polynomial σ R := { to_fun := trunc_fun n, map_zero' := by { ext, simp [coeff_trunc_fun] }, map_add' := by { intros, ext, simp [coeff_trunc_fun, ite_add], split_ifs; refl } } variable {R} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ R) : (trunc R n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc, coeff_trunc_fun] @[simp] lemma trunc_one : trunc R n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, simp }, { symmetry, rw mv_polynomial.coeff_one, exact if_neg (ne.symm H'), }, { symmetry, rw mv_polynomial.coeff_one, refine if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : R) : trunc R n (C σ R a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring R] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff R m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff R (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff R m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.tsub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext, rw [coe_add, coe_add, pi.add_apply, pi.add_apply, add_sub_cancel_left, add_comm], }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ R} : (X s : mv_power_series σ R) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff R m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ R), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring R] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : R) (φ : mv_power_series σ R) : mv_power_series σ R | n := if n = 0 then a else - a * ∑ x in n.antidiagonal, if h : x.2 < n then coeff R x.1 φ * inv.aux x.2 else 0 using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux [decidable_eq σ] (n : σ →₀ ℕ) (a : R) (φ : mv_power_series σ R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := show inv.aux a φ n = _, begin rw inv.aux, convert rfl -- unify `decidable` instances end /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ R) (u : units R) : mv_power_series σ R := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ R) (u : units R) : constant_coeff σ R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ R) (u : units R) (h : constant_coeff σ R φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal, { rw [finsupp.mem_antidiagonal, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring R] /-- Multivariate formal power series over a local ring form a local ring. -/ instance is_local_ring [local_ring R] : local_ring (mv_power_series σ R) := { is_local := by { intro φ, rcases local_ring.is_local (constant_coeff σ R φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h.symm } } } -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] -- Thanks to the linter for informing us that this instance does -- not actually need R and S to be local rings! /-- The map `A[[X]] → B[[X]]` induced by a local ring hom `A → B` is local -/ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ S) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ S ↑ψ) := @is_unit_constant_coeff σ S _ (↑ψ) ψ.is_unit, rw h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc.symm) end⟩ variables [local_ring R] [local_ring S] instance : local_ring (mv_power_series σ R) := { is_local := local_ring.is_local } end local_ring section field variables {k : Type*} [field k] /-- The inverse `1/f` of a multivariable power series `f` over a field -/ protected def inv (φ : mv_power_series σ k) : mv_power_series σ k := inv.aux (constant_coeff σ k φ)⁻¹ φ instance : has_inv (mv_power_series σ k) := ⟨mv_power_series.inv⟩ lemma coeff_inv [decidable_eq σ] (n : σ →₀ ℕ) (φ : mv_power_series σ k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff σ k φ)⁻¹ else - (constant_coeff σ k φ)⁻¹ * ∑ x in n.antidiagonal, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ k) : constant_coeff σ k (φ⁻¹) = (constant_coeff σ k φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ k} : φ⁻¹ = 0 ↔ constant_coeff σ k φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ k) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ k) (u : units k) (h : constant_coeff σ k φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ k) (h : constant_coeff σ k φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] protected lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : mv_power_series σ k} (h : constant_coeff σ k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := ⟨λ k, by simp [k, mul_assoc, mv_power_series.inv_mul _ h], λ k, by simp [← k, mul_assoc, mv_power_series.mul_inv _ h]⟩ protected lemma eq_inv_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := by rw [← mv_power_series.eq_mul_inv_iff_mul_eq h, one_mul] protected lemma inv_eq_iff_mul_eq_one {φ ψ : mv_power_series σ k} (h : constant_coeff σ k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := by rw [eq_comm, mv_power_series.eq_inv_iff_mul_eq_one h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ R) (mv_power_series σ R) := ⟨λ φ n, coeff n φ⟩ @[simp, norm_cast] lemma coeff_coe (φ : mv_polynomial σ R) (n : σ →₀ ℕ) : mv_power_series.coeff R n ↑φ = coeff n φ := rfl @[simp, norm_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : R) : (monomial n a : mv_power_series σ R) = mv_power_series.monomial R n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, norm_cast] lemma coe_zero : ((0 : mv_polynomial σ R) : mv_power_series σ R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : mv_polynomial σ R) : mv_power_series σ R) = 1 := coe_monomial _ _ @[simp, norm_cast] lemma coe_add (φ ψ : mv_polynomial σ R) : ((φ + ψ : mv_polynomial σ R) : mv_power_series σ R) = φ + ψ := rfl @[simp, norm_cast] lemma coe_mul (φ ψ : mv_polynomial σ R) : ((φ * ψ : mv_polynomial σ R) : mv_power_series σ R) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.C σ R a := coe_monomial _ _ @[simp, norm_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ R) : mv_power_series σ R) = mv_power_series.X s := coe_monomial _ _ /-- The coercion from multivariable polynomials to multivariable power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_mv_power_series.ring_hom : mv_polynomial σ R →+* mv_power_series σ R := { to_fun := (coe : mv_polynomial σ R → mv_power_series σ R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end mv_polynomial /-- Formal power series over the coefficient ring `R`.-/ def power_series (R : Type*) := mv_power_series unit R namespace power_series open finsupp (single) variable {R : Type*} section local attribute [reducible] power_series instance [inhabited R] : inhabited (power_series R) := by apply_instance instance [add_monoid R] : add_monoid (power_series R) := by apply_instance instance [add_group R] : add_group (power_series R) := by apply_instance instance [add_comm_monoid R] : add_comm_monoid (power_series R) := by apply_instance instance [add_comm_group R] : add_comm_group (power_series R) := by apply_instance instance [semiring R] : semiring (power_series R) := by apply_instance instance [comm_semiring R] : comm_semiring (power_series R) := by apply_instance instance [ring R] : ring (power_series R) := by apply_instance instance [comm_ring R] : comm_ring (power_series R) := by apply_instance instance [nontrivial R] : nontrivial (power_series R) := by apply_instance instance {A} [semiring R] [add_comm_monoid A] [module R A] : module R (power_series A) := by apply_instance instance {A S} [semiring R] [semiring S] [add_comm_monoid A] [module R A] [module S A] [has_scalar R S] [is_scalar_tower R S A] : is_scalar_tower R S (power_series A) := pi.is_scalar_tower instance {A} [semiring A] [comm_semiring R] [algebra R A] : algebra R (power_series A) := by apply_instance end section semiring variables (R) [semiring R] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series R →ₗ[R] R := mv_power_series.coeff R (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : R →ₗ[R] power_series R := mv_power_series.monomial R (single () n) variables {R} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff R n = mv_power_series.coeff R s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series R} (h : ∀ n, coeff R n φ = coeff R n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series R} : φ = ψ ↔ (∀ n, coeff R n φ = coeff R n ψ) := ⟨λ h n, congr_arg (coeff R n) h, ext⟩ /-- Constructor for formal power series.-/ def mk {R} (f : ℕ → R) : power_series R := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → R) : coeff R n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : R) : coeff R m (monomial R n a) = if m = n then a else 0 := calc coeff R m (monomial R n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : R) : monomial R n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial_same (n : ℕ) (a : R) : coeff R n (monomial R n a) = a := mv_power_series.coeff_monomial_same _ _ @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff R n).comp (monomial R n) = linear_map.id := linear_map.ext $ coeff_monomial_same n variable (R) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series R →+* R := mv_power_series.constant_coeff unit R /-- The constant formal power series.-/ def C : R →+* power_series R := mv_power_series.C unit R variable {R} /-- The variable of the formal power series ring.-/ def X : power_series R := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : ⇑(coeff R 0) = constant_coeff R := by { rw [coeff, finsupp.single_zero], refl } lemma coeff_zero_eq_constant_coeff_apply (φ : power_series R) : coeff R 0 φ = constant_coeff R φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : ⇑(monomial R 0) = C R := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] lemma monomial_zero_eq_C_apply (a : R) : monomial R 0 a = C R a := by simp lemma coeff_C (n : ℕ) (a : R) : coeff R n (C R a : power_series R) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : R) : coeff R 0 (C R a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial_same 0 a] lemma X_eq : (X : power_series R) = monomial R 1 1 := rfl lemma coeff_X (n : ℕ) : coeff R n (X : power_series R) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff R 0 (X : power_series R) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff R 1 (X : power_series R) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series R)^n = monomial R n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff R m ((X : power_series R)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff R n ((X : power_series R)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff R n (1 : power_series R) = if n = 0 then 1 else 0 := coeff_C n 1 lemma coeff_zero_one : coeff R 0 (1 : power_series R) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series R) : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, coeff R p.1 φ * coeff R p.2 ψ := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series R) (a : R) : coeff R n (φ * C R a) = coeff R n φ * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_C_mul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (C R a * φ) = a * coeff R n φ := mv_power_series.coeff_C_mul _ φ a @[simp] lemma coeff_smul (n : ℕ) (φ : power_series R) (a : R) : coeff R n (a • φ) = a * coeff R n φ := rfl @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series R) : coeff R (n+1) (φ * X) = coeff R n φ := begin simp only [coeff, finsupp.single_add], convert φ.coeff_add_mul_monomial (single () n) (single () 1) _, rw mul_one end @[simp] lemma coeff_succ_X_mul (n : ℕ) (φ : power_series R) : coeff R (n + 1) (X * φ) = coeff R n φ := begin simp only [coeff, finsupp.single_add, add_comm n 1], convert φ.coeff_add_monomial_mul (single () 1) (single () n) _, rw one_mul, end @[simp] lemma constant_coeff_C (a : R) : constant_coeff R (C R a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff R).comp (C R) = ring_hom.id R := rfl @[simp] lemma constant_coeff_zero : constant_coeff R 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff R 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff R X = 0 := mv_power_series.coeff_zero_X _ lemma coeff_zero_mul_X (φ : power_series R) : coeff R 0 (φ * X) = 0 := by simp lemma coeff_zero_X_mul (φ : power_series R) : coeff R 0 (X * φ) = 0 := by simp /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series R) (h : is_unit φ) : is_unit (constant_coeff R φ) := mv_power_series.is_unit_constant_coeff φ h /-- Split off the constant coefficient. -/ lemma eq_shift_mul_X_add_const (φ : power_series R) : φ = mk (λ p, coeff R (p + 1) φ) * X + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, mul_zero, ring_hom.map_mul], }, { simp only [coeff_succ_mul_X, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end /-- Split off the constant coefficient. -/ lemma eq_X_mul_shift_add_const (φ : power_series R) : φ = X * mk (λ p, coeff R (p + 1) φ) + C R (constant_coeff R φ) := begin ext (_ | n), { simp only [ring_hom.map_add, constant_coeff_C, constant_coeff_X, coeff_zero_eq_constant_coeff, zero_add, zero_mul, ring_hom.map_mul], }, { simp only [coeff_succ_X_mul, coeff_mk, linear_map.map_add, coeff_C, n.succ_ne_zero, sub_zero, if_false, add_zero], } end section map variables {S : Type*} {T : Type*} [semiring S] [semiring T] variables (f : R →+* S) (g : S →+* T) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series R →+* power_series S := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id R) : power_series R → power_series R) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series R) : coeff S n (map f φ) = f (coeff R n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring R] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series R} : (X : power_series R)^n ∣ φ ↔ ∀ m, m < n → coeff R m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit R _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series R} : (X : power_series R) ∣ φ ↔ constant_coeff R φ = 0 := begin rw [← pow_one (X : power_series R), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end open finset nat /-- The ring homomorphism taking a power series `f(X)` to `f(aX)`. -/ noncomputable def rescale (a : R) : power_series R →+* power_series R := { to_fun := λ f, power_series.mk $ λ n, a^n * (power_series.coeff R n f), map_zero' := by { ext, simp only [linear_map.map_zero, power_series.coeff_mk, mul_zero], }, map_one' := by { ext1, simp only [mul_boole, power_series.coeff_mk, power_series.coeff_one], split_ifs, { rw [h, pow_zero], }, refl, }, map_add' := by { intros, ext, exact mul_add _ _ _, }, map_mul' := λ f g, by { ext, rw [power_series.coeff_mul, power_series.coeff_mk, power_series.coeff_mul, finset.mul_sum], apply sum_congr rfl, simp only [coeff_mk, prod.forall, nat.mem_antidiagonal], intros b c H, rw [←H, pow_add, mul_mul_mul_comm] }, } @[simp] lemma coeff_rescale (f : power_series R) (a : R) (n : ℕ) : coeff R n (rescale a f) = a^n * coeff R n f := coeff_mk n _ @[simp] lemma rescale_zero : rescale 0 = (C R).comp (constant_coeff R) := begin ext, simp only [function.comp_app, ring_hom.coe_comp, rescale, ring_hom.coe_mk, power_series.coeff_mk _ _, coeff_C], split_ifs, { simp only [h, one_mul, coeff_zero_eq_constant_coeff, pow_zero], }, { rw [zero_pow' n h, zero_mul], }, end lemma rescale_zero_apply : rescale 0 X = C R (constant_coeff R X) := by simp @[simp] lemma rescale_one : rescale 1 = ring_hom.id (power_series R) := by { ext, simp only [ring_hom.id_apply, rescale, one_pow, coeff_mk, one_mul, ring_hom.coe_mk], } section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series R) : polynomial R := ∑ m in Ico 0 (n + 1), polynomial.monomial m (coeff R m φ) lemma coeff_trunc (m) (n) (φ : power_series R) : (trunc n φ).coeff m = if m ≤ n then coeff R m φ else 0 := by simp [trunc, polynomial.coeff_sum, polynomial.coeff_monomial, nat.lt_succ_iff] @[simp] lemma trunc_zero (n) : trunc n (0 : power_series R) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, linear_map.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series R) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : R) : trunc n (C R a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series R) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring R] /-- Auxiliary function used for computing inverse of a power series -/ protected def inv.aux : R → power_series R → power_series R := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : R) (φ : power_series R) : coeff R n (inv.aux a φ) = if n = 0 then a else - a * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv.aux a φ) else 0 := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series R) (u : units R) : power_series R := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series R) (u : units R) : coeff R n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff R x.1 φ * coeff R x.2 (inv_of_unit φ u) else 0 := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series R) (u : units R) : constant_coeff R (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series R) (u : units R) (h : constant_coeff R φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h /-- Two ways of removing the constant coefficient of a power series are the same. -/ lemma sub_const_eq_shift_mul_X (φ : power_series R) : φ - C R (constant_coeff R φ) = power_series.mk (λ p, coeff R (p + 1) φ) * X := sub_eq_iff_eq_add.mpr (eq_shift_mul_X_add_const φ) lemma sub_const_eq_X_mul_shift (φ : power_series R) : φ - C R (constant_coeff R φ) = X * power_series.mk (λ p, coeff R (p + 1) φ) := sub_eq_iff_eq_add.mpr (eq_X_mul_shift_add_const φ) end ring section comm_ring variables {A : Type*} [comm_ring A] @[simp] lemma rescale_neg_one_X : rescale (-1 : A) X = -X := begin ext, simp only [linear_map.map_neg, coeff_rescale, coeff_X], split_ifs with h; simp [h] end /-- The ring homomorphism taking a power series `f(X)` to `f(-X)`. -/ noncomputable def eval_neg_hom : power_series A →+* power_series A := rescale (-1 : A) @[simp] lemma eval_neg_hom_X : eval_neg_hom (X : power_series A) = -X := rescale_neg_one_X end comm_ring section integral_domain variables [comm_ring R] [integral_domain R] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series R) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw or_iff_not_imp_left, intro H, have ex : ∃ m, coeff R m φ ≠ 0, { contrapose! H, exact ext H }, let m := nat.find ex, have hm₁ : coeff R m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff R k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff R n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff R (m + n)) h, rw [linear_map.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_right_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series R) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nontrivial, .. power_series.comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series R))).is_prime := begin suffices : ideal.span ({X} : set (power_series R)) = (constant_coeff R).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series R) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff R 1) h } end lemma rescale_injective {a : R} (ha : a ≠ 0) : function.injective (rescale a) := begin intros p q h, rw power_series.ext_iff at *, intros n, specialize h n, rw [coeff_rescale, coeff_rescale, mul_eq_mul_left_iff] at h, apply h.resolve_right, intro h', exact ha (pow_eq_zero h'), end end integral_domain section local_ring variables {S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) [is_local_ring_hom f] instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f variables [local_ring R] [local_ring S] instance : local_ring (power_series R) := mv_power_series.local_ring end local_ring section algebra variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] theorem C_eq_algebra_map {r : R} : C R r = (algebra_map R (power_series R)) r := rfl theorem algebra_map_apply {r : R} : algebra_map R (power_series A) r = C A (algebra_map R A r) := mv_power_series.algebra_map_apply instance [nontrivial R] : nontrivial (subalgebra R (power_series R)) := mv_power_series.subalgebra.nontrivial end algebra section field variables {k : Type*} [field k] /-- The inverse 1/f of a power series f defined over a field -/ protected def inv : power_series k → power_series k := mv_power_series.inv instance : has_inv (power_series k) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series k) : φ⁻¹ = inv.aux (constant_coeff k φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series k) : coeff k n (φ⁻¹) = if n = 0 then (constant_coeff k φ)⁻¹ else - (constant_coeff k φ)⁻¹ * ∑ x in finset.nat.antidiagonal n, if x.2 < n then coeff k x.1 φ * coeff k x.2 (φ⁻¹) else 0 := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff k φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series k) : constant_coeff k (φ⁻¹) = (constant_coeff k φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series k} : φ⁻¹ = 0 ↔ constant_coeff k φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series k) (h : constant_coeff k φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series k) (u : units k) (h : constant_coeff k φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series k) (h : constant_coeff k φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h lemma eq_mul_inv_iff_mul_eq {φ₁ φ₂ φ₃ : power_series k} (h : constant_coeff k φ₃ ≠ 0) : φ₁ = φ₂ * φ₃⁻¹ ↔ φ₁ * φ₃ = φ₂ := mv_power_series.eq_mul_inv_iff_mul_eq h lemma eq_inv_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : φ = ψ⁻¹ ↔ φ * ψ = 1 := mv_power_series.eq_inv_iff_mul_eq_one h lemma inv_eq_iff_mul_eq_one {φ ψ : power_series k} (h : constant_coeff k ψ ≠ 0) : ψ⁻¹ = φ ↔ φ * ψ = 1 := mv_power_series.inv_eq_iff_mul_eq_one h end field end power_series namespace power_series variable {R : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring R] /-- The order of a formal power series `φ` is the greatest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series R) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series R) (h : ∃ n, coeff R n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, dsimp only, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series R) (h : (order φ).dom) : coeff R (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series R) (n : ℕ) (h : coeff R n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series R) (n : ℕ) (h: ↑n < order φ) : coeff R n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series R) = ⊤ := multiplicity.zero _ /-- The `0` power series is the unique power series with infinite order.-/ @[simp] lemma order_eq_top {φ : power_series R} : φ.order = ⊤ ↔ φ = 0 := begin split, { intro h, ext n, rw [(coeff R n).map_zero, coeff_of_lt_order], simp [h] }, { rintros rfl, exact order_zero } end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma nat_le_order (φ : power_series R) (n : ℕ) (h : ∀ i < n, coeff R i φ = 0) : ↑n ≤ order φ := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_coe H.le, rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma le_order (φ : power_series R) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff R i φ = 0) : n ≤ order φ := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply nat_le_order, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series R} {n : ℕ} : order φ = n ↔ (coeff R n φ ≠ 0) ∧ (∀ i, i < n → coeff R i φ = 0) := begin simp only [eq_coe_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series R} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff R i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff R i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma le_order_add (φ ψ : power_series R) : min (order φ) (order ψ) ≤ order (φ + ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series R) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series R) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (le_order_add _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series R) : order φ + order ψ ≤ order (φ * ψ) := begin apply le_order, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add hi hj), rw [← nat.cast_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : R) [decidable (a = 0)] : order (monomial R n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, linear_map.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial_same] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : R) (h : a ≠ 0) : order (monomial R n a) = n := by rw [order_monomial, if_neg h] /-- If `n` is strictly smaller than the order of `ψ`, then the `n`th coefficient of its product with any other power series is `0`. -/ lemma coeff_mul_of_lt_order {φ ψ : power_series R} {n : ℕ} (h : ↑n < ψ.order) : coeff R n (φ * ψ) = 0 := begin suffices : coeff R n (φ * ψ) = ∑ p in finset.nat.antidiagonal n, 0, rw [this, finset.sum_const_zero], rw [coeff_mul], apply finset.sum_congr rfl (λ x hx, _), refine mul_eq_zero_of_right (coeff R x.fst φ) (ψ.coeff_of_lt_order x.snd (lt_of_le_of_lt _ h)), rw finset.nat.mem_antidiagonal at hx, norm_cast, linarith, end lemma coeff_mul_one_sub_of_lt_order {R : Type*} [comm_ring R] {φ ψ : power_series R} (n : ℕ) (h : ↑n < ψ.order) : coeff R n (φ * (1 - ψ)) = coeff R n φ := by simp [coeff_mul_of_lt_order h, mul_sub] lemma coeff_mul_prod_one_sub_of_lt_order {R ι : Type*} [comm_ring R] (k : ℕ) (s : finset ι) (φ : power_series R) (f : ι → power_series R) : (∀ i ∈ s, ↑k < (f i).order) → coeff R k (φ * ∏ i in s, (1 - f i)) = coeff R k φ := begin apply finset.induction_on s, { simp }, { intros a s ha ih t, simp only [finset.mem_insert, forall_eq_or_imp] at t, rw [finset.prod_insert ha, ← mul_assoc, mul_right_comm, coeff_mul_one_sub_of_lt_order _ t.1], exact ih t.2 }, end end order_basic section order_zero_ne_one variables [comm_semiring R] [nontrivial R] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series R) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:R) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series R) = 1 := by simpa only [nat.cast_one] using order_monomial_of_ne_zero 1 (1:R) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series R)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [comm_ring R] [integral_domain R] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series R) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {R : Type*} [comm_semiring R] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial R) (power_series R) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, norm_cast] lemma coeff_coe (φ : polynomial R) (n) : power_series.coeff R n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, norm_cast] lemma coe_monomial (n : ℕ) (a : R) : (monomial n a : power_series R) = power_series.monomial R n a := by { ext, simp [coeff_coe, power_series.coeff_monomial, polynomial.coeff_monomial, eq_comm] } @[simp, norm_cast] lemma coe_zero : ((0 : polynomial R) : power_series R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : polynomial R) : power_series R) = 1 := begin have := coe_monomial 0 (1:R), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_add (φ ψ : polynomial R) : ((φ + ψ : polynomial R) : power_series R) = φ + ψ := by { ext, simp } @[simp, norm_cast] lemma coe_mul (φ ψ : polynomial R) : ((φ * ψ : polynomial R) : power_series R) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, norm_cast] lemma coe_C (a : R) : ((C a : polynomial R) : power_series R) = power_series.C R a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, norm_cast] lemma coe_X : ((X : polynomial R) : power_series R) = power_series.X := coe_monomial _ _ /-- The coercion from polynomials to power series as a ring homomorphism. -/ -- TODO as an algebra homomorphism? def coe_to_power_series.ring_hom : polynomial R →+* power_series R := { to_fun := (coe : polynomial R → power_series R), map_zero' := coe_zero, map_one' := coe_one, map_add' := coe_add, map_mul' := coe_mul } end polynomial
f15964848aec4aed130b0be11ef488957ebd6b73
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/multiset/bind.lean
3006a479e92ac66be68e0d775ad348c21e0e0412
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,439
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 algebra.big_operators.multiset.basic /-! # Bind operation for multisets This file defines a few basic operations on `multiset`, notably the monadic bind. ## Main declarations * `multiset.join`: The join, aka union or sum, of multisets. * `multiset.bind`: The bind of a multiset-indexed family of multisets. * `multiset.product`: Cartesian product of two multisets. * `multiset.sigma`: Disjoint sum of multisets in a sigma type. -/ variables {α β γ δ : Type*} namespace multiset /-! ### Join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum lemma coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] lemma join_zero : @join α 0 = 0 := rfl @[simp] lemma join_cons (s S) : @join α (s ::ₘ S) = s + join S := sum_cons _ _ @[simp] lemma join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] lemma singleton_join (a) : join ({a} : multiset (multiset α)) = a := sum_singleton _ @[simp] lemma mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] lemma card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) lemma rel_join {r : α → β → Prop} {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end /-! ### Bind -/ section bind variables (a : α) (s t : multiset α) (f g : α → multiset β) /-- `s.bind f` is the monad bind operation, defined as `(s.map f).join`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := (s.map f).join @[simp] lemma coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ←coe_join, list.map_map]; refl @[simp] lemma zero_bind : bind 0 f = 0 := rfl @[simp] lemma cons_bind : (a ::ₘ s).bind f = f a + s.bind f := by simp [bind] @[simp] lemma singleton_bind : bind {a} f = f a := by simp [bind] @[simp] lemma add_bind : (s + t).bind f = s.bind f + t.bind f := by simp [bind] @[simp] lemma bind_zero : s.bind (λ a, 0 : α → multiset β) = 0 := by simp [bind, join, nsmul_zero] @[simp] lemma bind_add : s.bind (λ a, f a + g a) = s.bind f + s.bind g := by simp [bind, join] @[simp] lemma bind_cons (f : α → β) (g : α → multiset β) : s.bind (λ a, f a ::ₘ g a) = map f s + s.bind g := multiset.induction_on s (by simp) (by simp [add_comm, add_left_comm] {contextual := tt}) @[simp] lemma bind_singleton (f : α → β) : s.bind (λ x, ({f x} : multiset β)) = map f s := multiset.induction_on s (by rw [zero_bind, map_zero]) (by simp [singleton_add]) @[simp] lemma mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] lemma card_bind : (s.bind f).card = (s.map (card ∘ f)).sum := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀ a ∈ m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a ∈ m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λ a, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λ a, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λ a, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λ a, bind n $ λ b, f a b) = (bind n $ λ b, bind m $ λ a, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λ a, n.map $ λ b, f a b) = (bind n $ λ b, m.map $ λ a, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : (s.bind t).prod = (s.map $ λ a, (t a).prod).prod := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) lemma rel_bind {r : α → β → Prop} {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by { apply rel_join, rw rel_map, exact hst.mono (λ a ha b hb hr, h hr) } lemma count_sum [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} : count a (map f m).sum = sum (m.map $ λ b, count a $ f b) := multiset.induction_on m (by simp) ( by simp) lemma count_bind [decidable_eq α] {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λ b, count a $ f b) := count_sum lemma le_bind {α β : Type*} {f : α → multiset β} (S : multiset α) {x : α} (hx : x ∈ S) : f x ≤ S.bind f := begin classical, rw le_iff_count, intro a, rw count_bind, apply le_sum_of_mem, rw mem_map, exact ⟨x, hx, rfl⟩ end @[simp] theorem attach_bind_coe (s : multiset α) (f : α → multiset β) : s.attach.bind (λ i, f i) = s.bind f := congr_arg join $ attach_map_coe' _ _ end bind /-! ### Product of two multisets -/ section product variables (a : α) (b : β) (s : multiset α) (t : multiset β) /-- The multiplicity of `(a, b)` in `s ×ˢ t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := multiset.product) ` ×ˢ `:82 := multiset.product @[simp] lemma coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by { rw [product, list.product, ←coe_bind], simp } @[simp] lemma zero_product : @product α β 0 t = 0 := rfl --TODO: Add `product_zero` @[simp] lemma cons_product : (a ::ₘ s) ×ˢ t = map (prod.mk a) t + s ×ˢ t := by simp [product] @[simp] lemma product_singleton : ({a} : multiset α) ×ˢ ({b} : multiset β) = {(a, b)} := by simp only [product, bind_singleton, map_singleton] @[simp] lemma add_product (s t : multiset α) (u : multiset β) : (s + t) ×ˢ u = s ×ˢ u + t ×ˢ u := by simp [product] @[simp] lemma product_add (s : multiset α) : ∀ t u : multiset β, s ×ˢ (t + u) = s ×ˢ t + s ×ˢ u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp; cc @[simp] lemma mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] lemma card_product : (s ×ˢ t).card = s.card * t.card := by simp [product, repeat, (∘), mul_comm] end product /-! ### Disjoint sum of multisets -/ section sigma variables {σ : α → Type*} (a : α) (s : multiset α) (t : Π a, multiset (σ a)) /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] lemma coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ←coe_bind]; simp @[simp] lemma zero_sigma : @multiset.sigma α σ 0 t = 0 := rfl @[simp] lemma cons_sigma : (a ::ₘ s).sigma t = (t a).map (sigma.mk a) + s.sigma t := by simp [multiset.sigma] @[simp] lemma sigma_singleton (b : α → β) : ({a} : multiset α).sigma (λ a, ({b a} : multiset β)) = {⟨a, b a⟩} := rfl @[simp] lemma add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] lemma sigma_add : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp; cc @[simp] lemma mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] lemma card_sigma : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end sigma end multiset
5b447ae20d59517ffbd5c203930ca0427c50a399
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/aexp/type.lean
95f843795f986ffd3e0684595502b24afa1852a9
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
3,421
lean
/- This file contains the type `aexp` for the alpha-equivalent class of `exp`. -/ import aeq import logic.basic import data.category namespace acie ----------------------------------------------------------------- variables {V : Type} [decidable_eq V] -- Type of variable names variables {vs : Type → Type} [vset vs V] -- Type of variable name sets variables {X Y : vs V} -- Variable name sets -- The type of alpha-equivalent expressions. def aexp (X : vs V) : Type := quotient (aeq.id.setoid X) namespace aexp ----------------------------------------------------------------- @[reducible] protected def of_exp : exp X → aexp X := quotient.mk -- Not needed? @[reducible] protected def eq (α₁ : aexp X) (α₂ : aexp X) : Prop := quotient.lift_on₂ α₁ α₂ aeq.id $ λ e₁ e₂ e₃ e₄ e₁_aeq_e₃ e₂_aeq_e₄, propext $ iff.intro (λ e₁_aeq_e₂, aeq.id.trans (aeq.id.trans (aeq.id.symm e₁_aeq_e₃) e₁_aeq_e₂) e₂_aeq_e₄) (λ e₃_aeq_e₄, aeq.id.trans e₁_aeq_e₃ (aeq.id.trans e₃_aeq_e₄ (aeq.id.symm e₂_aeq_e₄))) instance decidable_eq : decidable_eq (aexp X) := by apply_instance -- An `aexp` substitution is a strict wrapper around an `exp` substitution. We -- use a structure to allow us to convert to and from as necessary. protected structure subst (X Y : vs V) : Type := mk :: (as_exp : exp.subst X Y) @[reducible] protected def subst.id (X : vs V) : aexp.subst X X := ⟨exp.subst.id X⟩ @[reducible] protected def subst.app : aexp.subst X Y → ν∈ X → aexp Y := λ F x, aexp.of_exp (F.as_exp x) instance has_comp : has_comp aexp.subst := { comp := λ (X Y Z : vs V) (G : aexp.subst Y Z) (F : aexp.subst X Y), ⟨exp.subst.apply G.as_exp ∘ F.as_exp⟩ } theorem eq_of_aeq (F : exp.subst X Y) (e₁ e₂ : exp X) : e₁ ≡α e₂ → (aexp.of_exp ∘ exp.subst.apply F) e₁ = (aexp.of_exp ∘ exp.subst.apply F) e₂ := quotient.sound ∘ aeq.subst_preservation.id₁ F theorem eq_of_aeq₂ (F : exp.subst X Y) (G : exp.subst X Y) (ext : aeq.extend F G (vrel.id X) (vrel.id Y)) (e₁ e₂ : exp X) : e₁ ≡α e₂ → (aexp.of_exp ∘ exp.subst.apply F) e₁ = (aexp.of_exp ∘ exp.subst.apply G) e₂ := quotient.sound ∘ aeq.subst_preservation.id F G ext @[reducible] protected def subst.apply : aexp.subst X Y → aexp X → aexp Y | ⟨F⟩ := quotient.lift (aexp.of_exp ∘ exp.subst.apply F) (eq_of_aeq F) @[reducible] protected def subst.eq (F : aexp.subst X Y) (G : aexp.subst X Y) : Prop := subst.app F = subst.app G -- Reflexive protected theorem subst.refl : reflexive (@subst.eq _ _ _ _ X Y) := by simp [reflexive, subst.eq] -- Symmetric protected theorem subst.symm : symmetric (@subst.eq _ _ _ _ X Y) := by simp [symmetric, subst.eq]; intros F G; exact eq.symm -- Transitive protected theorem subst.trans : transitive (@subst.eq _ _ _ _ X Y) := by simp [transitive, subst.eq]; intros F G H; exact eq.trans -- Equivalence protected theorem subst.equiv : equivalence (@subst.eq _ _ _ _ X Y) := mk_equivalence (@subst.eq _ _ _ _ X Y) subst.refl subst.symm subst.trans -- Setoid instance subst.setoid (X Y : vs V) : setoid (aexp.subst X Y) := setoid.mk (@subst.eq _ _ _ _ X Y) subst.equiv end /- namespace -/ aexp ------------------------------------------------------- end /- namespace -/ acie -------------------------------------------------------
0390caa0824f44eab00882cb09cc1f278ed9f276
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/toExpr.lean
e44c93603a42934eb4edb94b7db342ab611f29b2
[ "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
811
lean
import Lean open Lean unsafe def test {α : Type} [ToString α] [ToExpr α] [BEq α] (a : α) : CoreM Unit := do let env ← getEnv; let auxName := `_toExpr._test; let decl := Declaration.defnDecl { name := auxName, levelParams := [], value := toExpr a, type := toTypeExpr α, hints := ReducibilityHints.abbrev, safety := DefinitionSafety.safe }; IO.println (toExpr a); (match env.addAndCompile {} decl with | Except.error _ => throwError "addDecl failed" | Except.ok env => match env.evalConst α {} auxName with | Except.error ex => throwError ex | Except.ok b => do IO.println b; unless a == b do throwError "toExpr failed"; pure ()) #eval test #[(1, 2), (3, 4)] #eval test ['a', 'b', 'c'] #eval test ("hello", true) #eval test ((), 10)
fa1577a008d5a4103e0259d6963f2a0afe7cad7b
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/01_Equality/03_type_inference.lean
13517dad19f28789428d46d18287e75ba9e2e5c8
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
2,436
lean
/- Type Inference -/ /- Now as we've seen, given a value, t, of some type, T, Lean can tell us what T is. The #check command tells us the type of any value or expression. The key observation is that if you give Lean a value, Lean can determine its type. -/ #check 0 /- We can use the ability of Lean to determine the types of given values to make it easier to apply the eq.refl rule. If we give a value, t, as an argument, Lean can automatically figure out its type, T, which we means we shouldn't have to say explicitly what T is. EXERCISE: If t = 0, what is T? If t = tt, what is T? If t = "Hello Lean!" what is T? Lean supports what we call type inference to relieve us of having to give values for type parameters explicitly when they can be inferred from from the context. The context in this case is the value of t. We will thus rewrite the eq.refl inference rule to indicate that we mean for the value of the T parameter to be inferred. We'll do this by putting braces around this argument. Here's the rule as we defined it up until now. T: Type, t : T -------------- (eq.refl) pf: t = t Here's the rewritten rule. { T: Type }, t : T ------------------ (eq.refl) pf: t = t The new version, with curly braces around { T : Type }, means exactly the same thing, but the curly braces indicates that when we write expressions where eq.refl is applied to arguments, we can leave out the explicit argument, T, and let Lean infer it from the value for t. What this slightly modified rule provides is the ability to expressions in which eq.refl is applied to just one argument, namely a value, t. Rather than writing "eq.refl nat 0", for example, we'd write "eq.refl 0". A value for T is still required, but it is inferred from the context (that t = 0 so T is of type nat), and thus does not need to be given explicitly. -/ /- In Lean, the eq.refl rule is defined in just this way. It's even called eq.refl. It takes one value, t, infers T from it, and returns a proof that that t equals itself! Read the output of the following check command very carefully. It says that (eq.refl 0) is a a proof of, 0 = 0! When eq.refl is applied to the value 0, a proof of 0 = 0 is produced. -/ #check (eq.refl 0) /- EXERCISE: Use #check to confirm similar conclusions for the cases where t = tt and t = "Hello Lean!". EXERCISE: In the case where t = tt, what value does Lean infer for the parameter, T? -/
52a2982c0ef1ce2c4018e98f07aaf36c7af11321
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/ring_theory/subring.lean
83d2bae1345a0ed01e78e7f22a2e2fa60ee99521
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,200
lean
/- Copyright (c) 2020 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan -/ import group_theory.subgroup.basic import ring_theory.subsemiring /-! # Subrings Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type whose terms correspond to subrings of `R`. This is the preferred way to talk about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`) are not in this file, and they will ultimately be deprecated. We prove that subrings are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subring R`, sending a subset of `R` to the subring it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)` `(A : subring R) (B : subring S) (s : set R)` * `subring R` : the type of subrings of a ring `R`. * `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings. * `subring.center` : the center of a ring `R`. * `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set. * `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M` form a `galois_insertion`. * `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f` * `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`. * `prod A B : subring (R × S)` : the product of subrings * `f.range : subring B` : the range of the ring homomorphism `f`. * `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`, the subring of `R` where `f x = g x` ## Implementation notes A subring is implemented as a subsemiring which is also an additive subgroup. The initial PR was as a submonoid which is also an additive subgroup. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subring's underlying set. ## Tags subring, subrings -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T] set_option old_structure_cmd true /-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R /-- Reinterpret a `subring` as a `subsemiring`. -/ add_decl_doc subring.to_subsemiring /-- Reinterpret a `subring` as an `add_subgroup`. -/ add_decl_doc subring.to_add_subgroup namespace subring /-- The underlying submonoid of a subring. -/ def to_submonoid (s : subring R) : submonoid R := { carrier := s.carrier, ..s.to_subsemiring.to_submonoid } instance : set_like (subring R) R := ⟨subring.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : subring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp] lemma mem_mk {S : set R} {x : R} (h₁ h₂ h₃ h₄ h₅) : x ∈ (⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set R) (h₁ h₂ h₃ h₄ h₅) : ((⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) : set R) = S := rfl @[simp] lemma mk_le_mk {S S' : set R} (h₁ h₂ h₃ h₄ h₅ h₁' h₂' h₃' h₄' h₅') : (⟨S, h₁, h₂, h₃, h₄, h₅⟩ : subring R) ≤ (⟨S', h₁', h₂', h₃', h₄', h₅'⟩ : subring R) ↔ S ⊆ S' := iff.rfl /-- Two subrings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subring with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subring R) (s : set R) (hs : s = ↑S) : subring R := { carrier := s, neg_mem' := hs.symm ▸ S.neg_mem', ..S.to_subsemiring.copy s hs } lemma to_subsemiring_injective : function.injective (to_subsemiring : subring R → subsemiring R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_subsemiring_strict_mono : strict_mono (to_subsemiring : subring R → subsemiring R) := λ _ _, id @[mono] lemma to_subsemiring_mono : monotone (to_subsemiring : subring R → subsemiring R) := to_subsemiring_strict_mono.monotone lemma to_add_subgroup_injective : function.injective (to_add_subgroup : subring R → add_subgroup R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : subring R → add_subgroup R) := λ _ _, id @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : subring R → add_subgroup R) := to_add_subgroup_strict_mono.monotone lemma to_submonoid_injective : function.injective (to_submonoid : subring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subring R → submonoid R) := to_submonoid_strict_mono.monotone /-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R) (hm : ↑sm = s) (ha : ↑sa = s) : subring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem, neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) {x : R} : x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa =s) : (subring.mk' s sm sa hm ha).to_add_subgroup = sa := set_like.coe_injective ha.symm end subring /-- A `subsemiring` containing -1 is a `subring`. -/ def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R := { neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, } ..s.to_submonoid, ..s.to_add_submonoid } namespace subring variables (s : subring R) /-- A subring contains the ring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subring contains the ring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subring is closed under negation. -/ theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subring is closed under subtraction -/ theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) } /-- Product of a list of elements in a subring is in the subring. -/ lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subring is in the subring. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/ lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in an `subring` of a `ring` is in the `subring`. -/ lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the subring. -/ lemma prod_mem {R : Type*} [comm_ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subring` of a `ring` indexed by a `finset` is in the `subring`. -/ lemma sum_mem {R : Type*} [ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n • x ∈ s := s.to_add_subgroup.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : R) ∈ s := by simp only [← gsmul_one, gsmul_mem, one_mem] /-- A subring of a ring inherits a ring structure -/ instance to_ring : ring s := { right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl @[simp, norm_cast] lemma coe_pow (x : s) (n : ℕ) : (↑(x ^ n) : R) = x ^ n := s.to_submonoid.coe_pow x n @[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 := ⟨λ h, subtype.ext (trans h s.coe_zero.symm), λ h, h.symm ▸ s.coe_zero⟩ /-- A subring of a `comm_ring` is a `comm_ring`. -/ instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s} /-- A subring of a non-trivial ring is non-trivial. -/ instance {R} [ring R] [nontrivial R] (s : subring R) : nontrivial s := s.to_subsemiring.nontrivial /-- A subring of a ring with no zero divisors has no zero divisors. -/ instance {R} [ring R] [no_zero_divisors R] (s : subring R) : no_zero_divisors s := s.to_subsemiring.no_zero_divisors /-- A subring of an integral domain is an integral domain. -/ instance {R} [integral_domain R] (s : subring R) : integral_domain s := { .. s.nontrivial, .. s.no_zero_divisors, .. s.to_comm_ring } /-- A subring of an `ordered_ring` is an `ordered_ring`. -/ instance to_ordered_ring {R} [ordered_ring R] (s : subring R) : ordered_ring s := subtype.coe_injective.ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of an `ordered_comm_ring` is an `ordered_comm_ring`. -/ instance to_ordered_comm_ring {R} [ordered_comm_ring R] (s : subring R) : ordered_comm_ring s := subtype.coe_injective.ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_ring` is a `linear_ordered_ring`. -/ instance to_linear_ordered_ring {R} [linear_ordered_ring R] (s : subring R) : linear_ordered_ring s := subtype.coe_injective.linear_ordered_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subring of a `linear_ordered_comm_ring` is a `linear_ordered_comm_ring`. -/ instance to_linear_ordered_comm_ring {R} [linear_ordered_comm_ring R] (s : subring R) : linear_ordered_comm_ring s := subtype.coe_injective.linear_ordered_comm_ring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural ring hom from a subring of ring `R` to `R`. -/ def subtype (s : subring R) : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl @[simp, norm_cast] lemma coe_nat_cast (n : ℕ) : ((n : s) : R) = n := s.subtype.map_nat_cast n @[simp, norm_cast] lemma coe_int_cast (n : ℤ) : ((n : s) : R) = n := s.subtype.map_int_cast n /-! ## Partial order -/ @[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl /-! ## top -/ /-- The subring `R` of the ring `R`. -/ instance : has_top (subring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl /-! ## comap -/ /-- The preimage of a subring along a ring homomorphism is a subring. -/ def comap {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) : subring R := { carrier := f ⁻¹' s.carrier, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_subgroup.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! ## map -/ /-- The image of a subring along a ring homomorphism is a subring. -/ def map {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring R) : subring S := { carrier := f '' s.carrier, .. s.to_submonoid.map (f : R →* S), .. s.to_add_subgroup.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-! ## range -/ /-- The range of a ring homomorphism, as a subring of the target. See Note [range copy pattern]. -/ def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S := ((⊤ : subring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_range : (f.range : set S) = set.range f := rfl @[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl lemma range_eq_map (f : R →+* S) : f.range = subring.map f ⊤ := by { ext, simp } lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range := mem_range.mpr ⟨x, rfl⟩ lemma map_range : f.range.map g = (g.comp f).range := by simpa only [range_eq_map] using (⊤ : subring R).map_map g f -- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } /-- The range of a ring homomorphism is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`. -/ instance fintype_range [fintype R] [decidable_eq S] (f : R →+* S) : fintype (range f) := set.fintype_range f end ring_hom namespace subring /-! ## bot -/ instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩ instance : inhabited (subring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) := ring_hom.coe_range (int.cast_ring_hom R) lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x := ring_hom.mem_range /-! ## inf -/ /-- The inf of two subrings is their intersection. -/ instance : has_inf (subring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩ @[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subring R) := ⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subring R)) : ((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_subgroup (s : set (subring R)) : (Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _ /-- Subrings of a ring form a complete lattice. -/ instance : complete_lattice (subring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-! ## Center of a ring -/ section variables (R) /-- The center of a ring `R` is the set of elements that commute with everything in `R` -/ def center : subring R := { carrier := set.center R, neg_mem' := λ a, set.neg_mem_center, .. subsemiring.center R } lemma coe_center : ↑(center R) = set.center R := rfl @[simp] lemma center_to_subsemiring : (center R).to_subsemiring = subsemiring.center R := rfl variables {R} lemma mem_center_iff {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl @[simp] lemma center_eq_top (R) [comm_ring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance : comm_ring (center R) := { ..subsemiring.center.comm_semiring, ..(center R).to_ring} end section division_ring variables {K : Type u} [division_ring K] instance : field (center K) := { inv := λ a, ⟨a⁻¹, set.inv_mem_center₀ a.prop⟩, mul_inv_cancel := λ ⟨a, ha⟩ h, subtype.ext $ mul_inv_cancel $ subtype.coe_injective.ne h, div := λ a b, ⟨a / b, set.div_mem_center₀ a.prop b.prop⟩, div_eq_mul_inv := λ a b, subtype.ext $ div_eq_mul_inv _ _, inv_zero := subtype.ext inv_zero, ..(center K).nontrivial, ..center.comm_ring } @[simp] lemma center.coe_inv (a : center K) : ((a⁻¹ : center K) : K) = (a : K)⁻¹ := rfl @[simp] lemma center.coe_div (a b : center K) : ((a / b : center K) : K) = (a : K) / (b : K) := rfl end division_ring /-! ## subring closure of a subset -/ /-- The `subring` generated by a set. -/ def closure (s : set R) : subring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S := mem_Inf /-- The subring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx /-- A subring `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ (x : R), p x → p (-x)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) := ⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx ) (add_subgroup.zero_mem _) (add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) ) (λ x y hx hy, add_subgroup.add_mem _ hx hy ) (λ x hx, add_subgroup.neg_mem _ hx ) ( λ x y hx hy, add_subgroup.closure_induction hy (λ q hq, add_subgroup.closure_induction hx ( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) ) ( begin rw zero_mul q, apply add_subgroup.zero_mem _, end ) ( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end ) ( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) ) ( begin rw mul_zero x, apply add_subgroup.zero_mem _, end ) ( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end ) ( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ), λ h, add_subgroup.closure_induction h ( λ x hx, submonoid.closure_induction hx ( λ x hx, subset_closure hx ) ( one_mem _ ) ( λ x y hx hy, mul_mem _ hx hy ) ) ( zero_mem _ ) (λ x y hx hy, add_mem _ hx hy) ( λ x hx, neg_mem _ hx ) ⟩ theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) : (∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) := add_subgroup.closure_induction (mem_closure_iff.1 h) (λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h]; clear_aux_decl; tauto!⟩) ⟨[], by simp⟩ (λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t), by simp [hl2, hm2]⟩) (λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2 ⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp) (by simp [list.map_cons, add_comm] {contextual := tt})⟩) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subring `S` equals `S`. -/ lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subring.gi R).gc.l_Sup lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t` as a subring of `R × S`. -/ def prod (s : subring R) (t : subring S) : subring (R × S) := { carrier := (s : set R).prod t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup} @[norm_cast] lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = (s : set R).prod (t : set S) := rfl lemma mem_prod {s : subring R} {t : subring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subring R) : s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subring S) : (⊤ : subring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subrings is isomorphic to their product as rings. -/ def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } /-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings. Note that this fails without the directedness assumption (the union of two subrings is typically not a subring) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subring R := subring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) : ((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] lemma mem_map_equiv {f : R ≃+* S} {K : subring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subring namespace ring_hom variables [ring T] {s : subring R} open subring /-- Restriction of a ring homomorphism to a subring of the domain. -/ def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype @[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def range_restrict (f : R →+* S) : R →+* f.range := f.cod_restrict' f.range $ λ x, ⟨x, rfl⟩ @[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩ lemma range_top_iff_surjective {f : R →+* S} : f.range = (⊤ : subring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.range = (⊤ : subring S) := range_top_iff_surjective.2 hf /-- The subring of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subring of R -/ def eq_locus (f g : R →+* S) : subring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/ lemma eq_on_set_closure {f g : R →+* S} {s : set R} (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 lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subring generated by a set equals the subring generated by the image of the set. -/ lemma map_closure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subring open ring_hom /-- The ring homomorphism associated to an inclusion of subrings. -/ def inclusion {S T : subring R} (h : S ≤ T) : S →* T := S.subtype.cod_restrict' _ (λ x, h x.2) @[simp] lemma range_subtype (s : subring R) : s.subtype.range = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subring namespace ring_equiv variables {s t : subring R} /-- Makes the identity isomorphism from a proof two subrings of a multiplicative monoid are equal. -/ def subring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.range`. -/ def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.range := { to_fun := λ x, f.range_restrict x, inv_fun := λ x, (g ∘ f.range.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end ring_equiv namespace subring variables {s : set R} local attribute [reducible] closure @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx end subring lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) : (k : R) * g ∈ G := by { convert add_subgroup.gsmul_mem G h k, simp } /-! ## Actions by `subring`s These are just copies of the definitions about `subsemiring` starting from `subsemiring.mul_action`. When `R` is commutative, `algebra.of_subring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subring variables {α β : Type*} /-- The action by a subring is the action by the underlying ring. -/ instance [mul_action R α] (S : subring R) : mul_action S α := S.to_subsemiring.mul_action lemma smul_def [mul_action R α] {S : subring R} (g : S) (m : α) : g • m = (g : R) • m := rfl instance smul_comm_class_left [mul_action R β] [has_scalar α β] [smul_comm_class R α β] (S : subring R) : smul_comm_class S α β := S.to_subsemiring.smul_comm_class_left instance smul_comm_class_right [has_scalar α β] [mul_action R β] [smul_comm_class α R β] (S : subring R) : smul_comm_class α S β := S.to_subsemiring.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [mul_action R α] [mul_action R β] [is_scalar_tower R α β] (S : subring R) : is_scalar_tower S α β := S.to_subsemiring.is_scalar_tower instance [mul_action R α] [has_faithful_scalar R α] (S : subring R) : has_faithful_scalar S α := S.to_subsemiring.has_faithful_scalar /-- The action by a subring is the action by the underlying ring. -/ instance [add_monoid α] [distrib_mul_action R α] (S : subring R) : distrib_mul_action S α := S.to_subsemiring.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [monoid α] [mul_distrib_mul_action R α] (S : subring R) : mul_distrib_mul_action S α := S.to_subsemiring.mul_distrib_mul_action /-- The action by a subring is the action by the underlying ring. -/ instance [add_comm_monoid α] [module R α] (S : subring R) : module S α := S.to_subsemiring.module end subring end actions -- while this definition is not about subrings, this is the earliest we have -- both ordered ring structures and submonoids available /-- The subgroup of positive units of a linear ordered commutative ring. -/ def units.pos_subgroup (R : Type*) [linear_ordered_comm_ring R] [nontrivial R] : subgroup (units R) := { carrier := {x | (0 : R) < x}, inv_mem' := λ x (hx : (0 : R) < x), (zero_lt_mul_left hx).mp $ x.mul_inv.symm ▸ zero_lt_one, ..(pos_submonoid R).comap (units.coe_hom R)} @[simp] lemma units.mem_pos_subgroup {R : Type*} [linear_ordered_comm_ring R] [nontrivial R] (u : units R) : u ∈ units.pos_subgroup R ↔ (0 : R) < u := iff.rfl
a7fba92a41d351b618b41461395131c0dd8d5bba
9028d228ac200bbefe3a711342514dd4e4458bff
/src/order/filter/at_top_bot.lean
668efa8b089618d335aae1b78ce9974152b6f613
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,381
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.forall_nonempty_iff_ne_bot.1 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp only [filter.frequently, eventually_at_top, not_exists, not_forall, not_not] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := begin rw frequently_at_top, split ; intros h a, { cases no_top a with a' ha', rcases h a' with ⟨b, hb, hb'⟩, exact ⟨b, lt_of_lt_of_le ha' hb, hb'⟩ }, { rcases h a with ⟨b, hb, hb'⟩, exact ⟨b, le_of_lt hb, hb'⟩ }, end lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_set_of_eq] lemma tendsto_at_bot [preorder β] (m : α → β) (f : filter α) : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b ≤ u a' := begin intros a b, have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b < u a' := begin intros a b, cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin letI := classical.DLO β, intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' ((tendsto_at_top (λ (a : α), f a) l).mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf end ordered_group open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] (f : α → β) (l : filter β) : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := (tendsto_at_bot_at_bot f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_set_of_eq, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_neg_at_top_at_bot [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual α) _ /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.exists_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
cf1aa65e40c8ba0f69edbc05f6fdc2fb8e750db2
46125763b4dbf50619e8846a1371029346f4c3db
/src/algebra/associated.lean
ecf806f0b8ad41b74fcbc13802af6a3c521b9fee
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
25,485
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker -/ import algebra.group.is_unit data.multiset /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} open lattice theorem is_unit.mk0 [division_ring α] (x : α) (hx : x ≠ 0) : is_unit x := is_unit_unit (units.mk0 x hx) theorem is_unit_iff_ne_zero [division_ring α] {x : α} : is_unit x ↔ x ≠ 0 := ⟨λ ⟨u, hu⟩, hu.symm ▸ λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3, is_unit.mk0 x⟩ @[simp] theorem is_unit_zero_iff [semiring α] : is_unit (0 : α) ↔ (0:α) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, begin haveI := subsingleton_of_zero_eq_one _ h, refine ⟨⟨0, 0, _, _⟩, rfl⟩; apply subsingleton.elim end⟩ @[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α) := mt is_unit_zero_iff.1 zero_ne_one lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem mul_dvd_of_is_unit_left [comm_semiring α] {x y z : α} (h : is_unit x) : x * y ∣ z ↔ y ∣ z := ⟨dvd_trans (dvd_mul_left _ _), dvd_trans $ by simpa using mul_dvd_mul_right (is_unit_iff_dvd_one.1 h) y⟩ theorem mul_dvd_of_is_unit_right [comm_semiring α] {x y z : α} (h : is_unit y) : x * y ∣ z ↔ x ∣ z := by rw [mul_comm, mul_dvd_of_is_unit_left h] @[simp] lemma unit_mul_dvd_iff [comm_semiring α] {a b : α} {u : units α} : (u : α) * a ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_left (is_unit_unit _) lemma mul_unit_dvd_iff [comm_semiring α] {a b : α} {u : units α} : a * u ∣ b ↔ a ∣ b := units.coe_mul_dvd _ _ _ theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨λ ⟨u, hu⟩, (int.units_eq_one_or u).elim (by simp *) (by simp *), λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [integral_domain α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ x ≠ 0 ∧ ∃ d : α, ¬ is_unit d ∧ y = x * d := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, (domain.mul_left_inj hx0).1 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [integral_domain α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x * x ^ m ∣ 1 * x ^ m, { rw [← pow_succ, one_mul], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h }, rwa [mul_dvd_mul_iff_right, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end /-- prime element of a semiring -/ def prime [comm_semiring α] (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime lemma ne_zero [comm_semiring α] {p : α} (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit [comm_semiring α] {p : α} (hp : prime p) : ¬ is_unit p := hp.2.1 lemma div_or_div [comm_semiring α] {p : α} (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h end prime @[simp] lemma not_prime_zero [comm_semiring α] : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one [comm_semiring α] : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.div_or_div this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := hp.2 a b h end irreducible @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [semiring α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [integral_domain α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show a ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show b ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [integral_domain α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [domain.mul_left_inj hp0] at h⟩, (hp.div_or_div hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end lemma exists_associated_mem_of_dvd_prod [integral_domain α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.div_or_div hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_semiring α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ mul_unit_dvd_iff.symm lemma dvd_mul_unit_iff [comm_semiring α] {a b : α} {u : units α} : a ∣ b * u ↔ a ∣ b := units.dvd_coe_mul _ _ _ lemma dvd_iff_dvd_of_rel_right [comm_semiring α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ dvd_mul_unit_iff.symm lemma eq_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv.symm, hu.symm]⟩, hu ▸ by { simp [mul_unit_dvd_iff], intros a b, exact hp.div_or_div }⟩⟩ lemma prime_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv.symm]⟩)⟩ lemma irreducible_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [integral_domain α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), (domain.mul_left_inj ha).1 begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [integral_domain α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} instance : has_dvd (associates α) := ⟨(≤)⟩ @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ @[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 := by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero] @[simp] protected theorem zero_mul : ∀(a : associates α), 0 * a = 0 := by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul] theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated ... ↔ a = 0 : associated_zero_iff_eq_zero a theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b) lemma prime.ne_zero {p : associates α} (hp : prime p) : p ≠ 0 := hp.1 lemma prime.ne_one {p : associates α} (hp : prime p) : p ≠ 1 := hp.2.1 lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match hp.le_or_le this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [associates.prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_zero_eq] }, apply and_congr, { rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff] end end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : lattice.order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : lattice.order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } theorem zero_ne_one : (0 : associates α) ≠ 1 := assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl)) (by simp [or_imp_distrib] {contextual := tt}) theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr iff.rfl, split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt (mk_zero_eq a).2 ha) hu⟩ end lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (le_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from lattice.bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ lattice.bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end end integral_domain end associates
e211cd65d71ca9435cbb077c58375cfe9c53e5f9
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/tactic.lean
d1859f07fa5aa258de76b7dabc75f3cfdcb79436
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
47,266
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.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state /-- Create a tactic state with an empty local context and a dummy goal. -/ meta constant mk_empty : environment → options → tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { interaction_monad.monad with failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _ } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, repeat_at_most n t) <|> skip /-- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, repeat_exactly n t meta def repeat : tactic unit → tactic unit := repeat_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨has_map.map to_fmt ∘ monad.mapm pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. -/ meta constant whnf (e : expr) (md := semireducible) : tactic expr /-- (head) eta expand the given expression -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction -/ meta constant head_zeta : expr → tactic expr /-- zeta reduction -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) meta constant get_unused_name (n : name) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- rotate goals to the left -/ meta constant rotate_left : nat → tactic unit meta constant get_goals : tactic (list expr) meta constant set_goals : list expr → tactic unit inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list expr) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool meta constant mk_fresh_name : tactic name /-- Return a hash code for expr that ignores inst_implicit arguments, and proofs. -/ meta constant abstract_hash : expr → tactic nat /-- Return the "weight" of the given expr while ignoring inst_implicit arguments, and proofs. -/ meta constant abstract_weight : expr → tactic nat meta constant abstract_eq : expr → expr → tactic bool /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal a list of new hypotheses and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- (doc_string env d k) return the doc string for d (if available) -/ meta constant doc_string : name → tactic string meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr meta constant module_doc_strings : tactic (list (option name × string)) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. -/ meta constant kabstract (e t : expr) (md := reducible) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none meta def whnf_target : tactic unit := target >>= whnf >>= change meta def unsafe_change (e : expr) : tactic unit := change e ff meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n meta def intro1 : tactic expr := intro `_ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q meta def revert (l : expr) : tactic nat := revert_lst [l] meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) meta def rotate : nat → tactic unit := rotate_left /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic unit := apply_core e cfg >>= try_apply_opt_auto_param cfg meta def fapply (e : expr) : tactic unit := apply e {new_goals := new_goals.all} meta def eapply (e : expr) : tactic unit := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) : tactic unit := mk_const c >>= apply meta def eapplyc (c : name) : tactic unit := mk_const c >>= eapply meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic unit := if e.is_local_constant then cases_core e ids md >> return () else do x ← mk_fresh_name, n ← revert_kdependencies e dmd, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, (step (cases_core h ids md); intron n) meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm) (intro h >> skip) private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Define id_locked using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_locked is used in the builtin implementation of tactic.change -/ run_cmd do let l := level.param `l, let Ty : pexpr := expr.sort l, type ← to_expr ``(Π {α : %%Ty}, α → α), val ← to_expr ``(λ {α : %%Ty} (a : α), a), add_decl (declaration.defn `id_locked [`l] type val reducibility_hints.opaque tt) lemma id_locked_eq {α : Type u} (a : α) : id_locked a = a := rfl attribute [inline] id_locked /- Define id_rhs using meta-programming because we don't have syntax for setting reducibility_hints. See module init.meta.declaration. Remark: id_rhs is used in the equation compiler to address performance issues when proving equational lemmas. -/ run_cmd do let l := level.param `l, let Ty : pexpr := expr.sort l, type ← to_expr ``(Π (α : %%Ty), α → α), val ← to_expr ``(λ (α : %%Ty) (a : α), a), add_decl (declaration.defn `id_rhs [`l] type val reducibility_hints.abbrev tt) attribute [reducible, inline] id_rhs /- Install monad laws tactic and use it to prove some instances. -/ meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def unsafe_monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined} namespace tactic meta def mk_id_locked_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id_locked [level.zero]) prop) pr meta def mk_id_locked_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_locked_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_locked_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
c7dc06f710e15981d62867f5b9c1fba152c637bd
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/computability/turing_machine.lean
7f3fbaf8571c2465c05c5c26cfefbf73a5973a9d
[ "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
67,647
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Define a sequence of simple machine languages, starting with Turing machines and working up to more complex lanaguages based on Wang B-machines. -/ import data.fintype data.pfun logic.relation open relation namespace turing /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq] inductive dir | left | right def tape (Γ) := Γ × list Γ × list Γ def tape.mk {Γ} [inhabited Γ] (l : list Γ) : tape Γ := (l.head, [], l.tail) def tape.mk' {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := (R.head, L, R.tail) def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left (a, L, R) := (L.head, L.tail, a :: R) | dir.right (a, L, R) := (R.head, a :: L, R.tail) def tape.nth {Γ} [inhabited Γ] : tape Γ → ℤ → Γ | (a, L, R) 0 := a | (a, L, R) (n+1:ℕ) := R.inth n | (a, L, R) -[1+ n] := L.inth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.nth 0 = T.1 | (a, L, R) := rfl @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | (a, L, R) -[1+ n] := by cases L; refl | (a, L, R) 0 := by cases L; refl | (a, L, R) 1 := rfl | (a, L, R) ((n+1:ℕ)+1) := by rw add_sub_cancel; refl @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.right).nth i = T.nth (i+1) | (a, L, R) (n+1:ℕ) := by cases R; refl | (a, L, R) 0 := by cases R; refl | (a, L, R) -1 := rfl | (a, L, R) -[1+ n+1] := show _ = tape.nth _ (-[1+ n] - 1 + 1), by rw sub_add_cancel; refl def tape.write {Γ} (b : Γ) : tape Γ → tape Γ | (a, LR) := (b, LR) @[simp] theorem tape.write_self {Γ} : ∀ (T : tape Γ), T.write T.1 = T | (a, LR) := rfl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | (a, L, R) 0 := rfl | (a, L, R) (n+1:ℕ) := rfl | (a, L, R) -[1+ n] := rfl def tape.map {Γ Γ'} (f : Γ → Γ') : tape Γ → tape Γ' | (a, L, R) := (f a, L.map f, R.map f) @[simp] theorem tape.map_fst {Γ Γ'} (f : Γ → Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 | (a, L, R) := rfl @[simp] theorem tape.map_write {Γ Γ'} (f : Γ → Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) | (a, L, R) := rfl @[class] def pointed_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') := f (default _) = default _ theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [pointed_map f] : ∀ (T : tape Γ) d, (T.move d).map f = (T.map f).move d | (a, [], R) dir.left := prod.ext ‹pointed_map f› rfl | (a, b::L, R) dir.left := rfl | (a, L, []) dir.right := prod.ext ‹pointed_map f› rfl | (a, L, b::R) dir.right := rfl theorem tape.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [f0 : pointed_map f] : ∀ (l : list Γ), (tape.mk l).map f = tape.mk (l.map f) | [] := prod.ext ‹pointed_map f› rfl | (a::l) := rfl def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ match f s with none := sum.inl s | some s' := sum.inr s' end) def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine pfun.fix_induction h (λ a h IH, _), cases e : f a with a', { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ roption.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases roption.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply roption.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply roption.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := roption.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp [respects], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := roption.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ def dwrite {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) : C k := if h : k = k' then eq.rec_on h.symm l else S k @[simp] theorem dwrite_eq {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) (l : C k) : dwrite S k l k = l := dif_pos rfl @[simp] theorem dwrite_ne {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) (h : ¬ k = k') : dwrite S k' l k = S k := dif_neg h @[simp] theorem dwrite_self {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) : dwrite S k (S k) = S := funext $ λ k', by unfold dwrite; split_ifs; [subst h, refl] namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move {} : dir → stmt | write {} : Γ → stmt /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ def machine := Λ → Γ → option (Λ × stmt) /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : roption (list Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] def stmt.map (f : Γ → Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) def cfg.map (f : Γ → Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : Γ → Γ') (f₂ : Γ' → Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S} (ss : supports M S) [pointed_map f₁] (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init [pointed_map f₁] [g0 : pointed_map g₁] (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g0) (tape.map_mk _ _) theorem machine.map_respects {S} (ss : supports M S) [pointed_map f₁] [pointed_map g₁] (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto {} : (Γ → σ → Λ) → stmt | halt {} : stmt open stmt /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) variables [inhabited Λ] [inhabited σ] def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk l⟩ def eval (M : Λ → stmt) (l : list Γ) : roption (list Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) variables [fintype Γ] def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) local attribute [instance] classical.dec noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply finset.mem_insert_self theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end end end TM1 namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end variables [fintype Γ] [fintype σ] noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ local attribute [instance] classical.dec local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [roption.map_eq_map, roption.map_map, TM1.eval], congr', exact funext (λ ⟨_, _, _⟩, rfl) end end end TM1to0 /- Reduce an n-symbol Turing machine to a 2-symbol Turing machine -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt :: v))) (stmt.move dir.right $ read_aux i (λ v, f (ff :: v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q def tr_normal : stmt₁ → stmt' | (stmt.move dir.left q) := move dir.right $ (move dir.left)^[2] $ tr_normal q | (stmt.move dir.right q) := move dir.right $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto (λ _ s, Λ'.normal (l a s)) | stmt.halt := move dir.right $ move dir.left $ stmt.halt def tr_tape' (L R : list Γ) : tape bool := tape.mk' (L.bind (λ x, (enc x).to_list.reverse)) (R.bind (λ x, (enc x).to_list) ++ [default _]) def tr_tape : tape Γ → tape bool | (a, L, R) := tr_tape' L (a :: R) theorem tr_tape_drop_right : ∀ R : list Γ, list.drop n (R.bind (λ x, (enc x).to_list)) = R.tail.bind (λ x, (enc x).to_list) | [] := list.drop_nil _ | (a::R) := list.drop_left' (enc a).2 parameters (enc0 : enc (default _) = vector.repeat ff n) section include enc0 theorem tr_tape_take_right : ∀ R : list Γ, list.take' n (R.bind (λ x, (enc x).to_list)) = (enc R.head).to_list | [] := show list.take' n list.nil = _, by rw [list.take'_nil]; exact (congr_arg vector.to_list enc0).symm | (a::R) := list.take'_left' (enc a).2 end parameters (M : Λ → stmt₁) def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (L.head :: R)) := begin cases L with a L, { simp only [enc0, vector.repeat, tr_tape', list.cons_bind, list.head, list.append_assoc], suffices : ∀ i R', default _ ∈ R' → (tape.move dir.left^[i]) (tape.mk' [] R') = tape.mk' [] (list.repeat ff i ++ R'), from this n _ (list.mem_append_right _ (list.mem_singleton_self _)), intros i R' hR, induction i with i IH, {refl}, rw [nat.iterate_succ', IH], refine prod.ext rfl (prod.ext rfl (list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR))) }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ L' R' l₁ l₂ (hR : default _ ∈ R') (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), (tape.move dir.left^[l₁.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' L' (vector.to_list (enc a) ++ R'), { simpa only [list.length_reverse, vector.to_list_length] using this _ _ _ _ _ (list.reverse_reverse _).symm, exact list.mem_append_right _ (list.mem_singleton_self _) }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, nat.iterate_succ], convert IH _ e, exact prod.ext rfl (prod.ext rfl (list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR))) } end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (R.head :: L) R.tail) := begin cases R with a R, { simp only [enc0, vector.repeat, tr_tape', list.head, list.cons_bind, vector.to_list_mk, list.reverse_repeat], suffices : ∀ i L', (tape.move dir.right^[i]) (ff, L', []) = (ff, list.repeat ff i ++ L', []), from this n _, intros, induction i with i IH, {refl}, rw [nat.iterate_succ', IH], refine prod.ext rfl (prod.ext rfl rfl) }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ L' R' l₁ l₂ : list bool, (tape.move dir.right^[l₂.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' (list.reverse_core l₂ l₁ ++ L') R', { simpa only [vector.to_list_length] using this _ _ [] (enc a).to_list }, intros, induction l₂ with b l₂ IH generalizing l₁, {refl}, exact IH (b::l₁) } end theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [nat.iterate_succ', step_aux, IH, ← nat.iterate_succ] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L (R.head :: R.tail)) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc L R) = step_aux (f (enc R.head)) v (tr_tape' enc (R.head :: L) R.tail), { rw [read, this, step_aux_move enc enc0, encdec, tr_tape'_move_left enc enc0], refl }, cases R with a R, { suffices : ∀ i f L', step_aux (read_aux i f) v (ff, L', []) = step_aux (f (vector.repeat ff i)) v (ff, list.repeat ff i ++ L', []), { intro f, convert this n f _, refine prod.ext rfl (prod.ext ((list.cons_bind _ _ _).trans _) rfl), simp only [list.head, enc0, vector.repeat, vector.to_list, list.reverse_repeat] }, clear f L, intros, induction i with i IH generalizing L', {refl}, change step_aux (read_aux i (λ v, f (ff :: v))) v (ff, ff :: L', []) = step_aux (f (vector.repeat ff (nat.succ i))) v (ff, ff :: (list.repeat ff i ++ L'), []), rw [IH], congr', simpa only [list.append_assoc] using congr_arg (++ L') (list.repeat_add ff i 1).symm }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (l₁ ++ L') (l₂ ++ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (l₂.reverse_core l₁ ++ L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp only [subtype.eta]; refl }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, change (tape.mk' (l₁ ++ L') (a :: (l₂ ++ R'))).1 with a, transitivity step_aux (read_aux l₂.length (λ v, f (a :: v))) v (tape.mk' (a :: l₁ ++ L') (l₂ ++ R')), { cases a; refl }, rw IH, refl } end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (b :: R)) = step_aux q v (tr_tape' (a :: L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (l₁ ++ L') (l₂' ++ R')) = step_aux q v (tape.mk' (list.reverse_core l₂ l₁ ++ L') R'), from this [] _ _ ((enc b).2.trans (enc a).2.symm), clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, unfold write step_aux, convert IH _ _ e, refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, (a, L, R)⟩, begin cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc L R)) (tr_cfg enc (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl (this _ (a::R)) }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, nat.iterate, step_aux_move enc enc0, step_aux, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0]; apply IH }, case TM1.stmt.write : a q IH { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, simp only [tr, tr_normal, step_aux, step_aux_write enc dec enc0 encdec, step_aux_move enc enc0, tr_tape'_move_left enc enc0], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read enc dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], change (tape.mk' L R).1 with R.head, cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move enc enc0, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0], apply refl_trans_gen.refl } end omit enc0 encdec local attribute [instance] classical.dec parameters [fintype Γ] noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (Λ'.normal l) (writes (M l))) theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, nat.iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] local attribute [simp] supports_stmt_move supports_stmt_write theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bind.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bind.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, nat.iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bind.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push {} : ∀ k, (σ → Γ k) → stmt → stmt | peek {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto {} : (σ → Λ) → stmt | halt {} : stmt open stmt structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) parameters {Γ Λ σ K} def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (dwrite S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (dwrite S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) variables [inhabited Λ] [inhabited σ] def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, dwrite (λ _, []) k L⟩ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) local attribute [instance] classical.dec noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply finset.mem_insert_self theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.insert_empty_eq_singleton, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end end end TM2 namespace TM2to1 section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ inductive stackel (k : K) | val : Γ k → stackel | bottom : stackel | top : stackel instance stackel.inhabited (k) : inhabited (stackel k) := ⟨stackel.top _⟩ def stackel.is_bottom {k} : stackel k → bool | (stackel.bottom _) := tt | _ := ff def stackel.is_top {k} : stackel k → bool | (stackel.top _) := tt | _ := ff def stackel.get {k} : stackel k → option (Γ k) | (stackel.val a) := some a | _ := none section open stackel def stackel_equiv {k} : stackel k ≃ option (option (Γ k)) := begin refine ⟨λ s, _, λ s, _, _, _⟩, { cases s, exacts [some (some s), none, some none] }, { rcases s with _|_|s, exacts [bottom _, top _, val s] }, { intro s, cases s; refl }, { intro s, rcases s with _|_|s; refl }, end end def Γ' := ∀ k, stackel k instance Γ'.inhabited : inhabited Γ' := ⟨λ _, default _⟩ instance stackel.fintype {k} [fintype (Γ k)] : fintype (stackel k) := fintype.of_equiv _ stackel_equiv.symm instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := pi.fintype inductive st_act (k : K) | push {} : (σ → Γ k) → st_act | pop {} : bool → (σ → option (Γ k) → σ) → st_act section open st_act def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (pop ff f) := TM2.stmt.peek k f | (pop tt f) := TM2.stmt.pop k f def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (pop b f) := f v l.head' def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (pop ff f) := l | (pop tt f) := l.tail @[elab_as_eliminator] theorem {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (pop ff f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop tt f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run [fintype K] [∀ k, fintype (Γ k)] [fintype σ] (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal {} : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret {} : K → stmt₂ → Λ' open Λ' instance : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, dwrite a k $ stackel.val $ f s) $ move dir.right $ write (λ a s, dwrite a k $ stackel.top k) q | (st_act.pop b f) := move dir.left $ load (λ a s, f s (a k).get) $ cond b ( branch (λ a s, (a k).is_bottom) ( move dir.right q ) ( move dir.right $ write (λ a s, dwrite a k $ default _) $ move dir.left $ write (λ a s, dwrite a k $ stackel.top k) q ) ) ( move dir.right q ) def tr_init (k) (L : list (Γ k)) : list Γ' := stackel.bottom :: match L.reverse with | [] := [stackel.top] | (a::L') := dwrite stackel.top k (stackel.val a) :: (L'.map stackel.val ++ [stackel.top k]).map (dwrite (default _) k) end theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (dwrite S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.pop ff f) := by unfold st_write; rw dwrite_self; refl | (st_act.pop tt f) := rfl def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.pop ff f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop tt f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl parameters (M : Λ → stmt₂) include M def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a k).is_top) (tr_st_act (goto (λ _ _, ret k q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret k q) := branch (λ a s, (a k).is_bottom) (tr_normal q) (move dir.left $ goto (λ _ _, ret k q)) def tr_stk {k} (S : list (Γ k)) (L : list (stackel k)) : Prop := ∃ n, L = (S.map stackel.val).reverse_core (stackel.top k :: list.repeat (default _) n) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} {L : list Γ'} : (∀ k, tr_stk (S k) (L.map (λ a, a k))) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, (stackel.bottom, [], L)⟩ theorem tr_respects_aux₁ {k} (o q v) : ∀ S₁ {s S₂} {T : list Γ'}, T.map (λ (a : Γ'), a k) = (list.map stackel.val S₁).reverse_core (s :: S₂) → ∃ a T₁ T₂, T = list.reverse_core T₁ (a :: T₂) ∧ a k = s ∧ T₁.map (λ (a : Γ'), a k) = S₁.map stackel.val ∧ T₂.map (λ (a : Γ'), a k) = S₂ ∧ reaches₀ (TM1.step tr) ⟨some (go k o q), v, (stackel.bottom, [], T)⟩ ⟨some (go k o q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ | [] s S₂ (a :: T) hT := by injection hT with es e₂; exact ⟨a, [], _, rfl, es, rfl, e₂, reaches₀.single rfl⟩ | (s' :: S₁) s S₂ T hT := let ⟨a, T₁, b'::T₂, e, es', e₁, e₂, H⟩ := tr_respects_aux₁ S₁ hT in by injection e₂ with es e₂; exact ⟨b', a::T₁, T₂, e, es, congr (congr_arg list.cons es') e₁, e₂, H.tail (by unfold TM1.step; change some (cond (TM2to1.stackel.is_top (a k)) _ _) = _; rw es'; refl)⟩ local attribute [simp] TM1.step TM1.step_aux tr tr_st_act st_var st_write tape.move tape.write list.reverse_core stackel.get stackel.is_bottom theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {T₁ T₂ : list Γ'} {a : Γ'} (hT : ∀ k, tr_stk (S k) ((T₁.reverse_core (a :: T₂)).map (λ (a : Γ'), a k))) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val (S k)) (ea : a k = stackel.top k) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' : ∀ k, list (Γ k) := dwrite S k Sk' in ∃ b (T₁' T₂' : list Γ'), (∀ (k' : K), tr_stk (S' k') ((T₁'.reverse_core (b :: T₂')).map (λ (a : Γ'), a k'))) ∧ T₁'.map (λ a, a k) = Sk'.map stackel.val ∧ b k = stackel.top k ∧ TM1.step_aux (tr_st_act q o) v (a, T₁ ++ [stackel.bottom], T₂) = TM1.step_aux q v' (b, T₁' ++ [stackel.bottom], T₂') := begin dsimp only, cases o with f b f, case TM2to1.st_act.push : { refine ⟨_, dwrite a k (stackel.val (f v)) :: T₁, _, _, by simp only [list.map, dwrite_eq, e₁]; refl, by simp only [tape.write, tape.move, dwrite_eq], rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n.pred, simp only [list.reverse_core_eq, list.map_append, list.map_reverse, e₁, list.map_cons, list.append_left_inj] at e, simp only [list.reverse_core_eq, e.1, e.2, list.map_append, prod.fst, list.map_reverse, list.reverse_cons, list.map, dwrite_eq, e₁, list.map_tail, list.tail_repeat, TM2to1.st_write] }, { cases T₂ with t T₂, { existsi n+1, simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add, tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append, list.map, list.head, list.tail, list.append_assoc] using congr_arg (++ [default Γ' k']) e }, { existsi n, simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add, tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append, list.map, list.head, list.tail, list.append_assoc] using e } } }, have dw := dwrite_self S k, cases T₁ with t T₁; cases eS : S k with s Sk; rw eS at e₁ dw; injection e₁ with tk e₁'; cases b, { -- peek nil simp only [dw, st_write], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- pop nil simp only [dw, st_write, list.tail], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- peek cons change t k = stackel.val s at tk, simp only [eS, tk, dw, st_write, TM1.step_aux, tr_st_act, cond, tape.move, list.head, list.tail, list.cons_append], exact ⟨_, t::T₁, _, hT, e₁, ea, rfl⟩ }, { -- pop cons change t k = stackel.val s at tk, simp only [tk, st_write, list.tail, TM1.step_aux, tr_st_act, cond, tape.move, list.cons_append, list.head], refine ⟨_, _, _, _, e₁', dwrite_eq _ _ _, rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n+1, simp only [list.reverse_core_eq, eS, e₁', list.append_left_inj, list.map_append, list.map_reverse, list.map, list.reverse_cons, list.append_assoc, list.cons_append] at e ⊢, simp only [tape.move, tape.write, list.head, list.tail, dwrite_eq], rw [e.2.2]; refl }, { existsi n, simpa only [dwrite_ne _ _ _ _ h, list.map, list.head, list.tail, list.reverse_core, list.map_reverse_core, tape.move, tape.write] using e } }, end theorem tr_respects_aux₃ {k q v} {S : Π k, list (Γ k)} {T : list Γ'} (hT : ∀ k, tr_stk (S k) (T.map (λ (a : Γ'), a k))) : ∀ (T₁ : list Γ') {T₂ : list Γ'} {a : Γ'} {S₁} (e : T = T₁.reverse_core (a :: T₂)) (ha : (a k).is_bottom = ff) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val S₁), reaches₀ (TM1.step tr) ⟨some (ret k q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ ⟨some (ret k q), v, (stackel.bottom, [], T)⟩ | [] T₂ a S₁ e ha e₁ := reaches₀.single (by simp only [ha, e, TM1.step, option.mem_def, tr, TM1.step_aux] {constructor_eq:=ff}; refl) | (b :: T₁) T₂ a (s :: S₁) e ha e₁ := begin unfold list.map at e₁, injection e₁ with es e₁, refine reaches₀.head _ (tr_respects_aux₃ T₁ e (by rw es; refl) e₁), simp only [ha, option.mem_def, TM1.step, tr, TM1.step_aux], refl end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list Γ'}, (∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.bottom, [], T)) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (stackel.bottom, [], T)) b := begin rcases hT k with ⟨n, hTk⟩, simp only [tr_normal_run], rcases tr_respects_aux₁ M o q v _ hTk with ⟨a, T₁, T₂, rfl, ea, e₁, e₂, hgo⟩, rcases tr_respects_aux₂ M hT e₁ ea _ with ⟨b, T₁', T₂', hT', e₁', eb, hrun⟩, have hret := tr_respects_aux₃ M hT' _ rfl (by rw eb; refl) e₁', have := hgo.tail' rfl, simp only [ea, tr, TM1.step_aux] at this, rw [hrun, TM1.step_aux] at this, rcases IH hT' with ⟨c, gc, rc⟩, simp only [step_run], refine ⟨c, gc, (this.to₀.trans hret _ (trans_gen.head' rfl rc)).to_refl⟩ end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ hT, exact IH₁ hT] }, { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := ⟨λ k', begin unfold tr_init, cases e : L.reverse with a L', { cases list.reverse_eq_nil.1 e, rw dwrite_self, exact ⟨0, rfl⟩ }, by_cases k' = k, { subst k', existsi 0, simp only [list.tail, dwrite_eq, list.reverse_core_eq, list.repeat, tr_init, list.map, list.map_map, (∘), list.map_id' (λ _, rfl)], rw [← list.map_reverse, e], refl }, { existsi L'.length + 1, simp only [dwrite_ne _ _ _ _ h, list.tail, tr_init, list.map_map, list.map, list.map_append, list.repeat_add, (∘), list.map_const] {constructor_eq:=ff}, refl } end⟩ theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ S : ∀ k, list (Γ k), (∀ k', tr_stk (S k') (L₁.map (λ a, a k'))) ∧ S k = L₂ := begin rcases (roption.mem_map_iff _).1 H₁ with ⟨c₁, h₁, rfl⟩, rcases (roption.mem_map_iff _).1 H₂ with ⟨c₂, h₂, rfl⟩, rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h₂ with ⟨_, ⟨q, v, S, L₁', hT⟩, h₃⟩, cases roption.mem_unique h₁ h₃, exact ⟨S, hT, rfl⟩ end variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] local attribute [instance] classical.dec local attribute [simp] TM2.stmts₁_self noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.pop ff f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop tt f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret k q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (normal l) (tr_stmts₁ (M l))) local attribute [simp] tr_stmts₁ tr_stmts₁_run supports_run tr_normal_run TM1.supports_stmt TM2.supports_stmt theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ M q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ M q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bind.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.has_insert_eq_insert, finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inr rfl), have hret := sub _ (or.inl $ or.inl rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.has_insert_eq_insert, finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bind.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
4bcc74eaec053e4536bee93ac2e296b96ffbd483
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/japanese_bracket.lean
d287916d88f202f9814e7731c5ac298b9e502f0a
[ "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
8,052
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import measure_theory.measure.haar_lebesgue import measure_theory.integral.layercake /-! # Japanese Bracket In this file, we show that Japanese bracket $(1 + \|x\|^2)^{1/2}$ can be estimated from above and below by $1 + \|x\|$. The functions $(1 + \|x\|^2)^{-r/2}$ and $(1 + |x|)^{-r}$ are integrable provided that `r` is larger than the dimension. ## Main statements * `integrable_one_add_norm`: the function $(1 + |x|)^{-r}$ is integrable * `integrable_jap` the Japanese bracket is integrable -/ noncomputable theory open_locale big_operators nnreal filter topology ennreal open asymptotics filter set real measure_theory finite_dimensional variables {E : Type*} [normed_add_comm_group E] lemma sqrt_one_add_norm_sq_le (x : E) : real.sqrt (1 + ‖x‖^2) ≤ 1 + ‖x‖ := begin refine le_of_pow_le_pow 2 (by positivity) two_pos _, simp [sq_sqrt (zero_lt_one_add_norm_sq x).le, add_pow_two], end lemma one_add_norm_le_sqrt_two_mul_sqrt (x : E) : 1 + ‖x‖ ≤ (real.sqrt 2) * sqrt (1 + ‖x‖^2) := begin suffices : (sqrt 2 * sqrt (1 + ‖x‖ ^ 2)) ^ 2 - (1 + ‖x‖) ^ 2 = (1 - ‖x‖) ^2, { refine le_of_pow_le_pow 2 (by positivity) (by norm_num) _, rw [←sub_nonneg, this], positivity, }, rw [mul_pow, sq_sqrt (zero_lt_one_add_norm_sq x).le, add_pow_two, sub_pow_two], norm_num, ring, end lemma rpow_neg_one_add_norm_sq_le {r : ℝ} (x : E) (hr : 0 < r) : (1 + ‖x‖^2)^(-r/2) ≤ 2^(r/2) * (1 + ‖x‖)^(-r) := begin have h1 : 0 ≤ (2 : ℝ) := by positivity, have h3 : 0 < sqrt 2 := by positivity, have h4 : 0 < 1 + ‖x‖ := by positivity, have h5 : 0 < sqrt (1 + ‖x‖ ^ 2) := by positivity, have h6 : 0 < sqrt 2 * sqrt (1 + ‖x‖^2) := mul_pos h3 h5, rw [rpow_div_two_eq_sqrt _ h1, rpow_div_two_eq_sqrt _ (zero_lt_one_add_norm_sq x).le, ←inv_mul_le_iff (rpow_pos_of_pos h3 _), rpow_neg h4.le, rpow_neg (sqrt_nonneg _), ←mul_inv, ←mul_rpow h3.le h5.le, inv_le_inv (rpow_pos_of_pos h6 _) (rpow_pos_of_pos h4 _), rpow_le_rpow_iff h4.le h6.le hr], exact one_add_norm_le_sqrt_two_mul_sqrt _, end lemma le_rpow_one_add_norm_iff_norm_le {r t : ℝ} (hr : 0 < r) (ht : 0 < t) (x : E) : t ≤ (1 + ‖x‖) ^ -r ↔ ‖x‖ ≤ t ^ -r⁻¹ - 1 := begin rw [le_sub_iff_add_le', neg_inv], exact (real.le_rpow_inv_iff_of_neg (by positivity) ht (neg_lt_zero.mpr hr)).symm, end variables (E) lemma closed_ball_rpow_sub_one_eq_empty_aux {r t : ℝ} (hr : 0 < r) (ht : 1 < t) : metric.closed_ball (0 : E) (t^(-r⁻¹) - 1) = ∅ := begin rw [metric.closed_ball_eq_empty, sub_neg], exact real.rpow_lt_one_of_one_lt_of_neg ht (by simp only [hr, right.neg_neg_iff, inv_pos]), end variables [normed_space ℝ E] [finite_dimensional ℝ E] variables {E} lemma finite_integral_rpow_sub_one_pow_aux {r : ℝ} (n : ℕ) (hnr : (n : ℝ) < r) : ∫⁻ (x : ℝ) in Ioc 0 1, ennreal.of_real ((x ^ -r⁻¹ - 1) ^ n) < ∞ := begin have hr : 0 < r := lt_of_le_of_lt n.cast_nonneg hnr, have h_int : ∀ (x : ℝ) (hx : x ∈ Ioc (0 : ℝ) 1), ennreal.of_real ((x ^ -r⁻¹ - 1) ^ n) ≤ ennreal.of_real (x ^ -(r⁻¹ * n)) := begin intros x hx, have hxr : 0 ≤ x^ -r⁻¹ := rpow_nonneg_of_nonneg hx.1.le _, apply ennreal.of_real_le_of_real, rw [←neg_mul, rpow_mul hx.1.le, rpow_nat_cast], refine pow_le_pow_of_le_left _ (by simp only [sub_le_self_iff, zero_le_one]) n, rw [le_sub_iff_add_le', add_zero], refine real.one_le_rpow_of_pos_of_le_one_of_nonpos hx.1 hx.2 _, rw [right.neg_nonpos_iff, inv_nonneg], exact hr.le, end, refine lt_of_le_of_lt (set_lintegral_mono (by measurability) (by measurability) h_int) _, refine integrable_on.set_lintegral_lt_top _, rw ←interval_integrable_iff_integrable_Ioc_of_le zero_le_one, apply interval_integral.interval_integrable_rpow', rwa [neg_lt_neg_iff, inv_mul_lt_iff' hr, one_mul], end lemma finite_integral_one_add_norm [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : ∫⁻ (x : E), ennreal.of_real ((1 + ‖x‖) ^ -r) < ∞ := begin have hr : 0 < r := lt_of_le_of_lt (finrank ℝ E).cast_nonneg hnr, -- We start by applying the layer cake formula have h_meas : measurable (λ (ω : E), (1 + ‖ω‖) ^ -r) := by measurability, have h_pos : ∀ x : E, 0 ≤ (1 + ‖x‖) ^ -r := by { intros x, positivity }, rw lintegral_eq_lintegral_meas_le volume h_pos h_meas, -- We use the first transformation of the integrant to show that we only have to integrate from -- 0 to 1 and from 1 to ∞ have h_int : ∀ (t : ℝ) (ht : t ∈ Ioi (0 : ℝ)), (volume {a : E | t ≤ (1 + ‖a‖) ^ -r} : ennreal) = volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) := begin intros t ht, congr' 1, ext x, simp only [mem_set_of_eq, mem_closed_ball_zero_iff], exact le_rpow_one_add_norm_iff_norm_le hr (mem_Ioi.mp ht) x, end, rw set_lintegral_congr_fun measurable_set_Ioi (ae_of_all volume $ h_int), have hIoi_eq : Ioi (0 : ℝ) = Ioc (0 : ℝ) 1 ∪ Ioi 1 := (set.Ioc_union_Ioi_eq_Ioi zero_le_one).symm, have hdisjoint : disjoint (Ioc (0 : ℝ) 1) (Ioi 1) := by simp [disjoint_iff], rw [hIoi_eq, lintegral_union measurable_set_Ioi hdisjoint, ennreal.add_lt_top], have h_int' : ∀ (t : ℝ) (ht : t ∈ Ioc (0 : ℝ) 1), (volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) : ennreal) = ennreal.of_real ((t^(-r⁻¹) - 1) ^ finite_dimensional.finrank ℝ E) * volume (metric.ball (0:E) 1) := begin intros t ht, refine volume.add_haar_closed_ball (0 : E) _, rw [le_sub_iff_add_le', add_zero], exact real.one_le_rpow_of_pos_of_le_one_of_nonpos ht.1 ht.2 (by simp [hr.le]), end, have h_meas' : measurable (λ (a : ℝ), ennreal.of_real ((a ^ -r⁻¹ - 1) ^ finrank ℝ E)) := by measurability, split, -- The integral from 0 to 1: { rw [set_lintegral_congr_fun measurable_set_Ioc (ae_of_all volume $ h_int'), lintegral_mul_const _ h_meas', ennreal.mul_lt_top_iff], left, -- We calculate the integral exact ⟨finite_integral_rpow_sub_one_pow_aux (finrank ℝ E) hnr, measure_ball_lt_top⟩ }, -- The integral from 1 to ∞ is zero: have h_int'' : ∀ (t : ℝ) (ht : t ∈ Ioi (1 : ℝ)), (volume (metric.closed_ball (0 : E) (t^(-r⁻¹) - 1)) : ennreal) = 0 := λ t ht, by rw [closed_ball_rpow_sub_one_eq_empty_aux E hr ht, measure_empty], -- The integral over the constant zero function is finite: rw [set_lintegral_congr_fun measurable_set_Ioi (ae_of_all volume $ h_int''), lintegral_const 0, zero_mul], exact with_top.zero_lt_top, end lemma integrable_one_add_norm [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : integrable (λ (x : E), (1 + ‖x‖) ^ -r) := begin refine ⟨by measurability, _⟩, -- Lower Lebesgue integral have : ∫⁻ (a : E), ‖(1 + ‖a‖) ^ -r‖₊ = ∫⁻ (a : E), ennreal.of_real ((1 + ‖a‖) ^ -r) := lintegral_nnnorm_eq_of_nonneg (λ _, rpow_nonneg_of_nonneg (by positivity) _), rw [has_finite_integral, this], exact finite_integral_one_add_norm hnr, end lemma integrable_rpow_neg_one_add_norm_sq [measure_space E] [borel_space E] [(@volume E _).is_add_haar_measure] {r : ℝ} (hnr : (finrank ℝ E : ℝ) < r) : integrable (λ (x : E), (1 + ‖x‖^2) ^ (-r/2)) := begin have hr : 0 < r := lt_of_le_of_lt (finrank ℝ E).cast_nonneg hnr, refine ((integrable_one_add_norm hnr).const_mul $ 2 ^ (r / 2)).mono (by measurability) (eventually_of_forall $ λ x, _), have h1 : 0 ≤ (1 + ‖x‖ ^ 2) ^ (-r/2) := by positivity, have h2 : 0 ≤ (1 + ‖x‖) ^ -r := by positivity, have h3 : 0 ≤ (2 : ℝ)^(r/2) := by positivity, simp_rw [norm_mul, norm_eq_abs, abs_of_nonneg h1, abs_of_nonneg h2, abs_of_nonneg h3], exact rpow_neg_one_add_norm_sq_le _ hr, end
c10e0abc313781db1b9b822c8ead79e2d3df7ec7
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/category_theory/colimits.lean
d823c5c5f128f1ed95672831e578057c591aba1e
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
12,805
lean
import category_theory.category import data.is_equiv import data.bij_on /- The basic finite colimit notions: initial objects, (binary) coproducts, coequalizers and pushouts. For each notion X, we define three structures/classes: * `Is_X`, parameterized by a cocone diagram (but not on the commutativity condition!), which describes the commutativity and the universal property of the cocone. For example, a value of type `Is_pushout f₀ f₁ g₀ g₁` represents the property that the square formed by the four morphisms commutes and is a pushout square. Each `Is_X` is a subsingleton, but not a Prop, because we want to be able to constructively obtain the morphisms whose existence is guaranteed by the universal property. * `X`, parameterized by the "input diagram" for the corresponding sort of colimit, which contains the data of a colimit of that sort on that diagram. For example, `pushout f₀ f₁` consists of an object and two maps which form a pushout square together with the given maps f₀ and f₁. These structures are not subsingletons, because colimits are unique only up to unique isomorphism. This structure exists mostly to be used in the corresponding `has_X` class. * `has_X`, a class for categories, which contains the data of a choice of `X` for each possible "input diagram". Thus an instance of `has_pushouts` is a category with a specified choice of pushout cocone on each span. It is not a subsingleton for the same reason that `X` is not one. The `has_X` classes are of obvious importance, but the `Is_X` structures are also very useful, especially in settings where colimits of type X are not known to exist a priori. For example, preservation of colimits by functors (in the usual "up to isomorphism" sense, not strictly preserving the chosen colimits) is naturally formulated in terms of `Is_X`, as is the standard fact about gluing together pushout squares. We define the `Is_X` structures by directly encoding the universal property using the `Is_equiv` type, a constructive version of `bijective`. Not sure yet whether this has advantages. In any case we provide an alternate "first-order" interface through `mk'` constructors and lemmas. -/ -- TODO: "first-order" lemmas for the other notions besides coequalizers open category_theory.category local notation f ` ∘ `:80 g:80 := g ≫ f namespace category_theory section universes v u parameters {C : Type u} [category.{v} C] section initial_object section Is -- The putative initial object. parameters {a : C} -- An object is initial if for each x, the Hom set `a ⟶ x` is a -- singleton. def initial_object_comparison (x : C) : (a ⟶ x) → true := λ _, trivial parameters (a) -- The (constructive) property of being an initial object. structure Is_initial_object : Type (max u v) := (universal : Π x, Is_equiv (initial_object_comparison x)) instance Is_initial_object.subsingleton : subsingleton Is_initial_object := ⟨by intros p p'; cases p; cases p'; congr⟩ parameters {a} -- Alternative verification of being an initial object. def Is_initial_object.mk' (induced : Π {x}, a ⟶ x) (uniqueness : ∀ {x} (k k' : a ⟶ x), k = k') : Is_initial_object := { universal := λ x, { e := { to_fun := initial_object_comparison x, inv_fun := λ p, induced, left_inv := assume h, uniqueness _ _, right_inv := assume p, rfl }, h := rfl } } parameters (H : Is_initial_object) def Is_initial_object.induced {x} : a ⟶ x := (H.universal x).e.symm trivial def Is_initial_object.uniqueness {x} (k k' : a ⟶ x) : k = k' := (H.universal x).bijective.1 rfl end Is -- An initial object. structure initial_object := (ob : C) (is_initial_object : Is_initial_object ob) parameters (C) -- A choice of initial object. (This is basically the same as -- initial_object, since there are no "parameters" in the definition -- of an initial object.) class has_initial_object := (initial_object : initial_object) end initial_object section coproduct section Is -- The putative coproduct diagram. parameters {a₀ a₁ b : C} {f₀ : a₀ ⟶ b} {f₁ : a₁ ⟶ b} -- The diagram above is a coproduct diagram when giving a map b ⟶ x is -- the same as giving a map a₀ ⟶ x and a map a₁ ⟶ x. def coproduct_comparison (x : C) : (b ⟶ x) → (a₀ ⟶ x) × (a₁ ⟶ x) := λ k, (k ∘ f₀, k ∘ f₁) parameters (f₀ f₁) -- The (constructive) property of being a coproduct. structure Is_coproduct : Type (max u v) := (universal : Π x, Is_equiv (coproduct_comparison x)) instance Is_coproduct.subsingleton : subsingleton Is_coproduct := ⟨by intros p p'; cases p; cases p'; congr⟩ parameters {f₀ f₁} -- Alternative verification of being a coproduct. def Is_coproduct.mk' (induced : Π {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x), b ⟶ x) (induced_commutes₀ : ∀ {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x), induced h₀ h₁ ∘ f₀ = h₀) (induced_commutes₁ : ∀ {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x), induced h₀ h₁ ∘ f₁ = h₁) (uniqueness : ∀ {x} (k k' : b ⟶ x), k ∘ f₀ = k' ∘ f₀ → k ∘ f₁ = k' ∘ f₁ → k = k') : Is_coproduct := { universal := λ x, { e := { to_fun := coproduct_comparison x, inv_fun := λ p, induced p.1 p.2, left_inv := assume h, by apply uniqueness; rw induced_commutes₀ <|> rw induced_commutes₁; refl, right_inv := assume p, prod.ext (induced_commutes₀ p.1 p.2) (induced_commutes₁ p.1 p.2) }, h := rfl } } parameters (H : Is_coproduct) def Is_coproduct.induced {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x) : b ⟶ x := (H.universal x).e.inv_fun (h₀, h₁) @[simp] lemma Is_coproduct.induced_commutes₀ {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x) : H.induced h₀ h₁ ∘ f₀ = h₀ := congr_arg prod.fst (H.universal x).cancel_right @[simp] lemma Is_coproduct.induced_commutes₁ {x} (h₀ : a₀ ⟶ x) (h₁ : a₁ ⟶ x) : H.induced h₀ h₁ ∘ f₁ = h₁ := congr_arg prod.snd (H.universal x).cancel_right lemma Is_coproduct.uniqueness {x : C} {k k' : b ⟶ x} (e₀ : k ∘ f₀ = k' ∘ f₀) (e₁ : k ∘ f₁ = k' ∘ f₁) : k = k' := (H.universal x).bijective.1 (prod.ext e₀ e₁) end Is -- A coproduct of a given diagram. structure coproduct (a₀ a₁ : C) := (ob : C) (map₀ : a₀ ⟶ ob) (map₁ : a₁ ⟶ ob) (is_coproduct : Is_coproduct map₀ map₁) parameters (C) -- A choice of coproducts of all diagrams. class has_coproducts := (coproduct : Π (a₀ a₁ : C), coproduct a₀ a₁) end coproduct section coequalizer section Is -- The putative coequalizer diagram. `commutes` is a `variable` -- because we do not want to index `Is_coequalizer` on it. parameters {a b c : C} {f₀ f₁ : a ⟶ b} {g : b ⟶ c} variables (commutes : g ∘ f₀ = g ∘ f₁) -- The diagram above is a coequalizer diagram when giving a map c ⟶ x -- is the same as giving a map b ⟶ x whose two pullback to a ⟶ x -- agree. def coequalizer_comparison (x : C) : (c ⟶ x) → {h : b ⟶ x // h ∘ f₀ = h ∘ f₁} := λ k, ⟨k ∘ g, have _ := commutes, by rw [←assoc, ←assoc, this]⟩ parameters (f₀ f₁ g) -- The (constructive) property of being a coequalizer diagram. -- TODO: Rewrite this in the same way as Is_pushout, using Bij_on? structure Is_coequalizer : Type (max u v) := (commutes : g ∘ f₀ = g ∘ f₁) (universal : Π x, Is_equiv (coequalizer_comparison commutes x)) instance Is_coequalizer.subsingleton : subsingleton Is_coequalizer := ⟨by intros p p'; cases p; cases p'; congr⟩ parameters {f₀ f₁ g} -- Alternative verification of being a coequalizer. def Is_coequalizer.mk' (induced : Π {x} (h : b ⟶ x), h ∘ f₀ = h ∘ f₁ → (c ⟶ x)) (induced_commutes : ∀ {x} (h : b ⟶ x) (e), induced h e ∘ g = h) (uniqueness : ∀ {x} (k k' : c ⟶ x), k ∘ g = k' ∘ g → k = k') : Is_coequalizer := { commutes := commutes, universal := λ x, { e := { to_fun := coequalizer_comparison commutes x, inv_fun := λ p, induced p.val p.property, left_inv := assume h, by apply uniqueness; rw induced_commutes; refl, right_inv := assume p, subtype.eq (induced_commutes p.val p.property) }, h := rfl } } parameters (H : Is_coequalizer) def Is_coequalizer.induced {x} (h : b ⟶ x) (e : h ∘ f₀ = h ∘ f₁) : c ⟶ x := (H.universal x).e.symm ⟨h, e⟩ @[simp] lemma Is_coequalizer.induced_commutes {x} (h : b ⟶ x) (e) : H.induced h e ∘ g = h := congr_arg subtype.val $ (H.universal x).cancel_right lemma Is_coequalizer.uniqueness {x} {k k' : c ⟶ x} (e : k ∘ g = k' ∘ g) : k = k' := (H.universal x).bijective.1 (subtype.eq e) end Is -- A coequalizer of a given diagram. structure coequalizer {a b : C} (f₀ f₁ : a ⟶ b) := (ob : C) (map : b ⟶ ob) (is_coequalizer : Is_coequalizer f₀ f₁ map) parameters (C) -- A choice of coequalizers of all diagrams. class has_coequalizers := (coequalizer : Π ⦃a b : C⦄ (f₀ f₁ : a ⟶ b), coequalizer f₀ f₁) end coequalizer section pushout section Is -- The putative pushout diagram. -- TODO: Order of indices? I sometimes prefer the "f g f' g' order", -- where f' is the pushout of f and g' is the pushout of g; that's -- "f₀ f₁ g₁ g₀" here. parameters {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁} {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} -- The diagram above is a pushout diagram when giving a map c ⟶ x is -- the same as giving a map b₀ ⟶ x and a map b₁ ⟶ x whose pullbacks to -- a ⟶ x agree. def pushout_comparison (commutes : g₀ ∘ f₀ = g₁ ∘ f₁) (x : C) : (c ⟶ x) → {p : (b₀ ⟶ x) × (b₁ ⟶ x) // p.1 ∘ f₀ = p.2 ∘ f₁} := λ k, ⟨(k ∘ g₀, k ∘ g₁), have _ := commutes, by rw [←assoc, ←assoc, this]⟩ parameters (f₀ f₁ g₀ g₁) -- The (constructive) property of being a pushout. structure Is_pushout : Type (max u v) := (universal : Π x, Bij_on (λ (k : c ⟶ x), (k ∘ g₀, k ∘ g₁)) set.univ {p | p.1 ∘ f₀ = p.2 ∘ f₁}) instance Is_pushout.subsingleton : subsingleton Is_pushout := ⟨by intros p p'; cases p; cases p'; congr⟩ parameters {f₀ f₁ g₀ g₁} -- Alternative verification of being a pushout. def Is_pushout.mk' (commutes : g₀ ∘ f₀ = g₁ ∘ f₁) (induced : Π {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x), h₀ ∘ f₀ = h₁ ∘ f₁ → (c ⟶ x)) (induced_commutes₀ : ∀ {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e), induced h₀ h₁ e ∘ g₀ = h₀) (induced_commutes₁ : ∀ {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e), induced h₀ h₁ e ∘ g₁ = h₁) (uniqueness : ∀ {x} (k k' : c ⟶ x), k ∘ g₀ = k' ∘ g₀ → k ∘ g₁ = k' ∘ g₁ → k = k') : Is_pushout := { universal := λ x, Bij_on.mk_univ { to_fun := pushout_comparison commutes x, inv_fun := λ p, induced p.val.1 p.val.2 p.property, left_inv := assume h, by apply uniqueness; rw induced_commutes₀ <|> rw induced_commutes₁; refl, right_inv := assume p, subtype.eq $ prod.ext (induced_commutes₀ p.val.1 p.val.2 p.property) (induced_commutes₁ p.val.1 p.val.2 p.property) } (assume p, rfl) } parameters (H : Is_pushout) include H def Is_pushout.commutes : g₀ ∘ f₀ = g₁ ∘ f₁ := by convert (H.universal c).maps_to (_ : 𝟙 c ∈ set.univ); simp def Is_pushout.induced {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e : h₀ ∘ f₀ = h₁ ∘ f₁) : c ⟶ x := (H.universal x).e.symm ⟨(h₀, h₁), e⟩ private lemma Is_pushout.induced_commutes' {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e) : (λ (k : c ⟶ x), (k ∘ g₀, k ∘ g₁)) (H.induced h₀ h₁ e) = (h₀, h₁) := (H.universal x).right_inv ⟨(h₀, h₁), e⟩ @[simp] lemma Is_pushout.induced_commutes₀ {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e) : H.induced h₀ h₁ e ∘ g₀ = h₀ := congr_arg prod.fst (Is_pushout.induced_commutes' h₀ h₁ e) @[simp] lemma Is_pushout.induced_commutes₁ {x} (h₀ : b₀ ⟶ x) (h₁ : b₁ ⟶ x) (e) : H.induced h₀ h₁ e ∘ g₁ = h₁ := congr_arg prod.snd (Is_pushout.induced_commutes' h₀ h₁ e) lemma Is_pushout.uniqueness {x} {k k' : c ⟶ x} (e₀ : k ∘ g₀ = k' ∘ g₀) (e₁ : k ∘ g₁ = k' ∘ g₁) : k = k' := (H.universal x).injective (prod.ext e₀ e₁) end Is -- A pushout of a given diagram. structure pushout {a b₀ b₁ : C} (f₀ : a ⟶ b₀) (f₁ : a ⟶ b₁) := (ob : C) (map₀ : b₀ ⟶ ob) (map₁ : b₁ ⟶ ob) (is_pushout : Is_pushout f₀ f₁ map₀ map₁) parameters (C) -- A choice of pushouts of all diagrams. class has_pushouts := (pushout : Π ⦃a b₀ b₁ : C⦄ (f₀ : a ⟶ b₀) (f₁ : a ⟶ b₁), pushout f₀ f₁) end pushout end end category_theory
3fdf7eb9703cc08de0a2e6a7e2b0d2be75a081f9
618003631150032a5676f229d13a079ac875ff77
/src/analysis/calculus/iterated_deriv.lean
99d440173c8348b7e417d51e96cf7d255b269d56
[ "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
14,704
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.calculus.deriv import analysis.calculus.times_cont_diff /-! # One-dimensional iterated derivatives We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nondiscrete normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topological_space open filter asymptotics set variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := begin rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = finset.univ.prod m • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one (hs : unique_diff_on 𝕜 s) {x : 𝕜} (hx : x ∈ s): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp [iterated_deriv_within, iterated_fderiv_within_one_apply hs hx], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `times_cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma times_cont_diff_on_of_continuous_on_differentiable_on_deriv {n : with_top ℕ} (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_on_of_differentiable_on_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : times_cont_diff_on 𝕜 n f s := begin apply times_cont_diff_on_of_differentiable_on, simpa [iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma times_cont_diff_on.continuous_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, -coe_fn_coe_base], exact h.continuous_on_iterated_fderiv_within hmn hs end /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma times_cont_diff_on.differentiable_on_iterated_deriv_within {n : with_top ℕ} {m : ℕ} (h : times_cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := begin simp [iterated_deriv_within_eq_equiv_comp, continuous_linear_equiv.comp_differentiable_on_iff, -coe_fn_coe_base], exact h.differentiable_on_iterated_fderiv_within hmn hs end /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma times_cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : with_top ℕ} (hs : unique_diff_on 𝕜 s) : times_cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [times_cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_continuous_on_iff, continuous_linear_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, continuous_linear_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = ((λ (g : 𝕜 → F), deriv_within g s)^[n]) f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), function.iterate_succ'], exact deriv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := begin rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, continuous_linear_equiv.self_comp_symm], refl end /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = finset.univ.prod m • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma times_cont_diff_iff_iterated_deriv {n : with_top ℕ} : times_cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : with_top ℕ) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : with_top ℕ) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [times_cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, continuous_linear_equiv.comp_continuous_iff, continuous_linear_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma times_cont_diff_of_differentiable_iterated_deriv {n : with_top ℕ} (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : times_cont_diff 𝕜 n f := times_cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma times_cont_diff.continuous_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) ≤ n) : continuous (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma times_cont_diff.differentiable_iterated_deriv {n : with_top ℕ} (m : ℕ) (h : times_cont_diff 𝕜 n f) (hmn : (m : with_top ℕ) < n) : differentiable 𝕜 (iterated_deriv m f) := (times_cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = (deriv^[n]) f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
4160410002fe3752356ae3fbe425c8a9c308ccfc
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/rescale/polyhedral_lattice.lean
ff1ca8edad5c5e9b6b07f67997f358d5eeadf839
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,892
lean
import rescale.normed_group import polyhedral_lattice.category /-! # Rescaling the norm on a polyhedral lattice. Rescaling the norm on a polyhedral lattice by a positive real factor gives a polyhedral lattice (at least for us -- Scholze seem to demand a rationality condition which we are missing). -/ noncomputable theory open_locale big_operators classical nnreal namespace generates_norm open rescale variables (N : ℝ≥0) (Λ : Type*) [polyhedral_lattice Λ] variables {J : Type*} [fintype J] (x : J → Λ) (hx : generates_norm x) def rescale_generators : J → (rescale N Λ) := x variables {Λ x} include hx lemma rescale [hN : fact (0 < N)] : generates_norm (rescale_generators N Λ x) := begin intro l, obtain ⟨c, H1, H2⟩ := hx l, refine ⟨c, H1, _⟩, simp only [norm_def, ← mul_div_assoc, ← finset.sum_div], congr' 1, end end generates_norm namespace rescale variables {N : ℝ≥0} {V : Type*} instance (Λ : Type*) [hN : fact (0 < N)] [polyhedral_lattice Λ] : polyhedral_lattice (rescale N Λ) := { finite := by { delta rescale, apply_instance }, free := by { delta rescale, apply_instance }, polyhedral' := begin obtain ⟨ι, _inst_ι, l, hl⟩ := polyhedral_lattice.polyhedral' Λ, resetI, refine ⟨ι, _inst_ι, l, hl.rescale N⟩, end } end rescale namespace PolyhedralLattice @[simps] protected def rescale (N : ℝ≥0) [hN : fact (0 < N)] : PolyhedralLattice ⥤ PolyhedralLattice := { obj := λ Λ, of (rescale N Λ), map := λ Λ₁ Λ₂ f, { to_fun := λ l, @rescale.of N Λ₂ (f ((@rescale.of N Λ₁).symm l)), map_add' := f.map_add, -- defeq abuse strict' := λ l, begin simp only [← coe_nnnorm, nnreal.coe_le_coe], erw [rescale.nnnorm_def, rescale.nnnorm_def], simp only [div_eq_mul_inv], exact mul_le_mul' (f.strict l) le_rfl end } } end PolyhedralLattice
634c450fc8f864f6931cc4facfd930a3163c4aa3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/387.lean
73b1950f0d11018de3302006d0a3b11ad4c7fa93
[ "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
587
lean
-- axiom p {α β} : α → β → Prop axiom foo {α β} (a : α) (b : β) : p a b example : p 0 0 := by simp [foo] example (a : Nat) : p a a := by simp [foo a] example : p 0 0 := by simp [foo 0] example : p 0 0 := by simp [foo 0 0] example : p 0 0 := by fail_if_success simp [foo 1] -- will not simplify simp [foo 0] example : p 0 0 ∧ p 1 1 := by simp [foo 1] trace_state simp [foo 0] namespace Foo axiom p {α} : α → Prop axiom foo {α} [ToString α] (n : Nat) (a : α) : p a example : p 0 := by simp [foo 0] example : p 0 ∧ True := by simp [foo 0] end Foo
f7aaa9baa537ca857a02154233b3213859ef0e6c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/direct_sum/module.lean
6735c5d53901d9a94271902e050f47a1ae224e4a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,163
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_sum.basic import linear_algebra.dfinsupp /-! # Direct sum of modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The first part of the file provides constructors for direct sums of modules. It provides a construction of the direct sum using the universal property and proves its uniqueness (`direct_sum.to_module.unique`). The second part of the file covers the special case of direct sums of submodules of a fixed module `M`. There is a canonical linear map from this direct sum to `M` (`direct_sum.coe_linear_map`), and the construction is of particular importance when this linear map is an equivalence; that is, when the submodules provide an internal decomposition of `M`. The property is defined more generally elsewhere as `direct_sum.is_internal`, but its basic consequences on `submodule`s are established in this file. -/ universes u v w u₁ namespace direct_sum open_locale direct_sum section general variables {R : Type u} [semiring R] variables {ι : Type v} [dec_ι : decidable_eq ι] include R variables {M : ι → Type w} [Π i, add_comm_monoid (M i)] [Π i, module R (M i)] instance : module R (⨁ i, M i) := dfinsupp.module instance {S : Type*} [semiring S] [Π i, module S (M i)] [Π i, smul_comm_class R S (M i)] : smul_comm_class R S (⨁ i, M i) := dfinsupp.smul_comm_class instance {S : Type*} [semiring S] [has_smul R S] [Π i, module S (M i)] [Π i, is_scalar_tower R S (M i)] : is_scalar_tower R S (⨁ i, M i) := dfinsupp.is_scalar_tower instance [Π i, module Rᵐᵒᵖ (M i)] [Π i, is_central_scalar R (M i)] : is_central_scalar R (⨁ i, M i) := dfinsupp.is_central_scalar lemma smul_apply (b : R) (v : ⨁ i, M i) (i : ι) : (b • v) i = b • (v i) := dfinsupp.smul_apply _ _ _ include dec_ι variables R ι M /-- Create the direct sum given a family `M` of `R` modules indexed over `ι`. -/ def lmk : Π s : finset ι, (Π i : (↑s : set ι), M i.val) →ₗ[R] (⨁ i, M i) := dfinsupp.lmk /-- Inclusion of each component into the direct sum. -/ def lof : Π i : ι, M i →ₗ[R] (⨁ i, M i) := dfinsupp.lsingle lemma lof_eq_of (i : ι) (b : M i) : lof R ι M i b = of M i b := rfl variables {ι M} lemma single_eq_lof (i : ι) (b : M i) : dfinsupp.single i b = lof R ι M i b := rfl /-- Scalar multiplication commutes with direct sums. -/ theorem mk_smul (s : finset ι) (c : R) (x) : mk M s (c • x) = c • mk M s x := (lmk R ι M s).map_smul c x /-- Scalar multiplication commutes with the inclusion of each component into the direct sum. -/ theorem of_smul (i : ι) (c : R) (x) : of M i (c • x) = c • of M i x := (lof R ι M i).map_smul c x variables {R} lemma support_smul [Π (i : ι) (x : M i), decidable (x ≠ 0)] (c : R) (v : ⨁ i, M i) : (c • v).support ⊆ v.support := dfinsupp.support_smul _ _ variables {N : Type u₁} [add_comm_monoid N] [module R N] variables (φ : Π i, M i →ₗ[R] N) variables (R ι N φ) /-- The linear map constructed using the universal property of the coproduct. -/ def to_module : (⨁ i, M i) →ₗ[R] N := dfinsupp.lsum ℕ φ /-- Coproducts in the categories of modules and additive monoids commute with the forgetful functor from modules to additive monoids. -/ lemma coe_to_module_eq_coe_to_add_monoid : (to_module R ι N φ : (⨁ i, M i) → N) = to_add_monoid (λ i, (φ i).to_add_monoid_hom) := rfl variables {ι N φ} /-- The map constructed using the universal property gives back the original maps when restricted to each component. -/ @[simp] lemma to_module_lof (i) (x : M i) : to_module R ι N φ (lof R ι M i x) = φ i x := to_add_monoid_of (λ i, (φ i).to_add_monoid_hom) i x variables (ψ : (⨁ i, M i) →ₗ[R] N) /-- Every linear map from a direct sum agrees with the one obtained by applying the universal property to each of its components. -/ theorem to_module.unique (f : ⨁ i, M i) : ψ f = to_module R ι N (λ i, ψ.comp $ lof R ι M i) f := to_add_monoid.unique ψ.to_add_monoid_hom f variables {ψ} {ψ' : (⨁ i, M i) →ₗ[R] N} /-- Two `linear_map`s out of a direct sum are equal if they agree on the generators. See note [partially-applied ext lemmas]. -/ @[ext] theorem linear_map_ext ⦃ψ ψ' : (⨁ i, M i) →ₗ[R] N⦄ (H : ∀ i, ψ.comp (lof R ι M i) = ψ'.comp (lof R ι M i)) : ψ = ψ' := dfinsupp.lhom_ext' H /-- The inclusion of a subset of the direct summands into a larger subset of the direct summands, as a linear map. -/ def lset_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), M i) →ₗ[R] (⨁ (i : T), M i) := to_module R _ _ $ λ i, lof R T (λ (i : subtype T), M i) ⟨i, H i.prop⟩ omit dec_ι variables (ι M) /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `⨁ i, M i` and `Π i, M i`. -/ @[simps apply] def linear_equiv_fun_on_fintype [fintype ι] : (⨁ i, M i) ≃ₗ[R] (Π i, M i) := { to_fun := coe_fn, map_add' := λ f g, by { ext, simp only [add_apply, pi.add_apply] }, map_smul' := λ c f, by { ext, simp only [dfinsupp.coe_smul, ring_hom.id_apply] }, .. dfinsupp.equiv_fun_on_fintype } variables {ι M} @[simp] lemma linear_equiv_fun_on_fintype_lof [fintype ι] [decidable_eq ι] (i : ι) (m : M i) : (linear_equiv_fun_on_fintype R ι M) (lof R ι M i m) = pi.single i m := begin ext a, change (dfinsupp.equiv_fun_on_fintype (lof R ι M i m)) a = _, convert _root_.congr_fun (dfinsupp.equiv_fun_on_fintype_single i m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single [fintype ι] [decidable_eq ι] (i : ι) (m : M i) : (linear_equiv_fun_on_fintype R ι M).symm (pi.single i m) = lof R ι M i m := begin ext a, change (dfinsupp.equiv_fun_on_fintype.symm (pi.single i m)) a = _, rw (dfinsupp.equiv_fun_on_fintype_symm_single i m), refl end @[simp] lemma linear_equiv_fun_on_fintype_symm_coe [fintype ι] (f : ⨁ i, M i) : (linear_equiv_fun_on_fintype R ι M).symm f = f := by { ext, simp [linear_equiv_fun_on_fintype], } /-- The natural linear equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def lid (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [module R M] [unique ι] : (⨁ (_ : ι), M) ≃ₗ[R] M := { .. direct_sum.id M ι, .. to_module R ι M (λ i, linear_map.id) } variables (ι M) /-- The projection map onto one component, as a linear map. -/ def component (i : ι) : (⨁ i, M i) →ₗ[R] M i := dfinsupp.lapply i variables {ι M} lemma apply_eq_component (f : ⨁ i, M i) (i : ι) : f i = component R ι M i f := rfl @[ext] lemma ext {f g : ⨁ i, M i} (h : ∀ i, component R ι M i f = component R ι M i g) : f = g := dfinsupp.ext h lemma ext_iff {f g : ⨁ i, M i} : f = g ↔ ∀ i, component R ι M i f = component R ι M i g := ⟨λ h _, by rw h, ext R⟩ include dec_ι @[simp] lemma lof_apply (i : ι) (b : M i) : ((lof R ι M i) b) i = b := dfinsupp.single_eq_same @[simp] lemma component.lof_self (i : ι) (b : M i) : component R ι M i ((lof R ι M i) b) = b := lof_apply R i b lemma component.of (i j : ι) (b : M j) : component R ι M i ((lof R ι M j) b) = if h : j = i then eq.rec_on h b else 0 := dfinsupp.single_apply omit dec_ι section congr_left variables {κ : Type*} /--Reindexing terms of a direct sum is linear.-/ def lequiv_congr_left (h : ι ≃ κ) : (⨁ i, M i) ≃ₗ[R] ⨁ k, M (h.symm k) := { map_smul' := dfinsupp.comap_domain'_smul _ _, ..equiv_congr_left h } @[simp] lemma lequiv_congr_left_apply (h : ι ≃ κ) (f : ⨁ i, M i) (k : κ) : lequiv_congr_left R h f k = f (h.symm k) := equiv_congr_left_apply _ _ _ end congr_left section sigma variables {α : ι → Type*} {δ : Π i, α i → Type w} variables [Π i j, add_comm_monoid (δ i j)] [Π i j, module R (δ i j)] /--`curry` as a linear map.-/ noncomputable def sigma_lcurry : (⨁ (i : Σ i, _), δ i.1 i.2) →ₗ[R] ⨁ i j, δ i j := { map_smul' := λ r, by convert (@dfinsupp.sigma_curry_smul _ _ _ δ _ _ _ r), ..sigma_curry } @[simp] lemma sigma_lcurry_apply (f : ⨁ (i : Σ i, _), δ i.1 i.2) (i : ι) (j : α i) : sigma_lcurry R f i j = f ⟨i, j⟩ := sigma_curry_apply f i j /--`uncurry` as a linear map.-/ def sigma_luncurry [Π i, decidable_eq (α i)] [Π i j, decidable_eq (δ i j)] : (⨁ i j, δ i j) →ₗ[R] ⨁ (i : Σ i, _), δ i.1 i.2 := { map_smul' := dfinsupp.sigma_uncurry_smul, ..sigma_uncurry } @[simp] lemma sigma_luncurry_apply [Π i, decidable_eq (α i)] [Π i j, decidable_eq (δ i j)] (f : ⨁ i j, δ i j) (i : ι) (j : α i) : sigma_luncurry R f ⟨i, j⟩ = f i j := sigma_uncurry_apply f i j /--`curry_equiv` as a linear equiv.-/ noncomputable def sigma_lcurry_equiv [Π i, decidable_eq (α i)] [Π i j, decidable_eq (δ i j)] : (⨁ (i : Σ i, _), δ i.1 i.2) ≃ₗ[R] ⨁ i j, δ i j := { ..sigma_curry_equiv, ..sigma_lcurry R } end sigma section option variables {α : option ι → Type w} [Π i, add_comm_monoid (α i)] [Π i, module R (α i)] include dec_ι /--Linear isomorphism obtained by separating the term of index `none` of a direct sum over `option ι`.-/ @[simps] noncomputable def lequiv_prod_direct_sum : (⨁ i, α i) ≃ₗ[R] α none × ⨁ i, α (some i) := { map_smul' := dfinsupp.equiv_prod_dfinsupp_smul, ..add_equiv_prod_direct_sum } end option end general section submodule section semiring variables {R : Type u} [semiring R] variables {ι : Type v} [dec_ι : decidable_eq ι] include dec_ι variables {M : Type*} [add_comm_monoid M] [module R M] variables (A : ι → submodule R M) /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `submodule R M` indexed by `ι`. This is `direct_sum.coe_add_monoid_hom` as a `linear_map`. -/ def coe_linear_map : (⨁ i, A i) →ₗ[R] M := to_module R ι M (λ i, (A i).subtype) @[simp] lemma coe_linear_map_of (i : ι) (x : A i) : direct_sum.coe_linear_map A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ variables {A} /-- If a direct sum of submodules is internal then the submodules span the module. -/ lemma is_internal.submodule_supr_eq_top (h : is_internal A) : supr A = ⊤ := begin rw [submodule.supr_eq_range_dfinsupp_lsum, linear_map.range_eq_top], exact function.bijective.surjective h, end /-- If a direct sum of submodules is internal then the submodules are independent. -/ lemma is_internal.submodule_independent (h : is_internal A) : complete_lattice.independent A := complete_lattice.independent_of_dfinsupp_lsum_injective _ h.injective /-- Given an internal direct sum decomposition of a module `M`, and a basis for each of the components of the direct sum, the disjoint union of these bases is a basis for `M`. -/ noncomputable def is_internal.collected_basis (h : is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) : basis (Σ i, α i) R M := { repr := (linear_equiv.of_bijective (direct_sum.coe_linear_map A) h).symm ≪≫ₗ (dfinsupp.map_range.linear_equiv (λ i, (v i).repr)) ≪≫ₗ (sigma_finsupp_lequiv_dfinsupp R).symm } @[simp] lemma is_internal.collected_basis_coe (h : is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) : ⇑(h.collected_basis v) = λ a : Σ i, (α i), ↑(v a.1 a.2) := begin funext a, simp only [is_internal.collected_basis, to_module, coe_linear_map, add_equiv.to_fun_eq_coe, basis.coe_of_repr, basis.repr_symm_apply, dfinsupp.lsum_apply_apply, dfinsupp.map_range.linear_equiv_apply, dfinsupp.map_range.linear_equiv_symm, dfinsupp.map_range_single, finsupp.total_single, linear_equiv.of_bijective_apply, linear_equiv.symm_symm, linear_equiv.symm_trans_apply, one_smul, sigma_finsupp_add_equiv_dfinsupp_apply, sigma_finsupp_equiv_dfinsupp_single, sigma_finsupp_lequiv_dfinsupp_apply], convert dfinsupp.sum_add_hom_single (λ i, (A i).subtype.to_add_monoid_hom) a.1 (v a.1 a.2), end lemma is_internal.collected_basis_mem (h : is_internal A) {α : ι → Type*} (v : Π i, basis (α i) R (A i)) (a : Σ i, α i) : h.collected_basis v a ∈ A a.1 := by simp /-- When indexed by only two distinct elements, `direct_sum.is_internal` implies the two submodules are complementary. Over a `ring R`, this is true as an iff, as `direct_sum.is_internal_iff_is_compl`. -/ lemma is_internal.is_compl {A : ι → submodule R M} {i j : ι} (hij : i ≠ j) (h : (set.univ : set ι) = {i, j}) (hi : is_internal A) : is_compl (A i) (A j) := ⟨hi.submodule_independent.pairwise_disjoint hij, codisjoint_iff.mpr $ eq.symm $ hi.submodule_supr_eq_top.symm.trans $ by rw [←Sup_pair, supr, ←set.image_univ, h, set.image_insert_eq, set.image_singleton]⟩ end semiring section ring variables {R : Type u} [ring R] variables {ι : Type v} [dec_ι : decidable_eq ι] include dec_ι variables {M : Type*} [add_comm_group M] [module R M] /-- Note that this is not generally true for `[semiring R]`; see `complete_lattice.independent.dfinsupp_lsum_injective` for details. -/ lemma is_internal_submodule_of_independent_of_supr_eq_top {A : ι → submodule R M} (hi : complete_lattice.independent A) (hs : supr A = ⊤) : is_internal A := ⟨hi.dfinsupp_lsum_injective, linear_map.range_eq_top.1 $ (submodule.supr_eq_range_dfinsupp_lsum _).symm.trans hs⟩ /-- `iff` version of `direct_sum.is_internal_submodule_of_independent_of_supr_eq_top`, `direct_sum.is_internal.independent`, and `direct_sum.is_internal.supr_eq_top`. -/ lemma is_internal_submodule_iff_independent_and_supr_eq_top (A : ι → submodule R M) : is_internal A ↔ complete_lattice.independent A ∧ supr A = ⊤ := ⟨λ i, ⟨i.submodule_independent, i.submodule_supr_eq_top⟩, and.rec is_internal_submodule_of_independent_of_supr_eq_top⟩ /-- If a collection of submodules has just two indices, `i` and `j`, then `direct_sum.is_internal` is equivalent to `is_compl`. -/ lemma is_internal_submodule_iff_is_compl (A : ι → submodule R M) {i j : ι} (hij : i ≠ j) (h : (set.univ : set ι) = {i, j}) : is_internal A ↔ is_compl (A i) (A j) := begin have : ∀ k, k = i ∨ k = j := λ k, by simpa using set.ext_iff.mp h k, rw [is_internal_submodule_iff_independent_and_supr_eq_top, supr, ←set.image_univ, h, set.image_insert_eq, set.image_singleton, Sup_pair, complete_lattice.independent_pair hij this], exact ⟨λ ⟨hd, ht⟩, ⟨hd, codisjoint_iff.mpr ht⟩, λ ⟨hd, ht⟩, ⟨hd, ht.eq_top⟩⟩, end /-! Now copy the lemmas for subgroup and submonoids. -/ lemma is_internal.add_submonoid_independent {M : Type*} [add_comm_monoid M] {A : ι → add_submonoid M} (h : is_internal A) : complete_lattice.independent A := complete_lattice.independent_of_dfinsupp_sum_add_hom_injective _ h.injective lemma is_internal.add_subgroup_independent {M : Type*} [add_comm_group M] {A : ι → add_subgroup M} (h : is_internal A) : complete_lattice.independent A := complete_lattice.independent_of_dfinsupp_sum_add_hom_injective' _ h.injective end ring end submodule end direct_sum
4a6509d16aef633dfb30fe3d059c371ff8e83fbf
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/linear_algebra/finsupp_vector_space.lean
854a5ad8df2da2796e6c1346ae669a843703ed98
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,058
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.mv_polynomial import linear_algebra.dimension import linear_algebra.direct_sum.finsupp import linear_algebra.finite_dimensional /-! # Linear structures on function with finite support `ι →₀ M` This file contains results on the `R`-module structure on functions of finite support from a type `ι` to an `R`-module `M`, in particular in the case that `R` is a field. Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension as well as the cardinality of finite dimensional vector spaces. ## TODO Move the second half of this file to more appropriate other files. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section ring variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply (hf i).map h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end open linear_map submodule lemma is_basis_single {φ : ι → Type*} (f : Π ι, φ ι → M) (hf : ∀i, is_basis R (f i)) : is_basis R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin split, { apply linear_independent_single, exact λ i, (hf i).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end lemma is_basis_single_one : is_basis R (λ i : ι, single i (1 : R)) := by convert (is_basis_single (λ (i : ι) (x : unit), (1 : R)) (λ i, is_basis_singleton_one R)).comp (λ i : ι, ⟨i, ()⟩) ⟨λ _ _, and.left ∘ sigma.mk.inj, λ ⟨i, ⟨⟩⟩, ⟨i, rfl⟩⟩ end ring section comm_ring variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ lemma is_basis.tensor_product {b : ι → M} (hb : is_basis R b) {c : κ → N} (hc : is_basis R c) : is_basis R (λ i : ι × κ, b i.1 ⊗ₜ[R] c i.2) := by { convert linear_equiv.is_basis is_basis_single_one ((tensor_product.congr (module_equiv_finsupp hb) (module_equiv_finsupp hc)).trans $ (finsupp_tensor_finsupp _ _ _ _ _).trans $ lcongr (equiv.refl _) (tensor_product.lid R R)).symm, ext ⟨i, k⟩, rw [function.comp_apply, linear_equiv.eq_symm_apply], simp } end comm_ring section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [module K V] lemma dim_eq : module.rank K (ι →₀ V) = cardinal.mk ι * module.rank K V := begin rcases exists_is_basis K V with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:ι, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] } end end dim end finsupp section module /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₁] [module K V₁] variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V'] [module K V'] open module lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (module.rank K V) = cardinal.lift.{w v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', rcases exists_is_basis K V with ⟨m, hm⟩, rcases exists_is_basis K V' with ⟨m', hm'⟩, rw [←cardinal.lift_inj.1 hm.mk_eq_dim, ←cardinal.lift_inj.1 hm'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨((module_equiv_finsupp hm).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hm').symm⟩, end /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim (h : module.rank K V₁ = module.rank K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv (n : ℕ) (hn : (module.rank K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end end module section module universes u open module variables (K V : Type u) [field K] [add_comm_group V] [module K V] lemma cardinal_mk_eq_cardinal_mk_field_pow_dim [finite_dimensional K V] : cardinal.mk V = cardinal.mk K ^ module.rank K V := begin rcases exists_is_basis K V with ⟨s, hs⟩, have : nonempty (fintype s), { rw [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim], exact finite_dimensional.dim_lt_omega K V }, cases this with hsf, letI := hsf, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_finite_dimensional [fintype K] [finite_dimensional K V] : cardinal.mk V < cardinal.omega := begin rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V, exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) (finite_dimensional.dim_lt_omega K V), end end module
d4da71fb5f577115a2628e6f3076e3c7328bcfe3
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/preadditive/schur.lean
b6ef90439f683e6f15c7ea5d21787d424ff90535
[ "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
6,950
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import algebra.group.ext import category_theory.simple import category_theory.linear import category_theory.endomorphism import field_theory.is_alg_closed.basic /-! # Schur's lemma We first prove the part of Schur's Lemma that holds in any preadditive category with kernels, that any nonzero morphism between simple objects is an isomorphism. Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces, over an algebraically closed field `𝕜`: the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional, and is 1-dimensional iff `X` and `Y` are isomorphic. ## Future work It might be nice to provide a `division_ring` instance on `End X` when `X` is simple. This is an easy consequence of the results here, but may take some care setting up usable instances. -/ namespace category_theory open category_theory.limits universes v u variables {C : Type u} [category.{v} C] variables [preadditive C] /-- The part of **Schur's lemma** that holds in any preadditive category with kernels: that a nonzero morphism between simple objects is an isomorphism. -/ lemma is_iso_of_hom_simple [has_kernels C] {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) : is_iso f := begin haveI : mono f := preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w), exact is_iso_of_mono_of_nonzero w end /-- As a corollary of Schur's lemma for preadditive categories, any morphism between simple objects is (exclusively) either an isomorphism or zero. -/ lemma is_iso_iff_nonzero [has_kernels C] {X Y : C} [simple.{v} X] [simple.{v} Y] (f : X ⟶ Y) : is_iso.{v} f ↔ f ≠ 0 := ⟨λ I, begin introI h, apply id_nonzero X, simp only [←is_iso.hom_inv_id f, h, zero_comp], end, λ w, is_iso_of_hom_simple w⟩ open finite_dimensional variables (𝕜 : Type*) [field 𝕜] /-- Part of **Schur's lemma** for `𝕜`-linear categories: the hom space between two non-isomorphic simple objects is 0-dimensional. -/ lemma finrank_hom_simple_simple_eq_zero_of_not_iso [has_kernels C] [linear 𝕜 C] {X Y : C} [simple.{v} X] [simple.{v} Y] (h : (X ≅ Y) → false): finrank 𝕜 (X ⟶ Y) = 0 := begin haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) (λ f, begin have p := not_congr (is_iso_iff_nonzero f), simp only [not_not, ne.def] at p, refine p.mp (λ _, by exactI h (as_iso f)), end), exact finrank_zero_of_subsingleton, end variables [is_alg_closed 𝕜] [linear 𝕜 C] -- In the proof below we have some difficulty using `I : finite_dimensional 𝕜 (X ⟶ X)` -- where we need a `finite_dimensional 𝕜 (End X)`. -- These are definitionally equal, but without eta reduction Lean can't see this. -- To get around this, we use `convert I`, -- then check the various instances agree field-by-field, -- using `ext` equipped with the following extra lemmas: local attribute [ext] module distrib_mul_action mul_action has_scalar /-- An auxiliary lemma for Schur's lemma. If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible, then `X ⟶ X` is 1-dimensional. -/ -- We prove this with the explicit `is_iso_iff_nonzero` assumption, -- rather than just `[simple X]`, as this form is useful for -- Müger's formulation of semisimplicity. lemma finrank_endomorphism_eq_one {X : C} (is_iso_iff_nonzero : ∀ f : X ⟶ X, is_iso f ↔ f ≠ 0) [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := begin have id_nonzero := (is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance), apply finrank_eq_one (𝟙 X), { exact id_nonzero, }, { intro f, haveI : nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero, obtain ⟨c, nu⟩ := @exists_spectrum_of_is_alg_closed_of_finite_dimensional 𝕜 _ _ (End X) _ _ _ (by { convert I, ext, refl, ext, refl, }) (End.of f), use c, rw [is_unit_iff_is_iso, is_iso_iff_nonzero, ne.def, not_not, sub_eq_zero, algebra.algebra_map_eq_smul_one] at nu, exact nu.symm, }, end variables [has_kernels C] /-- **Schur's lemma** for endomorphisms in `𝕜`-linear categories. -/ lemma finrank_endomorphism_simple_eq_one (X : C) [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] : finrank 𝕜 (X ⟶ X) = 1 := finrank_endomorphism_eq_one 𝕜 is_iso_iff_nonzero lemma endomorphism_simple_eq_smul_id {X : C} [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) : ∃ c : 𝕜, c • 𝟙 X = f := (finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f /-- **Schur's lemma** for `𝕜`-linear categories: if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional. See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below for the refinements when we know whether or not the simples are isomorphic. -/ -- We don't really need `[∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)]` here, -- just at least one of `[finite_dimensional 𝕜 (X ⟶ X)]` or `[finite_dimensional 𝕜 (Y ⟶ Y)]`. lemma finrank_hom_simple_simple_le_one (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) ≤ 1 := begin cases subsingleton_or_nontrivial (X ⟶ Y) with h, { resetI, convert zero_le_one, exact finrank_zero_of_subsingleton, }, { obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h, haveI fi := (is_iso_iff_nonzero f).mpr nz, apply finrank_le_one f, intro g, obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f), exact ⟨c, by simpa using w =≫ f⟩, }, end lemma finrank_hom_simple_simple_eq_one_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 1 ↔ nonempty (X ≅ Y) := begin fsplit, { intro h, rw finrank_eq_one_iff' at h, obtain ⟨f, nz, -⟩ := h, rw ←is_iso_iff_nonzero at nz, exactI ⟨as_iso f⟩, }, { rintro ⟨f⟩, have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y, have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) := finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (is_iso_iff_nonzero f.hom).mp infer_instance⟩, linarith, } end lemma finrank_hom_simple_simple_eq_zero_iff (X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] : finrank 𝕜 (X ⟶ Y) = 0 ↔ is_empty (X ≅ Y) := begin rw [← not_nonempty_iff, ← not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y)], refine ⟨λ h, by { rw h, simp, }, λ h, _⟩, have := finrank_hom_simple_simple_le_one 𝕜 X Y, interval_cases finrank 𝕜 (X ⟶ Y) with h', { exact h', }, { exact false.elim (h h'), }, end end category_theory
55494bb324a914996e1accbf86c549913dedb638
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Util/Constructions.lean
5492c2292cfab28116143e1a468594b6aabf42b3
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,998
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.Environment import Lean.MonadEnv namespace Lean @[extern "lean_mk_cases_on"] constant mkCasesOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_rec_on"] constant mkRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_no_confusion"] constant mkNoConfusionImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_below"] constant mkBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_ibelow"] constant mkIBelowImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_brec_on"] constant mkBRecOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment @[extern "lean_mk_binduction_on"] constant mkBInductionOnImp (env : Environment) (declName : @& Name) : Except KernelException Environment variables {m} [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] @[inline] private def adaptFn (f : Environment → Name → Except KernelException Environment) (declName : Name) : m Unit := do match f (← getEnv) declName with | Except.ok env => modifyEnv fun _ => env | Except.error ex => throwKernelException ex def mkCasesOn (declName : Name) : m Unit := adaptFn mkCasesOnImp declName def mkRecOn (declName : Name) : m Unit := adaptFn mkRecOnImp declName def mkNoConfusion (declName : Name) : m Unit := adaptFn mkNoConfusionImp declName def mkBelow (declName : Name) : m Unit := adaptFn mkBelowImp declName def mkIBelow (declName : Name) : m Unit := adaptFn mkIBelowImp declName def mkBRecOn (declName : Name) : m Unit := adaptFn mkBRecOnImp declName def mkBInductionOn (declName : Name) : m Unit := adaptFn mkBInductionOnImp declName end Lean
d47179c7a99a9443c66e07d606a79afbf76c8e85
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t8.lean
4083982d88cecb15bd3686dc6ef58a06971c6b1b
[ "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
152
lean
(* import("tactic.lua") *) set_option tactic::proof_state::goal_names true. theorem T (a : Bool) : a → a /\ a. apply and_intro. exact. done.
0811f16188f8ac6da92a7a866b6cc22b6e583854
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/finset.lean
384453fbe4b63a1c97964200ee1ed52ab119319b
[ "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
7,493
lean
import data.list open list setoid quot decidable nat namespace finset definition eqv {A : Type} (l₁ l₂ : list A) := ∀ a, a ∈ l₁ ↔ a ∈ l₂ infix `~` := eqv theorem eqv.refl {A : Type} (l : list A) : l ~ l := λ a, !iff.refl theorem eqv.symm {A : Type} {l₁ l₂ : list A} : l₁ ~ l₂ → l₂ ~ l₁ := λ H a, iff.symm (H a) theorem eqv.trans {A : Type} {l₁ l₂ l₃ : list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := λ H₁ H₂ a, iff.trans (H₁ a) (H₂ a) theorem eqv.is_equivalence (A : Type) : equivalence (@eqv A) := and.intro (@eqv.refl A) (and.intro (@eqv.symm A) (@eqv.trans A)) definition norep {A : Type} [H : decidable_eq A] : list A → list A | [] := [] | (x :: xs) := if x ∈ xs then norep xs else x :: norep xs definition eqv_norep {A : Type} [H : decidable_eq A] : ∀ l : list A, l ~ norep l | [] := (λ a, iff.rfl) | (x :: xs) := take y, assert ih : xs ~ norep xs, from eqv_norep xs, show y ∈ x :: xs ↔ y ∈ if x ∈ xs then norep xs else x :: norep xs, begin apply (@by_cases (x ∈ xs)), begin intro xin, rewrite (if_pos xin), apply iff.intro, {intro yinxxs, apply (or.elim (iff.mp !mem_cons_iff yinxxs)), intro yeqx, rewrite -yeqx at xin, exact (iff.mp (ih y) xin), intro yeqxs, exact (iff.mp (ih y) yeqxs)}, {intro yinnrep, show y ∈ x::xs, from or.inr (iff.mpr (ih y) yinnrep)} end, begin intro xnin, rewrite (if_neg xnin), apply iff.intro, {intro yinxxs, apply (or.elim (iff.mp !mem_cons_iff yinxxs)), intro yeqx, rewrite yeqx, apply mem_cons, intro yinxs, show y ∈ x:: norep xs, from or.inr (iff.mp (ih y) yinxs)}, {intro yinxnrep, apply (or.elim (iff.mp !mem_cons_iff yinxnrep)), intro yeqx, rewrite yeqx, apply mem_cons, intro yinrep, show y ∈ x::xs, from or.inr (iff.mpr (ih y) yinrep)} end end definition sub {A : Type} (l₁ l₂ : list A) := ∀ a, a ∈ l₁ → a ∈ l₂ infix ⊆ := sub theorem eqv_of_sub_of_sub {A : Type} {l₁ l₂ : list A} : l₁ ⊆ l₂ → l₂ ⊆ l₁ → l₁ ~ l₂ := assume h₁ h₂ a, iff.intro (h₁ a) (h₂ a) theorem sub_of_eqv_left {A : Type} {l₁ l₂ : list A} : l₁ ~ l₂ → l₁ ⊆ l₂ := assume h₁ a ainl₁, iff.mp (h₁ a) ainl₁ theorem sub_of_eqv_right {A : Type} {l₁ l₂ : list A} : l₁ ~ l₂ → l₂ ⊆ l₁ := assume h₁ a ainl₂, iff.mpr (h₁ a) ainl₂ definition sub_of_cons_sub {A : Type} {a : A} {l₁ l₂ : list A} : a :: l₁ ⊆ l₂ → l₁ ⊆ l₂ := assume s, take b, assume binl₁, s b (or.inr binl₁) definition decidable_sub [instance] {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ ⊆ l₂) | [] ys := inl (λ a h, absurd h !not_mem_nil) | (x::xs) ys := if xinys : x ∈ ys then match decidable_sub xs ys with | (inl xs_sub_ys) := inl (λ y yinxxs, or.elim (iff.mp !mem_cons_iff yinxxs) (λ yeqx, by rewrite yeqx; exact xinys) (λ yinxs, xs_sub_ys y yinxs)) | (inr nxs_sub_ys) := inr (λ h, absurd (sub_of_cons_sub h) nxs_sub_ys) end else inr (λ h, absurd (h x !mem_cons) xinys) example : [(1 : nat), 2, 3] ⊆ [1,3,4,1,2] := dec_trivial definition decidable_eqv [instance] {A : Type} [H : decidable_eq A] : ∀ l₁ l₂ : list A, decidable (l₁ ~ l₂) := take l₁ l₂ : list A, match decidable_sub l₁ l₂ with | (inl s₁) := match decidable_sub l₂ l₁ with | (inl s₂) := inl (eqv_of_sub_of_sub s₁ s₂) | (inr n₂) := inr (λ h, absurd (sub_of_eqv_right h) n₂) end | (inr n₁) := inr (λ h, absurd (sub_of_eqv_left h) n₁) end example : [(1:nat), 2, 3, 2, 2, 2] ~ [1,3,3,1,2] := dec_trivial definition finset_setoid [instance] (A : Type) : setoid (list A) := setoid.mk (@eqv A) (eqv.is_equivalence A) definition finset (A : Type) : Type := quot (finset_setoid A) definition has_decidable_eq [instance] {A : Type} [H : decidable_eq A] : ∀ s₁ s₂ : finset A, decidable (s₁ = s₂) := take s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (take l₁ l₂, match decidable_eqv l₁ l₂ with | inl e := inl (quot.sound e) | inr d := inr (λ e, absurd (quot.exact e) d) end) definition to_finset {A : Type} (l : list A) : finset A := ⟦l⟧ definition mem {A : Type} (a : A) (s : finset A) : Prop := quot.lift_on s (λ l : list A, a ∈ l) (λ l₁ l₂ r, propext (r a)) infix ∈ := mem theorem mem_list {A : Type} {a : A} {l : list A} : a ∈ l → a ∈ ⟦l⟧ := λ H, H definition empty {A : Type} : finset A := ⟦nil⟧ notation `∅` := empty definition union {A : Type} (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂ : list A, ⟦l₁ ++ l₂⟧) (λ l₁ l₂ l₃ l₄ r₁ r₂, begin apply quot.sound, intro a, apply iff.intro, begin intro inl₁l₂, apply (or.elim (mem_or_mem_of_mem_append inl₁l₂)), intro inl₁, exact (mem_append_of_mem_or_mem (or.inl (iff.mp (r₁ a) inl₁))), intro inl₂, exact (mem_append_of_mem_or_mem (or.inr (iff.mp (r₂ a) inl₂))) end, begin intro inl₃l₄, apply (or.elim (mem_or_mem_of_mem_append inl₃l₄)), intro inl₃, exact (mem_append_of_mem_or_mem (or.inl (iff.mpr (r₁ a) inl₃))), intro inl₄, exact (mem_append_of_mem_or_mem (or.inr (iff.mpr (r₂ a) inl₄))) end, end) infix `∪` := union theorem mem_union_left {A : Type} (s₁ s₂ : finset A) (a : A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.ind₂ (λ l₁ l₂ ainl₁, mem_append_left l₂ ainl₁) s₁ s₂ theorem mem_union_right {A : Type} (s₁ s₂ : finset A) (a : A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.ind₂ (λ l₁ l₂ ainl₂, mem_append_right l₁ ainl₂) s₁ s₂ theorem union_empty {A : Type} (s : finset A) : s ∪ ∅ = s := quot.induction_on s (λ l, quot.sound (λ a, by rewrite append_nil_right)) theorem empty_union {A : Type} (s : finset A) : ∅ ∪ s = s := quot.induction_on s (λ l, quot.sound (λ a, by rewrite append_nil_left)) example : to_finset ((1:nat)::2::nil) ∪ to_finset (2::3::nil) = ⟦1 :: 2 :: 2 :: 3 :: nil⟧ := rfl example : to_finset [(1:nat), 1, 2, 3] = to_finset [2, 3, 1, 2, 2, 3] := dec_trivial example : to_finset [(1:nat), 1, 4, 2, 3] ≠ to_finset [2, 3, 1, 2, 2, 3] := dec_trivial definition clean {A : Type} [H : decidable_eq A] (s : finset A) : finset A := quot.lift_on s (λ l, ⟦norep l⟧) (λ l₁ l₂ e, calc ⟦norep l₁⟧ = ⟦l₁⟧ : quot.sound (eqv_norep l₁) ... = ⟦l₂⟧ : quot.sound e ... = ⟦norep l₂⟧ : quot.sound (eqv_norep l₂)) theorem eq_clean {A : Type} [H : decidable_eq A] : ∀ s : finset A, clean s = s := take s, quot.induction_on s (λ l, eq.symm (quot.sound (eqv_norep l))) theorem eq_of_clean_eq_clean {A : Type} [H : decidable_eq A] : ∀ s₁ s₂ : finset A, clean s₁ = clean s₂ → s₁ = s₂ := take s₁ s₂, by rewrite *eq_clean; intro H; apply H example : to_finset [(1:nat), 1, 2, 3] = to_finset [1, 2, 2, 2, 3, 3] := !eq_of_clean_eq_clean rfl end finset
44d9663655c2230aa82a69994bc7caa20de6e3b9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/logic/nontrivial_auto.lean
250f40a62f317dbf27b97bdf899ec36a14a0a81c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,283
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.pi import Mathlib.data.prod import Mathlib.logic.unique import Mathlib.logic.function.basic import Mathlib.PostPort universes u_3 l u_1 u_2 u_4 namespace Mathlib /-! # Nontrivial types A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `nontrivial` formalizing this property. -/ /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class nontrivial (α : Type u_3) where exists_pair_ne : ∃ (x : α), ∃ (y : α), x ≠ y theorem nontrivial_iff {α : Type u_1} : nontrivial α ↔ ∃ (x : α), ∃ (y : α), x ≠ y := { mp := fun (h : nontrivial α) => nontrivial.exists_pair_ne, mpr := fun (h : ∃ (x : α), ∃ (y : α), x ≠ y) => nontrivial.mk h } theorem exists_pair_ne (α : Type u_1) [nontrivial α] : ∃ (x : α), ∃ (y : α), x ≠ y := nontrivial.exists_pair_ne theorem exists_ne {α : Type u_1} [nontrivial α] (x : α) : ∃ (y : α), y ≠ x := sorry -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. theorem nontrivial_of_ne {α : Type u_1} (x : α) (y : α) (h : x ≠ y) : nontrivial α := nontrivial.mk (Exists.intro x (Exists.intro y h)) -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. theorem nontrivial_of_lt {α : Type u_1} [preorder α] (x : α) (y : α) (h : x < y) : nontrivial α := nontrivial.mk (Exists.intro x (Exists.intro y (ne_of_lt h))) protected instance nontrivial.to_nonempty {α : Type u_1} [nontrivial α] : Nonempty α := sorry /-- An inhabited type is either nontrivial, or has a unique element. -/ def nontrivial_psum_unique (α : Type u_1) [Inhabited α] : psum (nontrivial α) (unique α) := dite (nontrivial α) (fun (h : nontrivial α) => psum.inl h) fun (h : ¬nontrivial α) => psum.inr (unique.mk { default := Inhabited.default } sorry) theorem subsingleton_iff {α : Type u_1} : subsingleton α ↔ ∀ (x y : α), x = y := { mp := fun (h : subsingleton α) => subsingleton.elim, mpr := fun (h : ∀ (x y : α), x = y) => subsingleton.intro h } theorem not_nontrivial_iff_subsingleton {α : Type u_1} : ¬nontrivial α ↔ subsingleton α := sorry theorem not_subsingleton (α : Type u_1) [h : nontrivial α] : ¬subsingleton α := sorry /-- A type is either a subsingleton or nontrivial. -/ theorem subsingleton_or_nontrivial (α : Type u_1) : subsingleton α ∨ nontrivial α := eq.mpr (id (Eq._oldrec (Eq.refl (subsingleton α ∨ nontrivial α)) (Eq.symm (propext not_nontrivial_iff_subsingleton)))) (eq.mpr (id (Eq._oldrec (Eq.refl (¬nontrivial α ∨ nontrivial α)) (propext (or_comm (¬nontrivial α) (nontrivial α))))) (classical.em (nontrivial α))) theorem false_of_nontrivial_of_subsingleton (α : Type u_1) [nontrivial α] [subsingleton α] : False := sorry protected instance option.nontrivial {α : Type u_1} [Nonempty α] : nontrivial (Option α) := nonempty.elim_to_inhabited fun (inst : Inhabited α) => nontrivial.mk (Exists.intro none (Exists.intro (some Inhabited.default) (id (id fun (ᾰ : none = some Inhabited.default) => option.no_confusion ᾰ)))) /-- Pushforward a `nontrivial` instance along an injective function. -/ protected theorem function.injective.nontrivial {α : Type u_1} {β : Type u_2} [nontrivial α] {f : α → β} (hf : function.injective f) : nontrivial β := sorry /-- Pullback a `nontrivial` instance along a surjective function. -/ protected theorem function.surjective.nontrivial {α : Type u_1} {β : Type u_2} [nontrivial β] {f : α → β} (hf : function.surjective f) : nontrivial α := sorry /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected theorem function.injective.exists_ne {α : Type u_1} {β : Type u_2} [nontrivial α] {f : α → β} (hf : function.injective f) (y : β) : ∃ (x : α), f x ≠ y := sorry protected instance nontrivial_prod_right {α : Type u_1} {β : Type u_2} [Nonempty α] [nontrivial β] : nontrivial (α × β) := function.surjective.nontrivial prod.snd_surjective protected instance nontrivial_prod_left {α : Type u_1} {β : Type u_2} [nontrivial α] [Nonempty β] : nontrivial (α × β) := function.surjective.nontrivial prod.fst_surjective namespace pi /-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/ theorem nontrivial_at {I : Type u_3} {f : I → Type u_4} (i' : I) [inst : ∀ (i : I), Nonempty (f i)] [nontrivial (f i')] : nontrivial ((i : I) → f i) := function.injective.nontrivial (function.update_injective (fun (i : I) => Classical.choice (inst i)) i') /-- As a convenience, provide an instance automatically if `(f (default I))` is nontrivial. If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`. -/ protected instance nontrivial {I : Type u_3} {f : I → Type u_4} [Inhabited I] [inst : ∀ (i : I), Nonempty (f i)] [nontrivial (f Inhabited.default)] : nontrivial ((i : I) → f i) := nontrivial_at Inhabited.default end pi protected instance function.nontrivial {α : Type u_1} {β : Type u_2} [h : Nonempty α] [nontrivial β] : nontrivial (α → β) := nonempty.elim h fun (a : α) => pi.nontrivial_at a protected theorem subsingleton.le {α : Type u_1} [preorder α] [subsingleton α] (x : α) (y : α) : x ≤ y := le_of_eq (subsingleton.elim x y) namespace tactic /-- Tries to generate a `nontrivial α` instance by performing case analysis on `subsingleton_or_nontrivial α`, attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute, including `subsingleton.le` and `eq_iff_true_of_subsingleton`. -/ /-- Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt` and local hypotheses. -/ end tactic namespace tactic.interactive /-- Attempts to generate a `nontrivial α` hypothesis. The tactic first looks for an instance using `apply_instance`. If the goal is an (in)equality, the type `α` is inferred from the goal. Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`. The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses, and use these to derive the `nontrivial` instance directly. Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of additional `simp` lemmas that can be passed to `nontriviality` using the syntax `nontriviality α using [lemmas]`. ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. assumption, end ``` ``` example {R : Type} [comm_ring R] {r s : R} : r * s = s * r := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. apply mul_comm, end ``` ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 := begin nontriviality R, -- there is now a `nontrivial R` hypothesis available. dec_trivial end ``` ``` def myeq {α : Type} (a b : α) : Prop := a = b example {α : Type} (a b : α) (h : a = b) : myeq a b := begin success_if_fail { nontriviality α }, -- Fails nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available assumption end ``` -/ end tactic.interactive namespace bool protected instance nontrivial : nontrivial Bool := nontrivial.mk (Exists.intro tt (Exists.intro false tt_eq_ff_eq_false)) end Mathlib
392bcebbb64919985956051f890ad3b67fa8a349
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/ring_theory/noetherian.lean
6db0d96fbd1d1cd5bb78549eed640f82c330a8cd
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,638
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [semimodule R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end /-- Finitely generated submodules are precisely compact elements in the submodule lattice -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [←finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [semimodule R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin refine rel_embedding.well_founded_iff_no_descending_seq.2 _, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.2)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.2 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range (f.cod_restrict' f.range f.mem_range_self) f.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
873a2678c21c0080116bb358c98d05e69b59fddd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF.lean
b3341af3898630382d1aadbc63e8945fde8f4c3d
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,495
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.AlphaEqv import Lean.Compiler.LCNF.Basic import Lean.Compiler.LCNF.Bind import Lean.Compiler.LCNF.Check import Lean.Compiler.LCNF.CompilerM import Lean.Compiler.LCNF.CSE import Lean.Compiler.LCNF.DependsOn import Lean.Compiler.LCNF.ElimDead import Lean.Compiler.LCNF.FixedParams import Lean.Compiler.LCNF.InferType import Lean.Compiler.LCNF.JoinPoints import Lean.Compiler.LCNF.LCtx import Lean.Compiler.LCNF.Level import Lean.Compiler.LCNF.Main import Lean.Compiler.LCNF.Passes import Lean.Compiler.LCNF.PassManager import Lean.Compiler.LCNF.PhaseExt import Lean.Compiler.LCNF.PrettyPrinter import Lean.Compiler.LCNF.PullFunDecls import Lean.Compiler.LCNF.PullLetDecls import Lean.Compiler.LCNF.ReduceJpArity import Lean.Compiler.LCNF.Simp import Lean.Compiler.LCNF.Specialize import Lean.Compiler.LCNF.SpecInfo import Lean.Compiler.LCNF.Testing import Lean.Compiler.LCNF.ToDecl import Lean.Compiler.LCNF.ToExpr import Lean.Compiler.LCNF.ToLCNF import Lean.Compiler.LCNF.Types import Lean.Compiler.LCNF.Util import Lean.Compiler.LCNF.ConfigOptions import Lean.Compiler.LCNF.ForEachExpr import Lean.Compiler.LCNF.MonoTypes import Lean.Compiler.LCNF.ToMono import Lean.Compiler.LCNF.MonadScope import Lean.Compiler.LCNF.Closure import Lean.Compiler.LCNF.LambdaLifting import Lean.Compiler.LCNF.ReduceArity
2d5f8e3a4fffe99028d55ec3e79ba91f349b7a3c
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/topology/algebra/group.lean
fad4bc533033abd6568ec967ea97ff116329d28b
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,318
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := begin have lim : tendsto has_inv.inv (𝓝 (1 : G)) (𝓝 1), { simpa only [one_inv] using tendsto_inv (1 : G) }, exact comap_eq_of_inverse _ inv_involutive.comp_self lim lim, end variable {G} @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v * w⁻¹ ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := begin refine comap_eq_of_inverse (λ y : G, y * x) _ _ _, { funext x, simp }, { rw ← mul_right_inv x, exact tendsto_id.mul tendsto_const_nhds }, { suffices : tendsto (λ y : G, y * x) (𝓝 1) (𝓝 (1 * x)), { simpa }, exact tendsto_id.mul tendsto_const_nhds } end @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, is_open_map_mul_right n s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin have : continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)) := continuous_quot_mk.comp continuous_inv, convert continuous_quotient_lift _ this, end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨continuous_fst.add continuous_snd.neg⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp (hf.prod_mk hg : _) lemma continuous_within_at.sub (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ x, f x - g x) s x := hf.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], apply inf_principal_eq_bot, rw mem_nhds_sets_iff, refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, hU.preimage (continuous_mul_left x), have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset (mem_nhds_sets (h1W x) (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), cases hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _ with t ht, swap, { intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin cases hV with g₀ hg₀, rcases is_compact.elim_finite_subcover hK (λ x : G, interior $ (λ h, x * h) ⁻¹' V) _ _ with ⟨t, ht⟩, { refine ⟨t, subset.trans ht _⟩, apply Union_subset_Union, intro g, apply Union_subset_Union, intro hg, apply interior_subset }, { intro g, apply is_open_interior }, { intros g hg, rw [mem_Union], use g₀ * g⁻¹, apply preimage_interior_subset_interior_preimage, exact continuous_const.mul continuous_id, rwa [mem_preimage, inv_mul_cancel_right] } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem_sets hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_nhds hd }, { simp only [inv_mul_cancel_right] } } end @[to_additive] lemma nhds_is_mul_hom : is_mul_hom (λx:G, 𝓝 x) := ⟨λ_ _, nhds_mul _ _⟩ end end filter_mul
2ef0c33dfde25917e4156e0ef8ade48eb706e6a2
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/selection.lean
95b477ddd5da3b059376ec96d502ae82ffd5ed4f
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
4,086
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import super.prover_state open native namespace super meta def simple_selection_strategy (f : term_order → clause → list ℕ) : literal_selection_strategy | dc := do gt ← get_term_order, pure $ if dc.selected.empty ∧ dc.cls.num_literals > 0 then { selected := f gt dc.cls, ..dc } else dc meta def dumb_selection : literal_selection_strategy := simple_selection_strategy $ λ gt c, match c.literals.zip_with_index.filter (λ l : literal × ℕ, l.1.is_neg) with | [] := list.range c.num_literals | neg_lit :: _ := [neg_lit.2] end meta def selection21 : literal_selection_strategy := simple_selection_strategy $ λ gt c, list.map prod.snd $ let lits := c.literals.zip_with_index in let maximal_lits := lits.filter_maximal $ λ i j : literal × ℕ, gt i.1.formula j.1.formula in if maximal_lits.length = 1 then maximal_lits else let neg_lits := lits.filter $ λ i : literal × ℕ, i.1.is_neg, maximal_neg_lits := neg_lits.filter_maximal $ λ i j : literal × ℕ, gt i.1.formula j.1.formula in if ¬ maximal_neg_lits.empty then maximal_neg_lits.take 1 else maximal_lits meta def selection22 : literal_selection_strategy := simple_selection_strategy $ λ gt c, list.map prod.snd $ let lits := c.literals.zip_with_index in let maximal_lits := lits.filter_maximal $ λ i j : literal × ℕ, gt i.1.formula j.1.formula, maximal_lits_neg := maximal_lits.filter $ λ i : literal × ℕ, i.1.is_neg in if ¬ maximal_lits_neg.empty then list.take 1 maximal_lits_neg else maximal_lits def sum {α} [has_zero α] [has_add α] : list α → α | [] := 0 | (x::xs) := x + sum xs section open expr meta def expr_size : expr → nat | (var _) := 1 | (sort _) := 1 | (const _ _) := 1 | (mvar n pp_n t) := 1 | (local_const _ _ _ _) := 1 | (app a b) := expr_size a + expr_size b | (lam _ _ d b) := 1 + expr_size b | (pi _ _ d b) := 1 + expr_size b | (elet _ t v b) := 1 + expr_size v + expr_size b | (macro _ _) := 1 end meta def clause_weight (c : derived_clause) : nat := sum (c.cls.literals.map (λ l : literal, expr_size l.formula + if l.is_pos then 10 else 1)) def find_minimal_by_core {α β} [has_lt β] [decidable_rel ((<) : β → β → Prop)] (f : α → β) : list α → option α → option α | [] min := min | (x::xs) none := find_minimal_by_core xs x | (x::xs) (some y) := find_minimal_by_core xs $ if f x < f y then x else y def find_minimal_by {α β} [has_lt β] [decidable_rel ((<) : β → β → Prop)] (xs : list α) (f : α → β) : option α := find_minimal_by_core f xs none meta def age_of_clause_id : name → ℕ | (name.mk_numeral i _) := unsigned.to_nat i | _ := 0 local attribute [instance] def prod.has_lt {α β} [has_lt α] [has_lt β] : has_lt (α × β) := ⟨λ s t, s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩ local attribute [instance] def prod_has_decidable_lt {α β} [has_lt α] [has_lt β] [decidable_eq α] [decidable_eq β] [decidable_rel ((<) : α → α → Prop)] [decidable_rel ((<) : β → β → Prop)] : Π s t : α × β, decidable (s < t) := λ t s, or.decidable meta def find_minimal_weight (passive : rb_map clause_id derived_clause) : clause_id := (derived_clause.id <$> find_minimal_by passive.values (λ c, (clause_weight c, c.id))) .get_or_else undefined meta def find_minimal_age (passive : rb_map clause_id derived_clause) : clause_id := (derived_clause.id <$> find_minimal_by passive.values (λ c, c.id)) .get_or_else undefined meta def weight_clause_selection : clause_selection_strategy | iter := do state ← get, return $ find_minimal_weight state.passive meta def oldest_clause_selection : clause_selection_strategy | iter := do state ← get, return $ find_minimal_age state.passive meta def age_weight_clause_selection (thr mod : ℕ) : clause_selection_strategy | iter := if iter % mod < thr then weight_clause_selection iter else oldest_clause_selection iter end super
a76a547a8b4457e1074027622761d9060fa4c595
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/big_operators/basic.lean
d599a0b842b06c64413d6a2bbae98c5d17cebcb9
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
48,163
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.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl end finset /- ## Operator precedence of `∏` and `∑` There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [semiring β] [semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : (∑ x in s, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.image sum.inl ∪ t.image sum.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_image, prod_image], { simp only [sum.elim_inl, sum.elim_inr] }, { exact λ _ _ _ _, sum.inr.inj }, { exact λ _ _ _ _, sum.inl.inj }, { rintros i hi, erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩, cases H } end @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bind t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `prod_product`. -/ @[to_additive] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bind (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bind ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bind $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bind_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bind $ λ x' hx y' hy hne, _).symm, rw [disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : (∏ x in s, g (f x)) = g (∏ x in s, f x) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λx, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) : (∑ x in range (n + 1), f x) = f n + (∑ x in range n, f x) := by rw [range_succ, sum_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (∏ x in range (n + 1), f x) = f n * (∏ x in range n, f x) := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[to_additive] lemma prod_range_zero (f : ℕ → β) : (∏ k in range 0, f k) = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (∏ k in range 1, f k) = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (∑ k in range 1, f k) = f 0 := @prod_range_one (multiplicative δ) _ f attribute [to_additive finset.sum_range_one] prod_range_one open multiset lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := begin apply s.induction_on, { simp only [prod_const_one, count_zero, prod_zero, pow_zero, map_zero] }, intros a s ih, simp only [prod_cons, map_cons, to_finset_cons, ih], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx end lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw map_id } /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := begin classical, induction s using finset.induction with x hx s hs, simpa, rw finset.prod_insert, swap, assumption, apply p_mul, apply p_s, simp, apply hs, intros a ha, apply p_s, simp [ha], end /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by apply @sum_range_sub (additive M) @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by apply @sum_range_sub' (additive M) /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b | 0 := rfl | (n+1) := by simp lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : (∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) -- `to_additive` fails on this lemma, so we prove it manually below lemma prod_flip {n : ℕ} (f : ℕ → β) : (∏ r in range (n + 1), f (n - r)) = (∏ k in range (n + 1), f k) := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : f i * (∏ x in s \ {i}, f x) = ∏ x in s, f x := by { convert s.prod_inter_mul_prod_diff {i} f, simp [h] } /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λy, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin suffices : ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y = (∏ x in s, f x), { rw [←this, ←finset.prod_eq_one], intros xbar xbar_in_s, rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s }, apply finset.prod_image' f, intros, refl end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum. -/ lemma eq_of_card_le_one_of_sum_eq [add_comm_monoid γ] {s : finset α} (hc : s.card ≤ 1) {f : α → γ} {b : γ} (h : ∑ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw sum_singleton at h, exact h } end attribute [to_additive eq_of_card_le_one_of_sum_eq] eq_of_card_le_one_of_prod_eq /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, apply prod_subset sdiff_subset_self, intros x hx hnx, rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [← mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n •ℕ (f x)) = n •ℕ ((∑ x in s, f x)) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card •ℕ b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] @[norm_cast] lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card •ℕ (f b) := @prod_comp _ (multiplicative β) _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) : (∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) := @prod_flip (multiplicative β) _ _ _ attribute [to_additive] prod_flip section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = ∑ u in s, card (t u) := calc (s.bind t).card = ∑ i in s.bind t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bind h ... = ∑ u in s, card (t u) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := (s.sum_hom (gsmul z)).symm @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by haveI := classical.dec_eq α; calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero section comm_group_with_zero variables [comm_group_with_zero β] @[simp] lemma prod_inv_distrib' : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := begin classical, by_cases h : ∃ x ∈ s, f x = 0, { simpa [prod_eq_zero_iff.mpr h, prod_eq_zero_iff] using h }, { push_neg at h, have h' := prod_ne_zero_iff.mpr h, have hf : ∀ x ∈ s, (f x)⁻¹ * f x = 1 := λ x hx, inv_mul_cancel (h x hx), apply mul_right_cancel' h', simp [h, h', ← finset.prod_mul_distrib, prod_congr rfl hf] } end end comm_group_with_zero end finset namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } lemma to_finset_sum_count_smul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a •ℕ (a ::ₘ 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s •ℕ (b ::ₘ 0)), { rw [singleton_coe, count_smul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_smul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_smul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k •ℕ u := begin use ∑ a in s.to_finset, (s.count a / k) •ℕ (a ::ₘ 0), have h₂ : ∑ (x : α) in s.to_finset, k •ℕ (count x s / k •ℕ (x ::ₘ 0)) = ∑ (x : α) in s.to_finset, count x s •ℕ (x ::ₘ 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_smul_eq] end end multiset @[simp, norm_cast] lemma nat.coe_prod {R : Type*} [comm_semiring R] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (nat.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma int.coe_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → units M) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _
a6394219ffefc964308c757905dab5e8c63af2e9
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/specific_limits.lean
2db687a60b992c4ae4269486d265e2a682c2148e
[ "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
25,284
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 A collection of specific limit computations. -/ import analysis.normed_space.basic import algebra.geom_sum import topology.instances.ennreal import tactic.ring_exp noncomputable theory open_locale classical topological_space open classical function filter finset metric open_locale big_operators variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp (tendsto_coe_nat_real_at_top_iff.2 tendsto_id) lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : nnreal)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : nnreal) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := nat.sub_add_cancel (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h) lemma lim_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) := lim_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top := (tendsto_inv_zero_at_top.comp lim_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm lemma tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := by_cases (assume : r = 0, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, this, tendsto_const_nhds]) (assume : r ≠ 0, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv (lt_of_le_of_ne h₁ this.symm) h₂), tendsto.congr' (univ_mem_sets' $ by simp *) this) lemma geom_lt {u : ℕ → ℝ} {k : ℝ} (hk : 0 < k) {n : ℕ} (h : ∀ m ≤ n, k*u m < u (m + 1)) : k^(n + 1) *u 0 < u (n + 1) := begin induction n with n ih, { simpa using h 0 (le_refl _) }, have : (∀ (m : ℕ), m ≤ n → k * u m < u (m + 1)), intros m hm, apply h, exact nat.le_succ_of_le hm, specialize ih this, change k ^ (n + 2) * u 0 < u (n + 2), replace h : k * u (n + 1) < u (n + 2) := h (n+1) (le_refl _), calc k ^ (n + 2) * u 0 = k*(k ^ (n + 1) * u 0) : by ring_exp ... < k*(u (n + 1)) : mul_lt_mul_of_pos_left ih hk ... < u (n + 2) : h, end /-- If a sequence `v` of real numbers satisfies `k*v n < v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_lt {v : ℕ → ℝ} {k : ℝ} (h₀ : 0 < v 0) (hk : 1 < k) (hu : ∀ n, k*v n < v (n+1)) : tendsto v at_top at_top := begin apply tendsto_at_top_mono, show ∀ n, k^n*v 0 ≤ v n, { intro n, induction n with n ih, { simp }, calc k ^ (n + 1) * v 0 = k*(k^n*v 0) : by ring_exp ... ≤ k*v n : mul_le_mul_of_nonneg_left ih (by linarith) ... ≤ v (n + 1) : le_of_lt (hu n) }, apply tendsto_at_top_mul_right h₀, exact tendsto_pow_at_top_at_top_of_one_lt hk, end lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : nnreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have r + -1 ≠ 0, by rw [←sub_eq_add_neg, ne, sub_eq_iff_eq_add]; simp; assumption, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a := (has_sum_geometric_two' a).tsum_eq lemma nnreal.has_sum_geometric {r : nnreal} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : nnreal} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : nnreal} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr, calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) } end variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl, rw [has_sum_iff_tendsto_nat_of_summable_norm, B], { simpa [geom_sum, xi_ne_one, neg_inv] using A }, { simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h end geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [ennreal.div_def, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [ennreal.div_def, ennreal.inv_pow] at hu, rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin have h0 : 0 ≤ C, by simpa using le_trans dist_nonneg (hu 0), rcases eq_or_lt_of_le h0 with rfl | Cpos, { simp [has_sum_zero] }, { have rnonneg: r ≥ 0, from nonneg_of_mul_nonneg_left (by simpa only [pow_one] using le_trans dist_nonneg (hu 1)) Cpos, refine has_sum.mul_left C _, by simpa using has_sum_geometric_of_lt_1 rnonneg hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm], symmetry, exact ((has_sum_geometric_two' C).mul_right _).tsum_eq end end le_geometric section summable_le_geometric variables [normed_group α] {r C : ℝ} {f : ℕ → α} lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg], convert hf n, rw [neg_sub, add_sub_cancel] end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥(∑' (n:ℕ), x ^ n)∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥(∑' (b : ℕ), (λ n, x ^ (n + 1)) b)∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' (i:ℕ), x ^ i) * (1 - x) = 1 := begin have := has_sum_of_bounded_monoid_hom_of_summable (normed_ring.summable_geometric_of_norm_lt_1 x h) (∥1 - x∥) (mul_right_bound (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, geom_series_def, finset.sum_mul], simp, end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * (∑' (i:ℕ), x ^ i) = 1 := begin have := has_sum_of_bounded_monoid_hom_of_summable (normed_ring.summable_geometric_of_norm_lt_1 x h) (∥1 - x∥) (mul_left_bound (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, geom_series_def, finset.mul_sum], simp, end end normed_ring_geometric /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos two_pos _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end namespace nnreal theorem exists_pos_sum_of_encodable {ε : nnreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := dense hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → nnreal, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε := begin rcases dense hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal /-! ### Harmonic series Here we define the harmonic series and prove some basic lemmas about it, leading to a proof of its divergence to +∞ -/ /-- The harmonic series `1 + 1/2 + 1/3 + ... + 1/n`-/ def harmonic_series (n : ℕ) : ℝ := ∑ i in range n, 1/(i+1 : ℝ) lemma mono_harmonic : monotone harmonic_series := begin intros p q hpq, apply sum_le_sum_of_subset_of_nonneg, rwa range_subset, intros x h _, exact le_of_lt nat.one_div_pos_of_nat, end lemma half_le_harmonic_double_sub_harmonic (n : ℕ) (hn : 0 < n) : 1/2 ≤ harmonic_series (2*n) - harmonic_series n := begin suffices : harmonic_series n + 1 / 2 ≤ harmonic_series (n + n), { rw two_mul, linarith }, have : harmonic_series n + ∑ k in Ico n (n + n), 1/(k + 1 : ℝ) = harmonic_series (n + n) := sum_range_add_sum_Ico _ (show n ≤ n+n, by linarith), rw [← this, add_le_add_iff_left], have : ∑ k in Ico n (n + n), 1/(n+n : ℝ) = 1/2, { have : (n : ℝ) + n ≠ 0, { norm_cast, linarith }, rw [sum_const, Ico.card], field_simp [this], ring }, rw ← this, apply sum_le_sum, intros x hx, rw one_div_le_one_div, { exact_mod_cast nat.succ_le_of_lt (Ico.mem.mp hx).2 }, { norm_cast, linarith }, { exact_mod_cast nat.zero_lt_succ x } end lemma self_div_two_le_harmonic_two_pow (n : ℕ) : (n / 2 : ℝ) ≤ harmonic_series (2^n) := begin induction n with n hn, unfold harmonic_series, simp only [one_div, nat.cast_zero, zero_div, nat.cast_succ, sum_singleton, inv_one, zero_add, pow_zero, range_one, zero_le_one], have : harmonic_series (2^n) + 1 / 2 ≤ harmonic_series (2^(n+1)), { have := half_le_harmonic_double_sub_harmonic (2^n) (by {apply pow_pos, linarith}), rw [nat.mul_comm, ← pow_succ'] at this, linarith }, apply le_trans _ this, rw (show (n.succ / 2 : ℝ) = (n/2 : ℝ) + (1/2), by field_simp), linarith, end /-- The harmonic series diverges to +∞ -/ theorem harmonic_tendsto_at_top : tendsto harmonic_series at_top at_top := begin suffices : tendsto (λ n : ℕ, harmonic_series (2^n)) at_top at_top, by { exact tendsto_at_top_of_monotone_of_subseq mono_harmonic this }, apply tendsto_at_top_mono self_div_two_le_harmonic_two_pow, apply tendsto_at_top_div, norm_num, exact tendsto_coe_nat_real_at_top_at_top end
dbe1041dacc6764a85f206b7552a21a79a5dbd3c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/intervals/disjoint.lean
c649e78d80052191c7685f5b0c458c50cff0cd4d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,992
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yury Kudryashov -/ import data.set.lattice /-! # Extra lemmas about intervals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas about intervals that cannot be included into `data.set.intervals.basic` because this would create an `import` cycle. Namely, lemmas in this file can use definitions from `data.set.lattice`, including `disjoint`. -/ universes u v w variables {ι : Sort u} {α : Type v} {β : Type w} open set order_dual (to_dual) namespace set section preorder variables [preorder α] {a b c : α} @[simp] lemma Iic_disjoint_Ioi (h : a ≤ b) : disjoint (Iic a) (Ioi b) := disjoint_left.mpr $ λ x ha hb, (h.trans_lt hb).not_le ha @[simp] lemma Iic_disjoint_Ioc (h : a ≤ b) : disjoint (Iic a) (Ioc b c) := (Iic_disjoint_Ioi h).mono le_rfl (λ _, and.left) @[simp] lemma Ioc_disjoint_Ioc_same {a b c : α} : disjoint (Ioc a b) (Ioc b c) := (Iic_disjoint_Ioc (le_refl b)).mono (λ _, and.right) le_rfl @[simp] lemma Ico_disjoint_Ico_same {a b c : α} : disjoint (Ico a b) (Ico b c) := disjoint_left.mpr $ λ x hab hbc, hab.2.not_le hbc.1 @[simp] lemma Ici_disjoint_Iic : disjoint (Ici a) (Iic b) ↔ ¬(a ≤ b) := by rw [set.disjoint_iff_inter_eq_empty, Ici_inter_Iic, Icc_eq_empty_iff] @[simp] lemma Iic_disjoint_Ici : disjoint (Iic a) (Ici b) ↔ ¬(b ≤ a) := disjoint.comm.trans Ici_disjoint_Iic @[simp] lemma Union_Iic : (⋃ a : α, Iic a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, right_mem_Iic⟩ @[simp] lemma Union_Ici : (⋃ a : α, Ici a) = univ := Union_eq_univ_iff.2 $ λ x, ⟨x, left_mem_Ici⟩ @[simp] lemma Union_Icc_right (a : α) : (⋃ b, Icc a b) = Ici a := by simp only [← Ici_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Ioc_right (a : α) : (⋃ b, Ioc a b) = Ioi a := by simp only [← Ioi_inter_Iic, ← inter_Union, Union_Iic, inter_univ] @[simp] lemma Union_Icc_left (b : α) : (⋃ a, Icc a b) = Iic b := by simp only [← Ici_inter_Iic, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Ico_left (b : α) : (⋃ a, Ico a b) = Iio b := by simp only [← Ici_inter_Iio, ← Union_inter, Union_Ici, univ_inter] @[simp] lemma Union_Iio [no_max_order α] : (⋃ a : α, Iio a) = univ := Union_eq_univ_iff.2 exists_gt @[simp] lemma Union_Ioi [no_min_order α] : (⋃ a : α, Ioi a) = univ := Union_eq_univ_iff.2 exists_lt @[simp] lemma Union_Ico_right [no_max_order α] (a : α) : (⋃ b, Ico a b) = Ici a := by simp only [← Ici_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioo_right [no_max_order α] (a : α) : (⋃ b, Ioo a b) = Ioi a := by simp only [← Ioi_inter_Iio, ← inter_Union, Union_Iio, inter_univ] @[simp] lemma Union_Ioc_left [no_min_order α] (b : α) : (⋃ a, Ioc a b) = Iic b := by simp only [← Ioi_inter_Iic, ← Union_inter, Union_Ioi, univ_inter] @[simp] lemma Union_Ioo_left [no_min_order α] (b : α) : (⋃ a, Ioo a b) = Iio b := by simp only [← Ioi_inter_Iio, ← Union_inter, Union_Ioi, univ_inter] end preorder section linear_order variables [linear_order α] {a₁ a₂ b₁ b₂ : α} @[simp] lemma Ico_disjoint_Ico : disjoint (Ico a₁ a₂) (Ico b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := by simp_rw [set.disjoint_iff_inter_eq_empty, Ico_inter_Ico, Ico_eq_empty_iff, inf_eq_min, sup_eq_max, not_lt] @[simp] lemma Ioc_disjoint_Ioc : disjoint (Ioc a₁ a₂) (Ioc b₁ b₂) ↔ min a₂ b₂ ≤ max a₁ b₁ := have h : _ ↔ min (to_dual a₁) (to_dual b₁) ≤ max (to_dual a₂) (to_dual b₂) := Ico_disjoint_Ico, by simpa only [dual_Ico] using h /-- If two half-open intervals are disjoint and the endpoint of one lies in the other, then it must be equal to the endpoint of the other. -/ lemma eq_of_Ico_disjoint {x₁ x₂ y₁ y₂ : α} (h : disjoint (Ico x₁ x₂) (Ico y₁ y₂)) (hx : x₁ < x₂) (h2 : x₂ ∈ Ico y₁ y₂) : y₁ = x₂ := begin rw [Ico_disjoint_Ico, min_eq_left (le_of_lt h2.2), le_max_iff] at h, apply le_antisymm h2.1, exact h.elim (λ h, absurd hx (not_lt_of_le h)) id end @[simp] lemma Union_Ico_eq_Iio_self_iff {f : ι → α} {a : α} : (⋃ i, Ico (f i) a) = Iio a ↔ ∀ x < a, ∃ i, f i ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma Union_Ioc_eq_Ioi_self_iff {f : ι → α} {a : α} : (⋃ i, Ioc a (f i)) = Ioi a ↔ ∀ x, a < x → ∃ i, x ≤ f i := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] @[simp] lemma bUnion_Ico_eq_Iio_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ico (f i hi) a) = Iio a ↔ ∀ x < a, ∃ i hi, f i hi ≤ x := by simp [← Ici_inter_Iio, ← Union_inter, subset_def] @[simp] lemma bUnion_Ioc_eq_Ioi_self_iff {p : ι → Prop} {f : Π i, p i → α} {a : α} : (⋃ i (hi : p i), Ioc a (f i hi)) = Ioi a ↔ ∀ x, a < x → ∃ i hi, x ≤ f i hi := by simp [← Ioi_inter_Iic, ← inter_Union, subset_def] end linear_order end set section Union_Ixx variables [linear_order α] {s : set α} {a : α} {f : ι → α} lemma is_glb.bUnion_Ioi_eq (h : is_glb s a) : (⋃ x ∈ s, Ioi x) = Ioi a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ioi_subset_Ioi (h.1 hx) }, { rcases h.exists_between hx with ⟨y, hys, hay, hyx⟩, exact mem_bUnion hys hyx } end lemma is_glb.Union_Ioi_eq (h : is_glb (range f) a) : (⋃ x, Ioi (f x)) = Ioi a := bUnion_range.symm.trans h.bUnion_Ioi_eq lemma is_lub.bUnion_Iio_eq (h : is_lub s a) : (⋃ x ∈ s, Iio x) = Iio a := h.dual.bUnion_Ioi_eq lemma is_lub.Union_Iio_eq (h : is_lub (range f) a) : (⋃ x, Iio (f x)) = Iio a := h.dual.Union_Ioi_eq lemma is_glb.bUnion_Ici_eq_Ioi (a_glb : is_glb s a) (a_not_mem : a ∉ s) : (⋃ x ∈ s, Ici x) = Ioi a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ici_subset_Ioi.mpr (lt_of_le_of_ne (a_glb.1 hx) (λ h, (h ▸ a_not_mem) hx)), }, { rcases a_glb.exists_between hx with ⟨y, hys, hay, hyx⟩, apply mem_Union₂.mpr , refine ⟨y, hys, hyx.le⟩, }, end lemma is_glb.bUnion_Ici_eq_Ici (a_glb : is_glb s a) (a_mem : a ∈ s) : (⋃ x ∈ s, Ici x) = Ici a := begin refine (Union₂_subset $ λ x hx, _).antisymm (λ x hx, _), { exact Ici_subset_Ici.mpr (mem_lower_bounds.mp a_glb.1 x hx), }, { apply mem_Union₂.mpr, refine ⟨a, a_mem, hx⟩, }, end lemma is_lub.bUnion_Iic_eq_Iio (a_lub : is_lub s a) (a_not_mem : a ∉ s) : (⋃ x ∈ s, Iic x) = Iio a := a_lub.dual.bUnion_Ici_eq_Ioi a_not_mem lemma is_lub.bUnion_Iic_eq_Iic (a_lub : is_lub s a) (a_mem : a ∈ s) : (⋃ x ∈ s, Iic x) = Iic a := a_lub.dual.bUnion_Ici_eq_Ici a_mem lemma Union_Ici_eq_Ioi_infi {R : Type*} [complete_linear_order R] {f : ι → R} (no_least_elem : (⨅ i, f i) ∉ range f) : (⋃ (i : ι), Ici (f i)) = Ioi (⨅ i, f i) := by simp only [← is_glb.bUnion_Ici_eq_Ioi (@is_glb_infi _ _ _ f) no_least_elem, mem_range, Union_exists, Union_Union_eq'] lemma Union_Iic_eq_Iio_supr {R : Type*} [complete_linear_order R] {f : ι → R} (no_greatest_elem : (⨆ i, f i) ∉ range f) : (⋃ (i : ι), Iic (f i)) = Iio (⨆ i, f i) := @Union_Ici_eq_Ioi_infi ι (order_dual R) _ f no_greatest_elem lemma Union_Ici_eq_Ici_infi {R : Type*} [complete_linear_order R] {f : ι → R} (has_least_elem : (⨅ i, f i) ∈ range f) : (⋃ (i : ι), Ici (f i)) = Ici (⨅ i, f i) := by simp only [← is_glb.bUnion_Ici_eq_Ici (@is_glb_infi _ _ _ f) has_least_elem, mem_range, Union_exists, Union_Union_eq'] lemma Union_Iic_eq_Iic_supr {R : Type*} [complete_linear_order R] {f : ι → R} (has_greatest_elem : (⨆ i, f i) ∈ range f) : (⋃ (i : ι), Iic (f i)) = Iic (⨆ i, f i) := @Union_Ici_eq_Ici_infi ι (order_dual R) _ f has_greatest_elem end Union_Ixx
4347eb09372d43adc6a3539bf82fc787601205a9
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/funext.lean
761feefe916df87efeb9780a34c3f8b14647a06e
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,199
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Extensional equality for functions, and a proof of function extensionality from quotients. -/ prelude import init.quot init.logic namespace function variables {A : Type} {B : A → Type} protected definition equiv (f₁ f₂ : Πx : A, B x) : Prop := ∀x, f₁ x = f₂ x namespace equiv_notation infix `~` := function.equiv end equiv_notation open equiv_notation protected theorem equiv.refl (f : Πx : A, B x) : f ~ f := take x, rfl protected theorem equiv.symm {f₁ f₂ : Πx: A, B x} : f₁ ~ f₂ → f₂ ~ f₁ := λH x, eq.symm (H x) protected theorem equiv.trans {f₁ f₂ f₃ : Πx: A, B x} : f₁ ~ f₂ → f₂ ~ f₃ → f₁ ~ f₃ := λH₁ H₂ x, eq.trans (H₁ x) (H₂ x) protected theorem equiv.is_equivalence (A : Type) (B : A → Type) : equivalence (@function.equiv A B) := mk_equivalence (@function.equiv A B) (@equiv.refl A B) (@equiv.symm A B) (@equiv.trans A B) end function section open quot variables {A : Type} {B : A → Type} private definition fun_setoid [instance] (A : Type) (B : A → Type) : setoid (Πx : A, B x) := setoid.mk (@function.equiv A B) (function.equiv.is_equivalence A B) private definition extfun (A : Type) (B : A → Type) : Type := quot (fun_setoid A B) private definition fun_to_extfun (f : Πx : A, B x) : extfun A B := ⟦f⟧ private definition extfun_app (f : extfun A B) : Πx : A, B x := take x, quot.lift_on f (λf : Πx : A, B x, f x) (λf₁ f₂ H, H x) theorem funext {f₁ f₂ : Πx : A, B x} : (∀x, f₁ x = f₂ x) → f₁ = f₂ := assume H, calc f₁ = extfun_app ⟦f₁⟧ : rfl ... = extfun_app ⟦f₂⟧ : {sound H} ... = f₂ : rfl end attribute funext [intro!] open function.equiv_notation definition subsingleton_pi [instance] {A : Type} {B : A → Type} (H : ∀ a, subsingleton (B a)) : subsingleton (Π a, B a) := subsingleton.intro (take f₁ f₂, have eqv : f₁ ~ f₂, from take a, subsingleton.elim (f₁ a) (f₂ a), funext eqv)
4a209fd8dedba420383415fdf1af17993d6aa461
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/induction_tac1.lean
f09f1fb6668520f170b33a8c8df35fde80df2385
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
608
lean
open tactic example (p q : Prop) : p ∨ q → q ∨ p := by do H ← intro `H, induction H [`Hp, `Hq], trace_state, constructor_idx 2, assumption, constructor_idx 1, assumption print "-----" open nat example (n : ℕ) : n = 0 ∨ n = succ (pred n) := by do n ← get_local `n, induction n [`n', `Hind], trace_state, constructor_idx 1, reflexivity, constructor_idx 2, reflexivity, return () print "-----" example (n : ℕ) (H : n ≠ 0) : n > 0 → n = succ (pred n) := by do n ← get_local `n, induction n [], trace_state, intro `H1, contradiction, intros, reflexivity
c05d6c2a4e9f638b29eff09df1c312193948584f
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0209.lean
cafaa964cca06e7f9c9107407b422f8ae4cfd19b
[]
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
13
lean
#check list
8d62eabc2171dcf80f6edf6d51d93b338ed07c57
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/ToString.lean
e5d7e81c7977510856f6e724bce4711d12b5f961
[ "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
235
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.ToString.Basic import Init.Data.ToString.Macro
45f9a1ff21cd24eabf566a02701d5d8587d1873b
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/Closure.lean
fb16300a5486449afdb68b948eaadf27d13bfcac
[ "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
14,678
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 Std.ShareCommon import Lean.MetavarContext import Lean.Environment import Lean.Util.FoldConsts import Lean.Meta.Basic import Lean.Meta.Check /- This module provides functions for "closing" open terms and creating auxiliary definitions. Here, we say a term is "open" if it contains free/meta-variables. The "closure" is performed by lambda abstracting the free/meta-variables. Recall that in dependent type theory lambda abstracting a let-variable may produce type incorrect terms. For example, given the context ```lean (n : Nat := 20) (x : Vector α n) (y : Vector α 20) ``` the term `x = y` is correct. However, its closure using lambda abstractions is not. ```lean fun (n : Nat) (x : Vector α n) (y : Vector α 20) => x = y ``` A previous version of this module would address this issue by always use let-expressions to abstract let-vars. In the example above, it would produce ```lean let n : Nat := 20; fun (x : Vector α n) (y : Vector α 20) => x = y ``` This approach produces correct result, but produces unsatisfactory results when we want to create auxiliary definitions. For example, consider the context ```lean (x : Nat) (y : Nat := fact x) ``` and the term `h (g y)`, now suppose we want to create an auxiliary definition for `y`. The previous version of this module would compute the auxiliary definition ```lean def aux := fun (x : Nat) => let y : Nat := fact x; h (g y) ``` and would return the term `aux x` as a substitute for `h (g y)`. This is correct, but we will re-evaluate `fact x` whenever we use `aux`. In this module, we produce ```lean def aux := fun (y : Nat) => h (g y) ``` Note that in this particular case, it is safe to lambda abstract the let-varible `y`. This module uses the following approach to decide whether it is safe or not to lambda abstract a let-variable. 1) We enable zeta-expansion tracking in `MetaM`. That is, whenever we perform type checking if a let-variable needs to zeta expanded, we store it in the set `zetaFVarIds`. We say a let-variable is zeta expanded when we replace it with its value. 2) We use the `MetaM` type checker `check` to type check the expression we want to close, and the type of the binders. 3) If a let-variable is not in `zetaFVarIds`, we lambda abstract it. Remark: We still use let-expressions for let-variables in `zetaFVarIds`, but we move the `let` inside the lambdas. The idea is to make sure the auxiliary definition does not have an interleaving of `lambda` and `let` expressions. Thus, if the let-variable occurs in the type of one of the lambdas, we simply zeta-expand it there. As a final example consider the context ```lean (x_1 : Nat) (x_2 : Nat) (x_3 : Nat) (x : Nat := fact (10 + x_1 + x_2 + x_3)) (ty : Type := Nat → Nat) (f : ty := fun x => x) (n : Nat := 20) (z : f 10) ``` and we use this module to compute an auxiliary definition for the term ```lean (let y : { v : Nat // v = n } := ⟨20, rfl⟩; y.1 + n + f x, z + 10) ``` we obtain ```lean def aux (x : Nat) (f : Nat → Nat) (z : Nat) : Nat×Nat := let n : Nat := 20; (let y : {v // v=n} := {val := 20, property := ex._proof_1}; y.val+n+f x, z+10) ``` BTW, this module also provides the `zeta : Bool` flag. When set to true, it expands all let-variables occurring in the target expression. -/ namespace Lean.Meta namespace Closure structure ToProcessElement := (fvarId : FVarId) (newFVarId : FVarId) instance : Inhabited ToProcessElement := ⟨⟨arbitrary, arbitrary⟩⟩ structure Context := (zeta : Bool) structure State := (visitedLevel : LevelMap Level := {}) (visitedExpr : ExprStructMap Expr := {}) (levelParams : Array Name := #[]) (nextLevelIdx : Nat := 1) (levelArgs : Array Level := #[]) (newLocalDecls : Array LocalDecl := #[]) (newLocalDeclsForMVars : Array LocalDecl := #[]) (newLetDecls : Array LocalDecl := #[]) (nextExprIdx : Nat := 1) (exprMVarArgs : Array Expr := #[]) (exprFVarArgs : Array Expr := #[]) (toProcess : Array ToProcessElement := #[]) abbrev ClosureM := ReaderT Context $ StateRefT State MetaM @[inline] def visitLevel (f : Level → ClosureM Level) (u : Level) : ClosureM Level := do if !u.hasMVar && !u.hasParam then pure u else let s ← get match s.visitedLevel.find? u with | some v => pure v | none => do let v ← f u modify fun s => { s with visitedLevel := s.visitedLevel.insert u v } pure v @[inline] def visitExpr (f : Expr → ClosureM Expr) (e : Expr) : ClosureM Expr := do if !e.hasLevelParam && !e.hasFVar && !e.hasMVar then pure e else let s ← get match s.visitedExpr.find? e with | some r => pure r | none => let r ← f e modify fun s => { s with visitedExpr := s.visitedExpr.insert e r } pure r def mkNewLevelParam (u : Level) : ClosureM Level := do let s ← get let p := (`u).appendIndexAfter s.nextLevelIdx modify fun s => { s with levelParams := s.levelParams.push p, nextLevelIdx := s.nextLevelIdx + 1, levelArgs := s.levelArgs.push u } pure $ mkLevelParam p partial def collectLevelAux : Level → ClosureM Level | u@(Level.succ v _) => return u.updateSucc! (← visitLevel collectLevelAux v) | u@(Level.max v w _) => return u.updateMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.imax v w _) => return u.updateIMax! (← visitLevel collectLevelAux v) (← visitLevel collectLevelAux w) | u@(Level.mvar mvarId _) => mkNewLevelParam u | u@(Level.param _ _) => mkNewLevelParam u | u@(Level.zero _) => pure u def collectLevel (u : Level) : ClosureM Level := do -- u ← instantiateLevelMVars u visitLevel collectLevelAux u def preprocess (e : Expr) : ClosureM Expr := do let e ← instantiateMVars e let ctx ← read -- If we are not zeta-expanding let-decls, then we use `check` to find -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. if !ctx.zeta then check e pure e /-- Remark: This method does not guarantee unique user names. The correctness of the procedure does not rely on unique user names. Recall that the pretty printer takes care of unintended collisions. -/ def mkNextUserName : ClosureM Name := do let s ← get let n := (`_x).appendIndexAfter s.nextExprIdx modify fun s => { s with nextExprIdx := s.nextExprIdx + 1 } pure n def pushToProcess (elem : ToProcessElement) : ClosureM Unit := modify fun s => { s with toProcess := s.toProcess.push elem } partial def collectExprAux (e : Expr) : ClosureM Expr := do let collect (e : Expr) := visitExpr collectExprAux e match e with | Expr.proj _ _ s _ => return e.updateProj! (← collect s) | Expr.forallE _ d b _ => return e.updateForallE! (← collect d) (← collect b) | Expr.lam _ d b _ => return e.updateLambdaE! (← collect d) (← collect b) | Expr.letE _ t v b _ => return e.updateLet! (← collect t) (← collect v) (← collect b) | Expr.app f a _ => return e.updateApp! (← collect f) (← collect a) | Expr.mdata _ b _ => return e.updateMData! (← collect b) | Expr.sort u _ => return e.updateSort! (← collectLevel u) | Expr.const c us _ => return e.updateConst! (← us.mapM collectLevel) | Expr.mvar mvarId _ => let mvarDecl ← getMVarDecl mvarId let type ← preprocess mvarDecl.type let type ← collect type let newFVarId ← mkFreshFVarId let userName ← mkNextUserName modify fun s => { s with newLocalDeclsForMVars := s.newLocalDeclsForMVars.push $ LocalDecl.cdecl arbitrary newFVarId userName type BinderInfo.default, exprMVarArgs := s.exprMVarArgs.push e } return mkFVar newFVarId | Expr.fvar fvarId _ => match (← read).zeta, (← getLocalDecl fvarId).value? with | true, some value => collect (← preprocess value) | _, _ => let newFVarId ← mkFreshFVarId pushToProcess ⟨fvarId, newFVarId⟩ return mkFVar newFVarId | e => pure e def collectExpr (e : Expr) : ClosureM Expr := do let e ← preprocess e visitExpr collectExprAux e partial def pickNextToProcessAux (lctx : LocalContext) (i : Nat) (toProcess : Array ToProcessElement) (elem : ToProcessElement) : ToProcessElement × Array ToProcessElement := if h : i < toProcess.size then let elem' := toProcess.get ⟨i, h⟩ if (lctx.get! elem.fvarId).index < (lctx.get! elem'.fvarId).index then pickNextToProcessAux lctx (i+1) (toProcess.set ⟨i, h⟩ elem) elem' else pickNextToProcessAux lctx (i+1) toProcess elem else (elem, toProcess) def pickNextToProcess? : ClosureM (Option ToProcessElement) := do let lctx ← getLCtx let s ← get if s.toProcess.isEmpty then pure none else modifyGet fun s => let elem := s.toProcess.back let toProcess := s.toProcess.pop let (elem, toProcess) := pickNextToProcessAux lctx 0 toProcess elem (some elem, { s with toProcess := toProcess }) def pushFVarArg (e : Expr) : ClosureM Unit := modify fun s => { s with exprFVarArgs := s.exprFVarArgs.push e } def pushLocalDecl (newFVarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : ClosureM Unit := do let type ← collectExpr type modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl arbitrary newFVarId userName type bi } partial def process : ClosureM Unit := do match (← pickNextToProcess?) with | none => pure () | some ⟨fvarId, newFVarId⟩ => let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => pushLocalDecl newFVarId userName type bi pushFVarArg (mkFVar fvarId) process | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl Recall that if `fvarId` is in `zetaFVarIds`, then we zeta-expanded it during type checking (see `check` at `collectExpr`). Our type checker may zeta-expand declarations that are not needed, but this check is conservative, and seems to work well in practice. -/ pushLocalDecl newFVarId userName type pushFVarArg (mkFVar fvarId) process else /- Dependent let-decl -/ let type ← collectExpr type let val ← collectExpr val modify fun s => { s with newLetDecls := s.newLetDecls.push <| LocalDecl.ldecl arbitrary newFVarId userName type val false } /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of newFVarId at `newLocalDecls` -/ modify fun s => { s with newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl newFVarId val) } process @[inline] def mkBinding (isLambda : Bool) (decls : Array LocalDecl) (b : Expr) : Expr := let xs := decls.map LocalDecl.toExpr let b := b.abstract xs decls.size.foldRev (init := b) fun i b => let decl := decls[i] match decl with | LocalDecl.cdecl _ _ n ty bi => let ty := ty.abstractRange i xs if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | LocalDecl.ldecl _ _ n ty val nonDep => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 def mkLambda (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding true decls b def mkForall (decls : Array LocalDecl) (b : Expr) : Expr := mkBinding false decls b structure MkValueTypeClosureResult := (levelParams : Array Name) (type : Expr) (value : Expr) (levelArgs : Array Level) (exprArgs : Array Expr) def mkValueTypeClosureAux (type : Expr) (value : Expr) : ClosureM (Expr × Expr) := do resetZetaFVarIds withTrackingZeta do let type ← collectExpr type let value ← collectExpr value process pure (type, value) def mkValueTypeClosure (type : Expr) (value : Expr) (zeta : Bool) : MetaM MkValueTypeClosureResult := do let ((type, value), s) ← ((mkValueTypeClosureAux type value).run { zeta := zeta }).run {} let newLocalDecls := s.newLocalDecls.reverse ++ s.newLocalDeclsForMVars let newLetDecls := s.newLetDecls.reverse let type := mkForall newLocalDecls (mkForall newLetDecls type) let value := mkLambda newLocalDecls (mkLambda newLetDecls value) pure { type := type, value := value, levelParams := s.levelParams, levelArgs := s.levelArgs, exprArgs := s.exprFVarArgs.reverse ++ s.exprMVarArgs } end Closure variables {m : Type → Type} [MonadLiftT MetaM m] private def mkAuxDefinitionImp (name : Name) (type : Expr) (value : Expr) (zeta : Bool) (compile : Bool) : MetaM Expr := do let result ← Closure.mkValueTypeClosure type value zeta let env ← getEnv let decl := Declaration.defnDecl { name := name, lparams := result.levelParams.toList, type := result.type, value := result.value, hints := ReducibilityHints.regular (getMaxHeight env result.value + 1), isUnsafe := env.hasUnsafe result.type || env.hasUnsafe result.value } trace[Meta.debug]! "{name} : {result.type} := {result.value}" addDecl decl if compile then compileDecl decl pure $ mkAppN (mkConst name result.levelArgs.toList) result.exprArgs /-- Create an auxiliary definition with the given name, type and value. The parameters `type` and `value` may contain free and meta variables. A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on, and `t_j`s are free and meta variables `type` and `value` depend on. -/ def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) (zeta := false) (compile := true) : m Expr := liftMetaM do trace[Meta.debug]! "{name} : {type} := {value}" mkAuxDefinitionImp name type value zeta compile /-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/ def mkAuxDefinitionFor (name : Name) (value : Expr) : m Expr := liftMetaM do let type ← inferType value let type := type.headBeta mkAuxDefinition name type value end Lean.Meta
65e807fb9112767f2711f54393636996a415d963
de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41
/old/old_demos_4-8/expressions_demo_wip.lean
c9fd5d78f8f8cc186fe3da5bcc30fd9e078ea2fb
[]
no_license
kevinsullivan/lang
d3e526ba363dc1ddf5ff1c2f36607d7f891806a7
e9d869bff94fb13ad9262222a6f3c4aafba82d5e
refs/heads/master
1,687,840,064,795
1,628,047,969,000
1,628,047,969,000
282,210,749
0
1
null
1,608,153,830,000
1,595,592,637,000
Lean
UTF-8
Lean
false
false
4,746
lean
import ..expressions.time_expr_wip open lang.time def env_ := env.init def eval_ := eval.init --set up math and phys literals --assume the default interpretation is in seconds for now (in lieu of measurement system) def world_time : time_space_expr := [(time_std_space ℚ)] def world_time_std := [(time_std_frame ℚ)] --using frame as measurement unit as discussed #check mk_space def year_origin : time_expr := let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in [(mk_time std_lit 0)] def year_basis : duration_expr := let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in [(mk_duration std_lit 0)] def year_fm := mk_time_frame_expr year_origin year_basis def year_space := let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in mk_time_space_expr ℚ year_fm /- Tests out various constructors of time and duration_expression. Here, spc is only referenced in the construction of literal expressions. -/ def now : time_expr := let frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) year_space) in [(mk_time year_lit 0)] def one_year : duration_expr := let frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) year_space) in [(mk_duration year_lit 1)] def two_years : duration_expr := 2•one_year def two_plus_one_years : duration_expr := one_year +ᵥ two_years def three_years_in_future : time_expr := two_plus_one_years +ᵥ now def zero_years : duration_expr := duration_expr.zero def still_zero_years := duration_expr.smul_dur (10000000:ℕ) zero_years def zero_years_as_time_sub := now -ᵥ now +ᵥ zero_years +ᵥ still_zero_years def duration_standard : duration_expr := let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in [(mk_duration std_lit 1)] --Does not type check adding together durations in different spaces/frames def invalid_expression_different_spaces : duration_expr := duration_standard +ᵥ one_year --You still need the expected space to get the result --Unfortunately this type checks --Updated comment 4/6 - unfortunately "current" version --with more explicit typing is susceptible to very similar weak typing errors as well --Thus, while it's a problem, it's not exclusive to this version of lang def does_not_enforce_type_check := let frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) year_space) in let year_env := env_.duration_env year_lit in let year_eval := eval_.duration_eval year_lit in year_eval year_env invalid_expression_different_spaces #eval does_not_enforce_type_check def should_type_check : let frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) year_space) in time year_lit := let frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) year_space) in let year_env := env_.time_env year_lit in let year_eval := eval_.time_eval year_lit in year_eval year_env three_years_in_future #eval pt_coord ℚ should_type_check.1.1 --well, eval not implemented yet def tr_from_seconds_to_years := let year_frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval year_frame_lit) (env_.space_env year_frame_lit) year_space) in let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in transform_expr.lit (std_lit.time_tr year_lit) def tr_from_years_to_seconds := let year_frame_lit := (eval_.frame_eval env_.frame_env year_fm) in let year_lit := ((eval_.space_eval year_frame_lit) (env_.space_env year_frame_lit) year_space) in let frame_lit := (eval_.frame_eval env_.frame_env world_time_std) in let std_lit := ((eval_.space_eval frame_lit) (env_.space_env frame_lit) world_time) in transform_expr.lit (year_lit.time_tr std_lit) def tr_from_Seconds_to_seconds := transform_expr.compose tr_from_seconds_to_years tr_from_years_to_seconds def invalid_composition := transform_expr.compose tr_from_seconds_to_years tr_from_seconds_to_years
22e814bfcfb155bd0032672c9e087cf94a23cf38
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Compiler/ImplementedByAttr.lean
223d80feeee01dae9b8a7f80ca3a0b1b67517eb6
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,192
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Attributes namespace Lean namespace Compiler def mkImplementedByAttr : IO (ParametricAttribute Name) := registerParametricAttribute `implementedBy "name of the Lean (probably unsafe) function that implements opaque constant" $ fun env declName stx => match env.find? declName with | none => Except.error "unknown declaration" | some decl => match attrParamSyntaxToIdentifier stx with | some fnName => match env.find? fnName with | none => Except.error ("unknown function '" ++ toString fnName ++ "'") | some fnDecl => if decl.type == fnDecl.type then Except.ok fnName else Except.error ("invalid function '" ++ toString fnName ++ "' type mismatch") | _ => Except.error "expected identifier" @[init mkImplementedByAttr] constant implementedByAttr : ParametricAttribute Name := arbitrary _ @[export lean_get_implemented_by] def getImplementedBy (env : Environment) (n : Name) : Option Name := implementedByAttr.getParam env n end Compiler end Lean
37385b04137f2cba77e89ff44d081049d7a8d3f2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Trace.lean
3ef311e873ad2554cd176aaa74ad715af2e77a34
[ "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
8,830
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ open System namespace Lake -------------------------------------------------------------------------------- /-! # Utilities -/ -------------------------------------------------------------------------------- class CheckExists.{u} (i : Type u) where /-- Check whether there already exists an artifact for the given target info. -/ checkExists : i → BaseIO Bool export CheckExists (checkExists) instance : CheckExists FilePath where checkExists := FilePath.pathExists -------------------------------------------------------------------------------- /-! # Trace Abstraction -/ -------------------------------------------------------------------------------- class ComputeTrace.{u,v,w} (i : Type u) (m : outParam $ Type v → Type w) (t : Type v) where /-- Compute the trace of some target info using information from the monadic context. -/ computeTrace : i → m t def computeTrace [ComputeTrace i m t] [MonadLiftT m n] (info : i) : n t := liftM <| ComputeTrace.computeTrace info class NilTrace.{u} (t : Type u) where /-- The nil trace. Should not unduly clash with a proper trace. -/ nilTrace : t export NilTrace (nilTrace) instance [NilTrace t] : Inhabited t := ⟨nilTrace⟩ class MixTrace.{u} (t : Type u) where /-- Combine two traces. The result should be dirty if either of the inputs is dirty. -/ mixTrace : t → t → t export MixTrace (mixTrace) def mixTraceM [MixTrace t] [Pure m] (t1 t2 : t) : m t := pure <| mixTrace t1 t2 section variable [MixTrace t] [NilTrace t] def mixTraceList (traces : List t) : t := traces.foldl mixTrace nilTrace def mixTraceArray (traces : Array t) : t := traces.foldl mixTrace nilTrace variable [ComputeTrace i m t] def computeListTrace [MonadLiftT m n] [Monad n] (artifacts : List i) : n t := mixTraceList <$> artifacts.mapM computeTrace instance [Monad m] : ComputeTrace (List i) m t := ⟨computeListTrace⟩ def computeArrayTrace [MonadLiftT m n] [Monad n] (artifacts : Array i) : n t := mixTraceArray <$> artifacts.mapM computeTrace instance [Monad m] : ComputeTrace (Array i) m t := ⟨computeArrayTrace⟩ end -------------------------------------------------------------------------------- /-! # Hash Trace -/ -------------------------------------------------------------------------------- /-- A content hash. TODO: Use a secure hash rather than the builtin Lean hash function. -/ structure Hash where val : UInt64 deriving BEq, DecidableEq, Repr namespace Hash def ofNat (n : Nat) := mk n.toUInt64 def loadFromFile (hashFile : FilePath) : IO (Option Hash) := return (← IO.FS.readFile hashFile).toNat?.map ofNat def nil : Hash := mk <| 1723 -- same as Name.anonymous instance : NilTrace Hash := ⟨nil⟩ def mix (h1 h2 : Hash) : Hash := mk <| mixHash h1.val h2.val instance : MixTrace Hash := ⟨mix⟩ protected def toString (self : Hash) : String := toString self.val instance : ToString Hash := ⟨Hash.toString⟩ def ofString (str : String) := mix nil <| mk <| hash str -- same as Name.mkSimple def ofByteArray (bytes : ByteArray) : Hash := ⟨hash bytes⟩ end Hash class ComputeHash (α : Type u) (m : outParam $ Type → Type v) where computeHash : α → m Hash instance [ComputeHash α m] : ComputeTrace α m Hash := ⟨ComputeHash.computeHash⟩ def pureHash [ComputeHash α Id] (a : α) : Hash := ComputeHash.computeHash a def computeHash [ComputeHash α m] [MonadLiftT m n] (a : α) : n Hash := liftM <| ComputeHash.computeHash a instance : ComputeHash String Id := ⟨Hash.ofString⟩ def computeFileHash (file : FilePath) : IO Hash := Hash.ofByteArray <$> IO.FS.readBinFile file instance : ComputeHash FilePath IO := ⟨computeFileHash⟩ /-- A wrapper around `FilePath` that adjusts its `ComputeHash` implementation to normalize `\r\n` sequences to `\n` for cross-platform compatibility. -/ structure TextFilePath where path : FilePath /-- This is the same as `String.replace text "\r\n" "\n"`, but more efficient. -/ partial def crlf2lf (text : String) : String := go "" 0 0 where go (acc : String) (accStop pos : String.Pos) : String := if h : text.atEnd pos then -- note: if accStop = 0 then acc is empty if accStop = 0 then text else acc ++ text.extract accStop pos else let c := text.get' pos h let pos' := text.next' pos h if c == '\r' && text.get pos' == '\n' then let acc := acc ++ text.extract accStop pos go acc pos' (text.next pos') else go acc accStop pos' instance : ComputeHash TextFilePath IO where computeHash file := do let text ← IO.FS.readFile file.path let text := crlf2lf text return Hash.ofString text instance [ComputeHash α m] [Monad m] : ComputeHash (Array α) m where computeHash ar := ar.foldlM (fun b a => Hash.mix b <$> computeHash a) Hash.nil -------------------------------------------------------------------------------- /-! # Modification Time (MTime) Trace -/ -------------------------------------------------------------------------------- open IO.FS (SystemTime) /-- A modification time. -/ def MTime := SystemTime namespace MTime instance : OfNat MTime (nat_lit 0) := ⟨⟨0,0⟩⟩ instance : BEq MTime := inferInstanceAs (BEq SystemTime) instance : Repr MTime := inferInstanceAs (Repr SystemTime) instance : Ord MTime := inferInstanceAs (Ord SystemTime) instance : LT MTime := ltOfOrd instance : LE MTime := leOfOrd instance : Min MTime := minOfLe instance : Max MTime := maxOfLe instance : NilTrace MTime := ⟨0⟩ instance : MixTrace MTime := ⟨max⟩ end MTime class GetMTime (α) where getMTime : α → IO MTime export GetMTime (getMTime) instance [GetMTime α] : ComputeTrace α IO MTime := ⟨getMTime⟩ def getFileMTime (file : FilePath) : IO MTime := return (← file.metadata).modified instance : GetMTime FilePath := ⟨getFileMTime⟩ instance : GetMTime TextFilePath := ⟨(getFileMTime ·.path)⟩ /-- Check if the info's `MTIme` is at least `depMTime`. -/ def checkIfNewer [GetMTime i] (info : i) (depMTime : MTime) : BaseIO Bool := (do pure ((← getMTime info) >= depMTime : Bool)).catchExceptions fun _ => pure false -------------------------------------------------------------------------------- /-! # Lake Build Trace (Hash + MTIme) -/ -------------------------------------------------------------------------------- /-- Trace used for common Lake targets. Combines `Hash` and `MTime`. -/ structure BuildTrace where hash : Hash mtime : MTime deriving Repr namespace BuildTrace def withHash (hash : Hash) (self : BuildTrace) : BuildTrace := {self with hash} def withoutHash (self : BuildTrace) : BuildTrace := {self with hash := Hash.nil} def withMTime (mtime : MTime) (self : BuildTrace) : BuildTrace := {self with mtime} def withoutMTime (self : BuildTrace) : BuildTrace := {self with mtime := 0} def fromHash (hash : Hash) : BuildTrace := mk hash 0 instance : Coe Hash BuildTrace := ⟨fromHash⟩ def fromMTime (mtime : MTime) : BuildTrace := mk Hash.nil mtime instance : Coe MTime BuildTrace := ⟨fromMTime⟩ def nil : BuildTrace := mk Hash.nil 0 instance : NilTrace BuildTrace := ⟨nil⟩ def compute [ComputeHash i m] [MonadLiftT m IO] [GetMTime i] (info : i) : IO BuildTrace := return mk (← computeHash info) (← getMTime info) instance [ComputeHash i m] [MonadLiftT m IO] [GetMTime i] : ComputeTrace i IO BuildTrace := ⟨compute⟩ def mix (t1 t2 : BuildTrace) : BuildTrace := mk (Hash.mix t1.hash t2.hash) (max t1.mtime t2.mtime) instance : MixTrace BuildTrace := ⟨mix⟩ /-- Check the build trace against the given target info and hash to see if the target is up-to-date. -/ def checkAgainstHash [CheckExists i] (info : i) (hash : Hash) (self : BuildTrace) : BaseIO Bool := pure (hash == self.hash) <&&> checkExists info /-- Check the build trace against the given target info and its modification time to see if the target is up-to-date. -/ def checkAgainstTime [CheckExists i] [GetMTime i] (info : i) (self : BuildTrace) : BaseIO Bool := checkIfNewer info self.mtime /-- Check the build trace against the given target info and its trace file to see if the target is up-to-date. -/ def checkAgainstFile [CheckExists i] [GetMTime i] (info : i) (traceFile : FilePath) (self : BuildTrace) : BaseIO Bool := do let act : IO _ := do if let some hash ← Hash.loadFromFile traceFile then self.checkAgainstHash info hash else return self.mtime < (← getMTime info) act.catchExceptions fun _ => pure false def writeToFile (traceFile : FilePath) (self : BuildTrace) : IO PUnit := IO.FS.writeFile traceFile self.hash.toString end BuildTrace
599ad5dd2aae33c3d98acdf3626388456c62c257
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finset/interval.lean
a8e5585b4c7dacd458452d814dbab200b4df65b4
[ "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
4,049
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.locally_finite /-! # Intervals of finsets as finsets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides the `locally_finite_order` instance for `finset α` and calculates the cardinality of finite intervals of finsets. If `s t : finset α`, then `finset.Icc s t` is the finset of finsets which include `s` and are included in `t`. For example, `finset.Icc {0, 1} {0, 1, 2, 3} = {{0, 1}, {0, 1, 2}, {0, 1, 3}, {0, 1, 2, 3}}` and `finset.Icc {0, 1, 2} {0, 1, 3} = {}`. -/ variables {α : Type*} namespace finset variables [decidable_eq α] (s t : finset α) instance : locally_finite_order (finset α) := { finset_Icc := λ s t, t.powerset.filter ((⊆) s), finset_Ico := λ s t, t.ssubsets.filter ((⊆) s), finset_Ioc := λ s t, t.powerset.filter ((⊂) s), finset_Ioo := λ s t, t.ssubsets.filter ((⊂) s), finset_mem_Icc := λ s t u, by {rw [mem_filter, mem_powerset], exact and_comm _ _ }, finset_mem_Ico := λ s t u, by {rw [mem_filter, mem_ssubsets], exact and_comm _ _ }, finset_mem_Ioc := λ s t u, by {rw [mem_filter, mem_powerset], exact and_comm _ _ }, finset_mem_Ioo := λ s t u, by {rw [mem_filter, mem_ssubsets], exact and_comm _ _ } } lemma Icc_eq_filter_powerset : Icc s t = t.powerset.filter ((⊆) s) := rfl lemma Ico_eq_filter_ssubsets : Ico s t = t.ssubsets.filter ((⊆) s) := rfl lemma Ioc_eq_filter_powerset : Ioc s t = t.powerset.filter ((⊂) s) := rfl lemma Ioo_eq_filter_ssubsets : Ioo s t = t.ssubsets.filter ((⊂) s) := rfl lemma Iic_eq_powerset : Iic s = s.powerset := filter_true_of_mem $ λ t _, empty_subset t lemma Iio_eq_ssubsets : Iio s = s.ssubsets := filter_true_of_mem $ λ t _, empty_subset t variables {s t} lemma Icc_eq_image_powerset (h : s ⊆ t) : Icc s t = (t \ s).powerset.image ((∪) s) := begin ext u, simp_rw [mem_Icc, mem_image, exists_prop, mem_powerset], split, { rintro ⟨hs, ht⟩, exact ⟨u \ s, sdiff_le_sdiff_right ht, sup_sdiff_cancel_right hs⟩ }, { rintro ⟨v, hv, rfl⟩, exact ⟨le_sup_left, union_subset h $ hv.trans $ sdiff_subset _ _⟩ } end lemma Ico_eq_image_ssubsets (h : s ⊆ t) : Ico s t = (t \ s).ssubsets.image ((∪) s) := begin ext u, simp_rw [mem_Ico, mem_image, exists_prop, mem_ssubsets], split, { rintro ⟨hs, ht⟩, exact ⟨u \ s, sdiff_lt_sdiff_right ht hs, sup_sdiff_cancel_right hs⟩ }, { rintro ⟨v, hv, rfl⟩, exact ⟨le_sup_left, sup_lt_of_lt_sdiff_left hv h⟩ } end /-- Cardinality of a non-empty `Icc` of finsets. -/ lemma card_Icc_finset (h : s ⊆ t) : (Icc s t).card = 2 ^ (t.card - s.card) := begin rw [←card_sdiff h, ←card_powerset, Icc_eq_image_powerset h, finset.card_image_iff], rintro u hu v hv (huv : s ⊔ u = s ⊔ v), rw [mem_coe, mem_powerset] at hu hv, rw [←(disjoint_sdiff.mono_right hu : disjoint s u).sup_sdiff_cancel_left, ←(disjoint_sdiff.mono_right hv : disjoint s v).sup_sdiff_cancel_left, huv], end /-- Cardinality of an `Ico` of finsets. -/ lemma card_Ico_finset (h : s ⊆ t) : (Ico s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc_finset h] /-- Cardinality of an `Ioc` of finsets. -/ lemma card_Ioc_finset (h : s ⊆ t) : (Ioc s t).card = 2 ^ (t.card - s.card) - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc_finset h] /-- Cardinality of an `Ioo` of finsets. -/ lemma card_Ioo_finset (h : s ⊆ t) : (Ioo s t).card = 2 ^ (t.card - s.card) - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc_finset h] /-- Cardinality of an `Iic` of finsets. -/ lemma card_Iic_finset : (Iic s).card = 2 ^ s.card := by rw [Iic_eq_powerset, card_powerset] /-- Cardinality of an `Iio` of finsets. -/ lemma card_Iio_finset : (Iio s).card = 2 ^ s.card - 1 := by rw [Iio_eq_ssubsets, ssubsets, card_erase_of_mem (mem_powerset_self _), card_powerset] end finset
e2f2f913bc5b534eb1ceb7f9862f39f1d9174262
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_912.lean
bf27b3e06d2588f0bcc95c0656c2640ce1a9cb6a
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,002
lean
import data.set.function open set function -- BEGIN variables {α β : Type*} variable f : α → β variables s t : set α variables u v : set β example (h : injective f) : f ⁻¹' (f '' s) ⊆ s := sorry example : f '' (f⁻¹' u) ⊆ u := sorry example (h : surjective f) : u ⊆ f '' (f⁻¹' u) := sorry example (h : s ⊆ t) : f '' s ⊆ f '' t := sorry example (h : u ⊆ v) : f ⁻¹' u ⊆ f ⁻¹' v := sorry example : f ⁻¹' (u ∪ v) = f ⁻¹' u ∪ f ⁻¹' v := sorry example : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := sorry example (h : injective f) : f '' s ∩ f '' t ⊆ f '' (s ∩ t) := sorry example : f '' s \ f '' t ⊆ f '' (s \ t) := sorry example : f ⁻¹' u \ f ⁻¹' v ⊆ f ⁻¹' (u \ v) := sorry example : f '' s ∩ v = f '' (s ∩ f ⁻¹' v) := sorry example : f '' (s ∩ f ⁻¹' u) ⊆ f '' s ∪ u := sorry example : s ∩ f ⁻¹' u ⊆ f ⁻¹' (f '' s ∩ u) := sorry example : s ∪ f ⁻¹' u ⊆ f ⁻¹' (f '' s ∪ u) := sorry -- END
26a7081849d7be32bf642d5956dd00571a462517
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL/Script.lean
0bfa583cdd7f0b4295715de13b292f753dfc29f5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,174
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lake.Config.Package import Lake.DSL.Attributes import Lake.DSL.DeclUtil namespace Lake.DSL open Lean Parser Command syntax scriptDeclSpec := ident (ppSpace simpleBinder)? (declValSimple <|> declValDo) /-- Define a new Lake script for the package. Has two forms: ```lean script «script-name» (args) do /- ... -/ script «script-name» (args) := ... ``` -/ scoped syntax (name := scriptDecl) (docComment)? optional(Term.attributes) "script " scriptDeclSpec : command @[macro scriptDecl] def expandScriptDecl : Macro | `($[$doc?]? $[$attrs?]? script $id:ident $[$args?]? do $seq $[$wds?]?) => do `($[$doc?]? $[$attrs?]? script $id:ident $[$args?]? := do $seq $[$wds?]?) | `($[$doc?]? $[$attrs?]? script $id:ident $[$args?]? := $defn $[$wds?]?) => do let args ← expandOptSimpleBinder args? let attrs := #[← `(Term.attrInstance| «script»)] ++ expandAttrs attrs? `($[$doc?]? @[$attrs,*] def $id : ScriptFn := fun $args => $defn $[$wds?]?) | stx => Macro.throwErrorAt stx "ill-formed script declaration"
681abdc62aad9a355d4cd1f3123e5e1f91f09508
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/fintype/card.lean
b7bcfe3e6a8e16c1b3bcb719e5ed3fdfb5e76fa5
[ "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
17,316
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import algebra.big_operators.ring /-! Results about "big operations" over a `fintype`, and consequent results about cardinalities of certain types. ## Implementation note This content had previously been in `data.fintype.basic`, but was moved here to avoid requiring `algebra.big_operators` (and hence many other imports) as a dependency of `fintype`. However many of the results here really belong in `algebra.big_operators.basic` and should be moved at some point. -/ universes u v variables {α : Type*} {β : Type*} {γ : Type*} open_locale big_operators namespace fintype @[to_additive] lemma prod_bool [comm_monoid α] (f : bool → α) : ∏ b, f b = f tt * f ff := by simp lemma card_eq_sum_ones {α} [fintype α] : fintype.card α = ∑ a : α, 1 := finset.card_eq_sum_ones _ section open finset variables {ι : Type*} [decidable_eq ι] [fintype ι] @[to_additive] lemma prod_extend_by_one [comm_monoid α] (s : finset ι) (f : ι → α) : ∏ i, (if i ∈ s then f i else 1) = ∏ i in s, f i := by rw [← prod_filter, filter_mem_eq_inter, univ_inter] end section variables {M : Type*} [fintype α] [comm_monoid M] @[to_additive] lemma prod_eq_one (f : α → M) (h : ∀ a, f a = 1) : (∏ a, f a) = 1 := finset.prod_eq_one $ λ a ha, h a @[to_additive] lemma prod_congr (f g : α → M) (h : ∀ a, f a = g a) : (∏ a, f a) = ∏ a, g a := finset.prod_congr rfl $ λ a ha, h a @[to_additive] lemma prod_eq_single {f : α → M} (a : α) (h : ∀ x ≠ a, f x = 1) : (∏ x, f x) = f a := finset.prod_eq_single a (λ x _ hx, h x hx) $ λ ha, (ha (finset.mem_univ a)).elim @[to_additive] lemma prod_eq_mul {f : α → M} (a b : α) (h₁ : a ≠ b) (h₂ : ∀ x, x ≠ a ∧ x ≠ b → f x = 1) : (∏ x, f x) = (f a) * (f b) := begin apply finset.prod_eq_mul a b h₁ (λ x _ hx, h₂ x hx); exact λ hc, (hc (finset.mem_univ _)).elim end @[to_additive] lemma prod_unique [unique β] (f : β → M) : (∏ x, f x) = f (default β) := by simp only [finset.prod_singleton, univ_unique] /-- If a product of a `finset` of a subsingleton type has a given value, so do the terms in that product. -/ @[to_additive "If a sum of a `finset` of a subsingleton type has a given value, so do the terms in that sum."] lemma eq_of_subsingleton_of_prod_eq {ι : Type*} [subsingleton ι] {s : finset ι} {f : ι → M} {b : M} (h : ∏ i in s, f i = b) : ∀ i ∈ s, f i = b := finset.eq_of_card_le_one_of_prod_eq (finset.card_le_one_of_subsingleton s) h end end fintype open finset section variables {M : Type*} [fintype α] [comm_monoid M] @[simp, to_additive] lemma fintype.prod_option (f : option α → M) : ∏ i, f i = f none * ∏ i, f (some i) := show ((finset.insert_none _).1.map f).prod = _, by simp only [finset.prod, finset.insert_none, multiset.map_cons, multiset.prod_cons, multiset.map_map] end @[to_additive] theorem fin.prod_univ_def [comm_monoid β] {n : ℕ} (f : fin n → β) : ∏ i, f i = ((list.fin_range n).map f).prod := by simp [fin.univ_def, finset.fin_range] @[to_additive] theorem finset.prod_range [comm_monoid β] {n : ℕ} (f : ℕ → β) : ∏ i in finset.range n, f i = ∏ i : fin n, f i := begin fapply @finset.prod_bij' _ _ _ _ _ _, exact λ k w, ⟨k, (by simpa using w)⟩, swap 3, exact λ a m, a, swap 3, exact λ a m, by simpa using a.2, all_goals { tidy, }, end @[to_additive] theorem fin.prod_of_fn [comm_monoid β] {n : ℕ} (f : fin n → β) : (list.of_fn f).prod = ∏ i, f i := by rw [list.of_fn_eq_map, fin.prod_univ_def] /-- A product of a function `f : fin 0 → β` is `1` because `fin 0` is empty -/ @[simp, to_additive "A sum of a function `f : fin 0 → β` is `0` because `fin 0` is empty"] theorem fin.prod_univ_zero [comm_monoid β] (f : fin 0 → β) : ∏ i, f i = 1 := rfl /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f x`, for some `x : fin (n + 1)` times the remaining product -/ theorem fin.prod_univ_succ_above [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∏ i, f i = f x * ∏ i : fin n, f (x.succ_above i) := begin rw [fin.univ_succ_above, finset.prod_insert, finset.prod_image], { intros x _ y _ hxy, exact fin.succ_above_right_inj.mp hxy }, { simp [fin.succ_above_ne] } end /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f x`, for some `x : fin (n + 1)` plus the remaining product -/ theorem fin.sum_univ_succ_above [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) (x : fin (n + 1)) : ∑ i, f i = f x + ∑ i : fin n, f (x.succ_above i) := by apply @fin.prod_univ_succ_above (multiplicative β) attribute [to_additive] fin.prod_univ_succ_above /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f 0` plus the remaining product -/ theorem fin.prod_univ_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = f 0 * ∏ i : fin n, f i.succ := fin.prod_univ_succ_above f 0 /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f 0` plus the remaining product -/ theorem fin.sum_univ_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = f 0 + ∑ i : fin n, f i.succ := fin.sum_univ_succ_above f 0 attribute [to_additive] fin.prod_univ_succ /-- A product of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the product of `f (fin.last n)` plus the remaining product -/ theorem fin.prod_univ_cast_succ [comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∏ i, f i = (∏ i : fin n, f i.cast_succ) * f (fin.last n) := by simpa [mul_comm] using fin.prod_univ_succ_above f (fin.last n) /-- A sum of a function `f : fin (n + 1) → β` over all `fin (n + 1)` is the sum of `f (fin.last n)` plus the remaining sum -/ theorem fin.sum_univ_cast_succ [add_comm_monoid β] {n : ℕ} (f : fin (n + 1) → β) : ∑ i, f i = ∑ i : fin n, f i.cast_succ + f (fin.last n) := by apply @fin.prod_univ_cast_succ (multiplicative β) attribute [to_additive] fin.prod_univ_cast_succ open finset @[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype.card (sigma β) = ∑ a, fintype.card (β a) := card_sigma _ _ -- FIXME ouch, this should be in the main file. @[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] : fintype.card (α ⊕ β) = fintype.card α + fintype.card β := by simp [sum.fintype, fintype.of_equiv_card] @[simp] lemma finset.card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = ∏ a in s, card (t a) := multiset.card_pi _ _ @[simp] lemma fintype.card_pi_finset [decidable_eq α] [fintype α] {δ : α → Type*} (t : Π a, finset (δ a)) : (fintype.pi_finset t).card = ∏ a, card (t a) := by simp [fintype.pi_finset, card_map] @[simp] lemma fintype.card_pi {β : α → Type*} [decidable_eq α] [fintype α] [f : Π a, fintype (β a)] : fintype.card (Π a, β a) = ∏ a, fintype.card (β a) := fintype.card_pi_finset _ -- FIXME ouch, this should be in the main file. @[simp] lemma fintype.card_fun [decidable_eq α] [fintype α] [fintype β] : fintype.card (α → β) = fintype.card β ^ fintype.card α := by rw [fintype.card_pi, finset.prod_const]; refl @[simp] lemma card_vector [fintype α] (n : ℕ) : fintype.card (vector α n) = fintype.card α ^ n := by rw fintype.of_equiv_card; simp @[simp, to_additive] lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) : ∏ x in univ.attach, f x = ∏ x, f ⟨x, (mem_univ _)⟩ := fintype.prod_equiv (equiv.subtype_univ_equiv (λ x, mem_univ _)) _ _ (λ x, by simp) /-- Taking a product over `univ.pi t` is the same as taking the product over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`. -/ @[to_additive "Taking a sum over `univ.pi t` is the same as taking the sum over `fintype.pi_finset t`. `univ.pi t` and `fintype.pi_finset t` are essentially the same `finset`, but differ in the type of their element, `univ.pi t` is a `finset (Π a ∈ univ, t a)` and `fintype.pi_finset t` is a `finset (Π a, t a)`."] lemma finset.prod_univ_pi [decidable_eq α] [fintype α] [comm_monoid β] {δ : α → Type*} {t : Π (a : α), finset (δ a)} (f : (Π (a : α), a ∈ (univ : finset α) → δ a) → β) : ∏ x in univ.pi t, f x = ∏ x in fintype.pi_finset t, f (λ a _, x a) := prod_bij (λ x _ a, x a (mem_univ _)) (by simp) (by simp) (by simp [function.funext_iff] {contextual := tt}) (λ x hx, ⟨λ a _, x a, by simp * at *⟩) /-- The product over `univ` of a sum can be written as a sum over the product of sets, `fintype.pi_finset`. `finset.prod_sum` is an alternative statement when the product is not over `univ` -/ lemma finset.prod_univ_sum [decidable_eq α] [fintype α] [comm_semiring β] {δ : α → Type u_1} [Π (a : α), decidable_eq (δ a)] {t : Π (a : α), finset (δ a)} {f : Π (a : α), δ a → β} : ∏ a, ∑ b in t a, f a b = ∑ p in fintype.pi_finset t, ∏ x, f x (p x) := by simp only [finset.prod_attach_univ, prod_sum, finset.sum_univ_pi] /-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a fintype of cardinality `n` gives `(a + b)^n`. The "good" proof involves expanding along all coordinates using the fact that `x^n` is multilinear, but multilinear maps are only available now over rings, so we give instead a proof reducing to the usual binomial theorem to have a result over semirings. -/ lemma fintype.sum_pow_mul_eq_add_pow (α : Type*) [fintype α] {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset α, a ^ s.card * b ^ (fintype.card α - s.card) = (a + b) ^ (fintype.card α) := finset.sum_pow_mul_eq_add_pow _ _ _ lemma fin.sum_pow_mul_eq_add_pow {n : ℕ} {R : Type*} [comm_semiring R] (a b : R) : ∑ s : finset (fin n), a ^ s.card * b ^ (n - s.card) = (a + b) ^ n := by simpa using fintype.sum_pow_mul_eq_add_pow (fin n) a b lemma fin.prod_const [comm_monoid α] (n : ℕ) (x : α) : ∏ i : fin n, x = x ^ n := by simp lemma fin.sum_const [add_comm_monoid α] (n : ℕ) (x : α) : ∑ i : fin n, x = n • x := by simp @[to_additive] lemma function.bijective.prod_comp [fintype α] [fintype β] [comm_monoid γ] {f : α → β} (hf : function.bijective f) (g : β → γ) : ∏ i, g (f i) = ∏ i, g i := fintype.prod_bijective f hf _ _ (λ x, rfl) @[to_additive] lemma equiv.prod_comp [fintype α] [fintype β] [comm_monoid γ] (e : α ≃ β) (f : β → γ) : ∏ i, f (e i) = ∏ i, f i := e.bijective.prod_comp f /-- It is equivalent to sum a function over `fin n` or `finset.range n`. -/ @[to_additive] lemma fin.prod_univ_eq_prod_range [comm_monoid α] (f : ℕ → α) (n : ℕ) : ∏ i : fin n, f i = ∏ i in range n, f i := calc (∏ i : fin n, f i) = ∏ i : {x // x ∈ range n}, f i : ((equiv.fin_equiv_subtype n).trans (equiv.subtype_equiv_right (λ _, mem_range.symm))).prod_comp (f ∘ coe) ... = ∏ i in range n, f i : by rw [← attach_eq_univ, prod_attach] @[to_additive] lemma finset.prod_fin_eq_prod_range [comm_monoid β] {n : ℕ} (c : fin n → β) : ∏ i, c i = ∏ i in finset.range n, if h : i < n then c ⟨i, h⟩ else 1 := begin rw [← fin.prod_univ_eq_prod_range, finset.prod_congr rfl], rintros ⟨i, hi⟩ _, simp only [fin.coe_eq_val, hi, dif_pos] end @[to_additive] lemma finset.prod_to_finset_eq_subtype {M : Type*} [comm_monoid M] [fintype α] (p : α → Prop) [decidable_pred p] (f : α → M) : ∏ a in {x | p x}.to_finset, f a = ∏ a : subtype p, f a := by { rw ← finset.prod_subtype, simp } @[to_additive] lemma finset.prod_fiberwise [decidable_eq β] [fintype β] [comm_monoid γ] (s : finset α) (f : α → β) (g : α → γ) : ∏ b : β, ∏ a in s.filter (λ a, f a = b), g a = ∏ a in s, g a := finset.prod_fiberwise_of_maps_to (λ x _, mem_univ _) _ @[to_additive] lemma fintype.prod_fiberwise [fintype α] [decidable_eq β] [fintype β] [comm_monoid γ] (f : α → β) (g : α → γ) : (∏ b : β, ∏ a : {a // f a = b}, g (a : α)) = ∏ a, g a := begin rw [← (equiv.sigma_preimage_equiv f).prod_comp, ← univ_sigma_univ, prod_sigma], refl end lemma fintype.prod_dite [fintype α] {p : α → Prop} [decidable_pred p] [comm_monoid β] (f : Π (a : α) (ha : p a), β) (g : Π (a : α) (ha : ¬p a), β) : (∏ a, dite (p a) (f a) (g a)) = (∏ a : {a // p a}, f a a.2) * (∏ a : {a // ¬p a}, g a a.2) := begin simp only [prod_dite, attach_eq_univ], congr' 1, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // p x}, f x x.2), simp }, { convert (equiv.subtype_equiv_right _).prod_comp (λ x : {x // ¬p x}, g x x.2), simp } end section open finset variables {α₁ : Type*} {α₂ : Type*} {M : Type*} [fintype α₁] [fintype α₂] [comm_monoid M] @[to_additive] lemma fintype.prod_sum_elim (f : α₁ → M) (g : α₂ → M) : (∏ x, sum.elim f g x) = (∏ a₁, f a₁) * (∏ a₂, g a₂) := by { classical, rw [univ_sum_type, prod_sum_elim] } @[to_additive] lemma fintype.prod_sum_type (f : α₁ ⊕ α₂ → M) : (∏ x, f x) = (∏ a₁, f (sum.inl a₁)) * (∏ a₂, f (sum.inr a₂)) := by simp only [← fintype.prod_sum_elim, sum.elim_comp_inl_inr] end namespace list lemma prod_take_of_fn [comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).prod = ∏ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := begin have A : ∀ (j : fin n), ¬ ((j : ℕ) < 0) := λ j, not_lt_bot, induction i with i IH, { simp [A] }, by_cases h : i < n, { have : i < length (of_fn f), by rwa [length_of_fn f], rw prod_take_succ _ _ this, have A : ((finset.univ : finset (fin n)).filter (λ j, j.val < i + 1)) = ((finset.univ : finset (fin n)).filter (λ j, j.val < i)) ∪ {(⟨i, h⟩ : fin n)}, by { ext j, simp [nat.lt_succ_iff_lt_or_eq, fin.ext_iff, - add_comm] }, have B : _root_.disjoint (finset.filter (λ (j : fin n), j.val < i) finset.univ) (singleton (⟨i, h⟩ : fin n)), by simp, rw [A, finset.prod_union B, IH], simp }, { have A : (of_fn f).take i = (of_fn f).take i.succ, { rw ← length_of_fn f at h, have : length (of_fn f) ≤ i := not_lt.mp h, rw [take_all_of_le this, take_all_of_le (le_trans this (nat.le_succ _))] }, have B : ∀ (j : fin n), ((j : ℕ) < i.succ) = ((j : ℕ) < i), { assume j, have : (j : ℕ) < i := lt_of_lt_of_le j.2 (not_lt.mp h), simp [this, lt_trans this (nat.lt_succ_self _)] }, simp [← A, B, IH] } end -- `to_additive` does not work on `prod_take_of_fn` because of `0 : ℕ` in the proof. -- Use `multiplicative` instead. lemma sum_take_of_fn [add_comm_monoid α] {n : ℕ} (f : fin n → α) (i : ℕ) : ((of_fn f).take i).sum = ∑ j in finset.univ.filter (λ (j : fin n), j.val < i), f j := @prod_take_of_fn (multiplicative α) _ n f i attribute [to_additive] prod_take_of_fn @[to_additive] lemma prod_of_fn [comm_monoid α] {n : ℕ} {f : fin n → α} : (of_fn f).prod = ∏ i, f i := begin convert prod_take_of_fn f n, { rw [take_all_of_le (le_of_eq (length_of_fn f))] }, { have : ∀ (j : fin n), (j : ℕ) < n := λ j, j.is_lt, simp [this] } end lemma alternating_sum_eq_finset_sum {G : Type*} [add_comm_group G] : ∀ (L : list G), alternating_sum L = ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.is_lt | [] := by { rw [alternating_sum, finset.sum_eq_zero], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∑ i : fin 1, (-1 : ℤ) ^ (i : ℕ) • [g].nth_le i i.2, rw [fin.sum_univ_succ], simp, end | (g :: h :: L) := calc g + -h + L.alternating_sum = g + -h + ∑ i : fin L.length, (-1 : ℤ) ^ (i : ℕ) • L.nth_le i i.2 : congr_arg _ (alternating_sum_eq_finset_sum _) ... = ∑ i : fin (L.length + 2), (-1 : ℤ) ^ (i : ℕ) • list.nth_le (g :: h :: L) i _ : begin rw [fin.sum_univ_succ, fin.sum_univ_succ, add_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end @[to_additive] lemma alternating_prod_eq_finset_prod {G : Type*} [comm_group G] : ∀ (L : list G), alternating_prod L = ∏ i : fin L.length, (L.nth_le i i.2) ^ ((-1 : ℤ) ^ (i : ℕ)) | [] := by { rw [alternating_prod, finset.prod_eq_one], rintro ⟨i, ⟨⟩⟩ } | (g :: []) := begin show g = ∏ i : fin 1, [g].nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ), rw [fin.prod_univ_succ], simp, end | (g :: h :: L) := calc g * h⁻¹ * L.alternating_prod = g * h⁻¹ * ∏ i : fin L.length, L.nth_le i i.2 ^ (-1 : ℤ) ^ (i : ℕ) : congr_arg _ (alternating_prod_eq_finset_prod _) ... = ∏ i : fin (L.length + 2), list.nth_le (g :: h :: L) i _ ^ (-1 : ℤ) ^ (i : ℕ) : begin rw [fin.prod_univ_succ, fin.prod_univ_succ, mul_assoc], unfold_coes, simp [nat.succ_eq_add_one, pow_add], refl, end end list
51e657d48b49d3c747d4c2b80b40a3edfd8c7b27
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Data/SMap.lean
966fc8acf4c12d86fd17d8718baf57e3e916b311
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
4,057
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap import Std.Data.PersistentHashMap universe u v w w' namespace Lean open Std (HashMap PHashMap) /- Staged map for implementing the Environment. The idea is to store imported entries into a hashtable and local entries into a persistent hashtable. Hypotheses: - The number of entries (i.e., declarations) coming from imported files is much bigger than the number of entries in the current file. - HashMap is faster than PersistentHashMap. - When we are reading imported files, we have exclusive access to the map, and efficient destructive updates are performed. Remarks: - We never remove declarations from the Environment. In principle, we could support deletion by using `(PHashMap α (Option β))` where the value `none` would indicate that an entry was "removed" from the hashtable. - We do not need additional bookkeeping for extracting the local entries. -/ structure SMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where stage₁ : Bool := true map₁ : HashMap α β := {} map₂ : PHashMap α β := {} namespace SMap variable {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (SMap α β) := ⟨{}⟩ def empty : SMap α β := {} @[inline] def fromHashMap (m : HashMap α β) (stage₁ := true) : SMap α β := { map₁ := m, stage₁ := stage₁ } @[specialize] def insert : SMap α β → α → β → SMap α β | ⟨true, m₁, m₂⟩, k, v => ⟨true, m₁.insert k v, m₂⟩ | ⟨false, m₁, m₂⟩, k, v => ⟨false, m₁, m₂.insert k v⟩ @[specialize] def insert' : SMap α β → α → β → SMap α β | ⟨true, m₁, m₂⟩, k, v => ⟨true, m₁.insert k v, m₂⟩ | ⟨false, m₁, m₂⟩, k, v => ⟨false, m₁, m₂.insert k v⟩ @[specialize] def find? : SMap α β → α → Option β | ⟨true, m₁, _⟩, k => m₁.find? k | ⟨false, m₁, m₂⟩, k => (m₂.find? k).orElse fun _ => m₁.find? k @[inline] def findD (m : SMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : SMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[specialize] def contains : SMap α β → α → Bool | ⟨true, m₁, _⟩, k => m₁.contains k | ⟨false, m₁, m₂⟩, k => m₁.contains k || m₂.contains k /- Similar to `find?`, but searches for result in the hashmap first. So, the result is correct only if we never "overwrite" `map₁` entries using `map₂`. -/ @[specialize] def find?' : SMap α β → α → Option β | ⟨true, m₁, _⟩, k => m₁.find? k | ⟨false, m₁, m₂⟩, k => (m₁.find? k).orElse fun _ => m₂.find? k def forM [Monad m] (s : SMap α β) (f : α → β → m PUnit) : m PUnit := do s.map₁.forM f s.map₂.forM f /- Move from stage 1 into stage 2. -/ def switch (m : SMap α β) : SMap α β := if m.stage₁ then { m with stage₁ := false } else m @[inline] def foldStage2 {σ : Type w} (f : σ → α → β → σ) (s : σ) (m : SMap α β) : σ := m.map₂.foldl f s def fold {σ : Type w} (f : σ → α → β → σ) (init : σ) (m : SMap α β) : σ := m.map₂.foldl f $ m.map₁.fold f init def size (m : SMap α β) : Nat := m.map₁.size + m.map₂.size def stageSizes (m : SMap α β) : Nat × Nat := (m.map₁.size, m.map₂.size) def numBuckets (m : SMap α β) : Nat := m.map₁.numBuckets def toList (m : SMap α β) : List (α × β) := m.fold (init := []) fun es a b => (a, b)::es end SMap def List.toSMap [BEq α] [Hashable α] (es : List (α × β)) : SMap α β := es.foldl (init := {}) fun s (a, b) => s.insert a b instance {_ : BEq α} {_ : Hashable α} [Repr α] [Repr β] : Repr (SMap α β) where reprPrec v prec := Repr.addAppParen (reprArg v.toList ++ ".toSMap") prec end Lean
109496f8f200d5a4ac4aeb97d8d02bc218d28f69
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/list/default_auto.lean
f9684c4a9c470718e7f4580f705ae494558f3f8c
[]
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
403
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.list.basic import Mathlib.Lean3Lib.init.data.list.instances import Mathlib.Lean3Lib.init.data.list.lemmas import Mathlib.Lean3Lib.init.data.list.qsort namespace Mathlib end Mathlib
729ebff79538ae169cd0ad99ebdded51ffe932e8
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/order/compactly_generated.lean
6eb7b15458e1d559a116dec8c41cdfb3f9f865e5
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
22,898
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import tactic.tfae import order.atoms import order.order_iso_nat import order.sup_indep import order.zorn import data.finset.order import data.finite.default /-! # Compactness properties for complete lattices For complete lattices, there are numerous equivalent ways to express the fact that the relation `>` is well-founded. In this file we define three especially-useful characterisations and provide proofs that they are indeed equivalent to well-foundedness. ## Main definitions * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `complete_lattice.is_compact_element` * `complete_lattice.is_compactly_generated` ## Main results The main result is that the following four conditions are equivalent for a complete lattice: * `well_founded (>)` * `complete_lattice.is_sup_closed_compact` * `complete_lattice.is_Sup_finite_compact` * `∀ k, complete_lattice.is_compact_element k` This is demonstrated by means of the following four lemmas: * `complete_lattice.well_founded.is_Sup_finite_compact` * `complete_lattice.is_Sup_finite_compact.is_sup_closed_compact` * `complete_lattice.is_sup_closed_compact.well_founded` * `complete_lattice.is_Sup_finite_compact_iff_all_elements_compact` We also show well-founded lattices are compactly generated (`complete_lattice.compactly_generated_of_well_founded`). ## References - [G. Călugăreanu, *Lattice Concepts of Module Theory*][calugareanu] ## Tags complete lattice, well-founded, compact -/ variables {α : Type*} [complete_lattice α] namespace complete_lattice variables (α) /-- A compactness property for a complete lattice is that any `sup`-closed non-empty subset contains its `Sup`. -/ def is_sup_closed_compact : Prop := ∀ (s : set α) (h : s.nonempty), (∀ a b ∈ s, a ⊔ b ∈ s) → (Sup s) ∈ s /-- A compactness property for a complete lattice is that any subset has a finite subset with the same `Sup`. -/ def is_Sup_finite_compact : Prop := ∀ (s : set α), ∃ (t : finset α), ↑t ⊆ s ∧ Sup s = t.sup id /-- An element `k` of a complete lattice is said to be compact if any set with `Sup` above `k` has a finite subset with `Sup` above `k`. Such an element is also called "finite" or "S-compact". -/ def is_compact_element {α : Type*} [complete_lattice α] (k : α) := ∀ s : set α, k ≤ Sup s → ∃ t : finset α, ↑t ⊆ s ∧ k ≤ t.sup id lemma {u} is_compact_element_iff {α : Type u} [complete_lattice α] (k : α) : complete_lattice.is_compact_element k ↔ ∀ (ι : Type u) (s : ι → α), k ≤ supr s → ∃ t : finset ι, k ≤ t.sup s := begin classical, split, { intros H ι s hs, obtain ⟨t, ht, ht'⟩ := H (set.range s) hs, have : ∀ x : t, ∃ i, s i = x := λ x, ht x.prop, choose f hf using this, refine ⟨finset.univ.image f, ht'.trans _⟩, { rw finset.sup_le_iff, intros b hb, rw ← (show s (f ⟨b, hb⟩) = id b, from hf _), exact finset.le_sup (finset.mem_image_of_mem f $ finset.mem_univ ⟨b, hb⟩) } }, { intros H s hs, obtain ⟨t, ht⟩ := H s coe (by { delta supr, rwa subtype.range_coe }), refine ⟨t.image coe, by simp, ht.trans _⟩, rw finset.sup_le_iff, exact λ x hx, @finset.le_sup _ _ _ _ _ id _ (finset.mem_image_of_mem coe hx) } end /-- An element `k` is compact if and only if any directed set with `Sup` above `k` already got above `k` at some point in the set. -/ theorem is_compact_element_iff_le_of_directed_Sup_le (k : α) : is_compact_element k ↔ ∀ s : set α, s.nonempty → directed_on (≤) s → k ≤ Sup s → ∃ x : α, x ∈ s ∧ k ≤ x := begin classical, split, { intros hk s hne hdir hsup, obtain ⟨t, ht⟩ := hk s hsup, -- certainly every element of t is below something in s, since ↑t ⊆ s. have t_below_s : ∀ x ∈ t, ∃ y ∈ s, x ≤ y, from λ x hxt, ⟨x, ht.left hxt, le_rfl⟩, obtain ⟨x, ⟨hxs, hsupx⟩⟩ := finset.sup_le_of_le_directed s hne hdir t t_below_s, exact ⟨x, ⟨hxs, le_trans ht.right hsupx⟩⟩, }, { intros hk s hsup, -- Consider the set of finite joins of elements of the (plain) set s. let S : set α := { x | ∃ t : finset α, ↑t ⊆ s ∧ x = t.sup id }, -- S is directed, nonempty, and still has sup above k. have dir_US : directed_on (≤) S, { rintros x ⟨c, hc⟩ y ⟨d, hd⟩, use x ⊔ y, split, { use c ∪ d, split, { simp only [hc.left, hd.left, set.union_subset_iff, finset.coe_union, and_self], }, { simp only [hc.right, hd.right, finset.sup_union], }, }, simp only [and_self, le_sup_left, le_sup_right], }, have sup_S : Sup s ≤ Sup S, { apply Sup_le_Sup, intros x hx, use {x}, simpa only [and_true, id.def, finset.coe_singleton, eq_self_iff_true, finset.sup_singleton, set.singleton_subset_iff], }, have Sne : S.nonempty, { suffices : ⊥ ∈ S, from set.nonempty_of_mem this, use ∅, simp only [set.empty_subset, finset.coe_empty, finset.sup_empty, eq_self_iff_true, and_self], }, -- Now apply the defn of compact and finish. obtain ⟨j, ⟨hjS, hjk⟩⟩ := hk S Sne dir_US (le_trans hsup sup_S), obtain ⟨t, ⟨htS, htsup⟩⟩ := hjS, use t, exact ⟨htS, by rwa ←htsup⟩, }, end lemma is_compact_element.exists_finset_of_le_supr {k : α} (hk : is_compact_element k) {ι : Type*} (f : ι → α) (h : k ≤ ⨆ i, f i) : ∃ s : finset ι, k ≤ ⨆ i ∈ s, f i := begin classical, let g : finset ι → α := λ s, ⨆ i ∈ s, f i, have h1 : directed_on (≤) (set.range g), { rintros - ⟨s, rfl⟩ - ⟨t, rfl⟩, exact ⟨g (s ∪ t), ⟨s ∪ t, rfl⟩, supr_le_supr_of_subset (finset.subset_union_left s t), supr_le_supr_of_subset (finset.subset_union_right s t)⟩ }, have h2 : k ≤ Sup (set.range g), { exact h.trans (supr_le (λ i, le_Sup_of_le ⟨{i}, rfl⟩ (le_supr_of_le i (le_supr_of_le (finset.mem_singleton_self i) le_rfl)))) }, obtain ⟨-, ⟨s, rfl⟩, hs⟩ := (is_compact_element_iff_le_of_directed_Sup_le α k).mp hk (set.range g) (set.range_nonempty g) h1 h2, exact ⟨s, hs⟩, end /-- A compact element `k` has the property that any directed set lying strictly below `k` has its Sup strictly below `k`. -/ lemma is_compact_element.directed_Sup_lt_of_lt {α : Type*} [complete_lattice α] {k : α} (hk : is_compact_element k) {s : set α} (hemp : s.nonempty) (hdir : directed_on (≤) s) (hbelow : ∀ x ∈ s, x < k) : Sup s < k := begin rw is_compact_element_iff_le_of_directed_Sup_le at hk, by_contradiction, have sSup : Sup s ≤ k, from Sup_le (λ s hs, (hbelow s hs).le), replace sSup : Sup s = k := eq_iff_le_not_lt.mpr ⟨sSup, h⟩, obtain ⟨x, hxs, hkx⟩ := hk s hemp hdir sSup.symm.le, obtain hxk := hbelow x hxs, exact hxk.ne (hxk.le.antisymm hkx), end lemma finset_sup_compact_of_compact {α β : Type*} [complete_lattice α] {f : β → α} (s : finset β) (h : ∀ x ∈ s, is_compact_element (f x)) : is_compact_element (s.sup f) := begin classical, rw is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, change f with id ∘ f, rw ←finset.sup_finset_image, apply finset.sup_le_of_le_directed d hemp hdir, rintros x hx, obtain ⟨p, ⟨hps, rfl⟩⟩ := finset.mem_image.mp hx, specialize h p hps, rw is_compact_element_iff_le_of_directed_Sup_le at h, specialize h d hemp hdir (le_trans (finset.le_sup hps) hsup), simpa only [exists_prop], end lemma well_founded.is_Sup_finite_compact (h : well_founded ((>) : α → α → Prop)) : is_Sup_finite_compact α := begin intros s, let p : set α := { x | ∃ (t : finset α), ↑t ⊆ s ∧ t.sup id = x }, have hp : p.nonempty, { use [⊥, ∅], simp, }, obtain ⟨m, ⟨t, ⟨ht₁, ht₂⟩⟩, hm⟩ := well_founded.well_founded_iff_has_max'.mp h p hp, use t, simp only [ht₁, ht₂, true_and], apply le_antisymm, { apply Sup_le, intros y hy, classical, have hy' : (insert y t).sup id ∈ p, { use insert y t, simp, rw set.insert_subset, exact ⟨hy, ht₁⟩, }, have hm' : m ≤ (insert y t).sup id, { rw ← ht₂, exact finset.sup_mono (t.subset_insert y), }, rw ← hm _ hy' hm', simp, }, { rw [← ht₂, finset.sup_id_eq_Sup], exact Sup_le_Sup ht₁, }, end lemma is_Sup_finite_compact.is_sup_closed_compact (h : is_Sup_finite_compact α) : is_sup_closed_compact α := begin intros s hne hsc, obtain ⟨t, ht₁, ht₂⟩ := h s, clear h, cases t.eq_empty_or_nonempty with h h, { subst h, rw finset.sup_empty at ht₂, rw ht₂, simp [eq_singleton_bot_of_Sup_eq_bot_of_nonempty ht₂ hne], }, { rw ht₂, exact t.sup_closed_of_sup_closed h ht₁ hsc, }, end lemma is_sup_closed_compact.well_founded (h : is_sup_closed_compact α) : well_founded ((>) : α → α → Prop) := begin refine rel_embedding.well_founded_iff_no_descending_seq.mpr ⟨λ a, _⟩, suffices : Sup (set.range a) ∈ set.range a, { obtain ⟨n, hn⟩ := set.mem_range.mp this, have h' : Sup (set.range a) < a (n+1), { change _ > _, simp [← hn, a.map_rel_iff], }, apply lt_irrefl (a (n+1)), apply lt_of_le_of_lt _ h', apply le_Sup, apply set.mem_range_self, }, apply h (set.range a), { use a 37, apply set.mem_range_self, }, { rintros x ⟨m, hm⟩ y ⟨n, hn⟩, use m ⊔ n, rw [← hm, ← hn], apply rel_hom_class.map_sup a, }, end lemma is_Sup_finite_compact_iff_all_elements_compact : is_Sup_finite_compact α ↔ (∀ k : α, is_compact_element k) := begin refine ⟨λ h k s hs, _, λ h s, _⟩, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h s, use [t, hts], rwa ←htsup, }, { obtain ⟨t, ⟨hts, htsup⟩⟩ := h (Sup s) s (by refl), have : Sup s = t.sup id, { suffices : t.sup id ≤ Sup s, by { apply le_antisymm; assumption }, simp only [id.def, finset.sup_le_iff], intros x hx, exact le_Sup (hts hx) }, use [t, hts, this] }, end lemma well_founded_characterisations : tfae [well_founded ((>) : α → α → Prop), is_Sup_finite_compact α, is_sup_closed_compact α, ∀ k : α, is_compact_element k] := begin tfae_have : 1 → 2, by { exact well_founded.is_Sup_finite_compact α, }, tfae_have : 2 → 3, by { exact is_Sup_finite_compact.is_sup_closed_compact α, }, tfae_have : 3 → 1, by { exact is_sup_closed_compact.well_founded α, }, tfae_have : 2 ↔ 4, by { exact is_Sup_finite_compact_iff_all_elements_compact α }, tfae_finish, end lemma well_founded_iff_is_Sup_finite_compact : well_founded ((>) : α → α → Prop) ↔ is_Sup_finite_compact α := (well_founded_characterisations α).out 0 1 lemma is_Sup_finite_compact_iff_is_sup_closed_compact : is_Sup_finite_compact α ↔ is_sup_closed_compact α := (well_founded_characterisations α).out 1 2 lemma is_sup_closed_compact_iff_well_founded : is_sup_closed_compact α ↔ well_founded ((>) : α → α → Prop) := (well_founded_characterisations α).out 2 0 alias well_founded_iff_is_Sup_finite_compact ↔ _ is_Sup_finite_compact.well_founded alias is_Sup_finite_compact_iff_is_sup_closed_compact ↔ _ is_sup_closed_compact.is_Sup_finite_compact alias is_sup_closed_compact_iff_well_founded ↔ _ _root_.well_founded.is_sup_closed_compact variables {α} lemma well_founded.finite_of_set_independent (h : well_founded ((>) : α → α → Prop)) {s : set α} (hs : set_independent s) : s.finite := begin classical, refine set.not_infinite.mp (λ contra, _), obtain ⟨t, ht₁, ht₂⟩ := well_founded.is_Sup_finite_compact α h s, replace contra : ∃ (x : α), x ∈ s ∧ x ≠ ⊥ ∧ x ∉ t, { have : (s \ (insert ⊥ t : finset α)).infinite := contra.diff (finset.finite_to_set _), obtain ⟨x, hx₁, hx₂⟩ := this.nonempty, exact ⟨x, hx₁, by simpa [not_or_distrib] using hx₂⟩, }, obtain ⟨x, hx₀, hx₁, hx₂⟩ := contra, replace hs : x ⊓ Sup s = ⊥, { have := hs.mono (by simp [ht₁, hx₀, -set.union_singleton] : ↑t ∪ {x} ≤ s) (by simp : x ∈ _), simpa [disjoint, hx₂, ← t.sup_id_eq_Sup, ← ht₂] using this, }, apply hx₁, rw [← hs, eq_comm, inf_eq_left], exact le_Sup hx₀, end lemma well_founded.finite_of_independent (hwf : well_founded ((>) : α → α → Prop)) {ι : Type*} {t : ι → α} (ht : independent t) (h_ne_bot : ∀ i, t i ≠ ⊥) : finite ι := begin haveI := (well_founded.finite_of_set_independent hwf ht.set_independent_range).to_subtype, exact finite.of_injective_finite_range (ht.injective h_ne_bot), end end complete_lattice /-- A complete lattice is said to be compactly generated if any element is the `Sup` of compact elements. -/ class is_compactly_generated (α : Type*) [complete_lattice α] : Prop := (exists_Sup_eq : ∀ (x : α), ∃ (s : set α), (∀ x ∈ s, complete_lattice.is_compact_element x) ∧ Sup s = x) section variables {α} [is_compactly_generated α] {a b : α} {s : set α} @[simp] lemma Sup_compact_le_eq (b) : Sup {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} = b := begin rcases is_compactly_generated.exists_Sup_eq b with ⟨s, hs, rfl⟩, exact le_antisymm (Sup_le (λ c hc, hc.2)) (Sup_le_Sup (λ c cs, ⟨hs c cs, le_Sup cs⟩)), end @[simp] theorem Sup_compact_eq_top : Sup {a : α | complete_lattice.is_compact_element a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_compact_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_compact_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, complete_lattice.is_compact_element c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_compact_le_eq a, ← Sup_compact_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ /-- This property is sometimes referred to as `α` being upper continuous. -/ theorem inf_Sup_eq_of_directed_on (h : directed_on (≤) s): a ⊓ Sup s = ⨆ b ∈ s, a ⊓ b := le_antisymm (begin rw le_iff_compact_le_imp, by_cases hs : s.nonempty, { intros c hc hcinf, rw le_inf_iff at hcinf, rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le at hc, rcases hc s hs h hcinf.2 with ⟨d, ds, cd⟩, exact (le_inf hcinf.1 cd).trans (le_supr₂ d ds) }, { rw set.not_nonempty_iff_eq_empty at hs, simp [hs] } end) supr_inf_le_inf_Sup /-- This property is equivalent to `α` being upper continuous. -/ theorem inf_Sup_eq_supr_inf_sup_finset : a ⊓ Sup s = ⨆ (t : finset α) (H : ↑t ⊆ s), a ⊓ (t.sup id) := le_antisymm (begin rw le_iff_compact_le_imp, intros c hc hcinf, rw le_inf_iff at hcinf, rcases hc s hcinf.2 with ⟨t, ht1, ht2⟩, exact (le_inf hcinf.1 ht2).trans (le_supr₂ t ht1), end) (supr_le $ λ t, supr_le $ λ h, inf_le_inf_left _ ((finset.sup_id_eq_Sup t).symm ▸ (Sup_le_Sup h))) theorem complete_lattice.set_independent_iff_finite {s : set α} : complete_lattice.set_independent s ↔ ∀ t : finset α, ↑t ⊆ s → complete_lattice.set_independent (↑t : set α) := ⟨λ hs t ht, hs.mono ht, λ h a ha, begin rw [disjoint_iff, inf_Sup_eq_supr_inf_sup_finset, supr_eq_bot], intro t, rw [supr_eq_bot, finset.sup_id_eq_Sup], intro ht, classical, have h' := (h (insert a t) _ (t.mem_insert_self a)).eq_bot, { rwa [finset.coe_insert, set.insert_diff_self_of_not_mem] at h', exact λ con, ((set.mem_diff a).1 (ht con)).2 (set.mem_singleton a) }, { rw [finset.coe_insert, set.insert_subset], exact ⟨ha, set.subset.trans ht (set.diff_subset _ _)⟩ } end⟩ lemma complete_lattice.set_independent_Union_of_directed {η : Type*} {s : η → set α} (hs : directed (⊆) s) (h : ∀ i, complete_lattice.set_independent (s i)) : complete_lattice.set_independent (⋃ i, s i) := begin by_cases hη : nonempty η, { resetI, rw complete_lattice.set_independent_iff_finite, intros t ht, obtain ⟨I, fi, hI⟩ := set.finite_subset_Union t.finite_to_set ht, obtain ⟨i, hi⟩ := hs.finset_le fi.to_finset, exact (h i).mono (set.subset.trans hI $ set.Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { rintros a ⟨_, ⟨i, _⟩, _⟩, exfalso, exact hη ⟨i⟩, }, end lemma complete_lattice.independent_sUnion_of_directed {s : set (set α)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, complete_lattice.set_independent a) : complete_lattice.set_independent (⋃₀ s) := by rw set.sUnion_eq_Union; exact complete_lattice.set_independent_Union_of_directed hs.directed_coe (by simpa using h) end namespace complete_lattice lemma compactly_generated_of_well_founded (h : well_founded ((>) : α → α → Prop)) : is_compactly_generated α := begin rw [well_founded_iff_is_Sup_finite_compact, is_Sup_finite_compact_iff_all_elements_compact] at h, -- x is the join of the set of compact elements {x} exact ⟨λ x, ⟨{x}, ⟨λ x _, h x, Sup_singleton⟩⟩⟩, end /-- A compact element `k` has the property that any `b < k` lies below a "maximal element below `k`", which is to say `[⊥, k]` is coatomic. -/ theorem Iic_coatomic_of_compact_element {k : α} (h : is_compact_element k) : is_coatomic (set.Iic k) := ⟨λ ⟨b, hbk⟩, begin by_cases htriv : b = k, { left, ext, simp only [htriv, set.Iic.coe_top, subtype.coe_mk], }, right, obtain ⟨a, a₀, ba, h⟩ := zorn_nonempty_partial_order₀ (set.Iio k) _ b (lt_of_le_of_ne hbk htriv), { refine ⟨⟨a, le_of_lt a₀⟩, ⟨ne_of_lt a₀, λ c hck, by_contradiction $ λ c₀, _⟩, ba⟩, cases h c.1 (lt_of_le_of_ne c.2 (λ con, c₀ (subtype.ext con))) hck.le, exact lt_irrefl _ hck, }, { intros S SC cC I IS, by_cases hS : S.nonempty, { exact ⟨Sup S, h.directed_Sup_lt_of_lt hS cC.directed_on SC, λ _, le_Sup⟩, }, exact ⟨b, lt_of_le_of_ne hbk htriv, by simp only [set.not_nonempty_iff_eq_empty.mp hS, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff]⟩, }, end⟩ lemma coatomic_of_top_compact (h : is_compact_element (⊤ : α)) : is_coatomic α := (@order_iso.Iic_top α _ _).is_coatomic_iff.mp (Iic_coatomic_of_compact_element h) end complete_lattice section variables [is_modular_lattice α] [is_compactly_generated α] @[priority 100] instance is_atomic_of_is_complemented [is_complemented α] : is_atomic α := ⟨λ b, begin by_cases h : {c : α | complete_lattice.is_compact_element c ∧ c ≤ b} ⊆ {⊥}, { left, rw [← Sup_compact_le_eq b, Sup_eq_bot], exact h }, { rcases set.not_subset.1 h with ⟨c, ⟨hc, hcb⟩, hcbot⟩, right, have hc' := complete_lattice.Iic_coatomic_of_compact_element hc, rw ← is_atomic_iff_is_coatomic at hc', haveI := hc', obtain con | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le (⟨c, le_refl c⟩ : set.Iic c), { exfalso, apply hcbot, simp only [subtype.ext_iff, set.Iic.coe_bot, subtype.coe_mk] at con, exact con }, rw [← subtype.coe_le_coe, subtype.coe_mk] at hac, exact ⟨a, ha.of_is_atom_coe_Iic, hac.trans hcb⟩ }, end⟩ /-- See Lemma 5.1, Călugăreanu -/ @[priority 100] instance is_atomistic_of_is_complemented [is_complemented α] : is_atomistic α := ⟨λ b, ⟨{a | is_atom a ∧ a ≤ b}, begin symmetry, have hle : Sup {a : α | is_atom a ∧ a ≤ b} ≤ b := (Sup_le $ λ _, and.right), apply (lt_or_eq_of_le hle).resolve_left (λ con, _), obtain ⟨c, hc⟩ := exists_is_compl (⟨Sup {a : α | is_atom a ∧ a ≤ b}, hle⟩ : set.Iic b), obtain rfl | ⟨a, ha, hac⟩ := eq_bot_or_exists_atom_le c, { exact ne_of_lt con (subtype.ext_iff.1 (eq_top_of_is_compl_bot hc)) }, { apply ha.1, rw eq_bot_iff, apply le_trans (le_inf _ hac) hc.1, rw [← subtype.coe_le_coe, subtype.coe_mk], exact le_Sup ⟨ha.of_is_atom_coe_Iic, a.2⟩ } end, λ _, and.left⟩⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_Sup_atoms_eq_top (h : Sup {a : α | is_atom a} = ⊤) : is_complemented α := ⟨λ b, begin obtain ⟨s, ⟨s_ind, b_inf_Sup_s, s_atoms⟩, s_max⟩ := zorn_subset {s : set α | complete_lattice.set_independent s ∧ b ⊓ Sup s = ⊥ ∧ ∀ a ∈ s, is_atom a} _, { refine ⟨Sup s, le_of_eq b_inf_Sup_s, h.symm.trans_le $ Sup_le_iff.2 $ λ a ha, _⟩, rw ← inf_eq_left, refine (ha.le_iff.mp inf_le_left).resolve_left (λ con, ha.1 _), rw [eq_bot_iff, ← con], refine le_inf (le_refl a) ((le_Sup _).trans le_sup_right), rw ← disjoint_iff at *, have a_dis_Sup_s : disjoint a (Sup s) := con.mono_right le_sup_right, rw ← s_max (s ∪ {a}) ⟨λ x hx, _, ⟨_, λ x hx, _⟩⟩ (set.subset_union_left _ _), { exact set.mem_union_right _ (set.mem_singleton _) }, { rw [set.mem_union, set.mem_singleton_iff] at hx, by_cases xa : x = a, { simp only [xa, set.mem_singleton, set.insert_diff_of_mem, set.union_singleton], exact con.mono_right (le_trans (Sup_le_Sup (set.diff_subset s {a})) le_sup_right) }, { have h : (s ∪ {a}) \ {x} = (s \ {x}) ∪ {a}, { simp only [set.union_singleton], rw set.insert_diff_of_not_mem, rw set.mem_singleton_iff, exact ne.symm xa }, rw [h, Sup_union, Sup_singleton], apply (s_ind (hx.resolve_right xa)).disjoint_sup_right_of_disjoint_sup_left (a_dis_Sup_s.mono_right _).symm, rw [← Sup_insert, set.insert_diff_singleton, set.insert_eq_of_mem (hx.resolve_right xa)] } }, { rw [Sup_union, Sup_singleton, ← disjoint_iff], exact b_inf_Sup_s.disjoint_sup_right_of_disjoint_sup_left con.symm }, { rw [set.mem_union, set.mem_singleton_iff] at hx, cases hx, { exact s_atoms x hx }, { rw hx, exact ha } } }, { intros c hc1 hc2, refine ⟨⋃₀ c, ⟨complete_lattice.independent_sUnion_of_directed hc2.directed_on (λ s hs, (hc1 hs).1), _, λ a ha, _⟩, λ _, set.subset_sUnion_of_mem⟩, { rw [Sup_sUnion, ← Sup_image, inf_Sup_eq_of_directed_on, supr_eq_bot], { intro i, rw supr_eq_bot, intro hi, obtain ⟨x, xc, rfl⟩ := (set.mem_image _ _ _).1 hi, exact (hc1 xc).2.1 }, { rw directed_on_image, refine hc2.directed_on.mono (λ s t, Sup_le_Sup) } }, { rcases set.mem_sUnion.1 ha with ⟨s, sc, as⟩, exact (hc1 sc).2.2 a as } } end⟩ /-- See Theorem 6.6, Călugăreanu -/ theorem is_complemented_of_is_atomistic [is_atomistic α] : is_complemented α := is_complemented_of_Sup_atoms_eq_top Sup_atoms_eq_top theorem is_complemented_iff_is_atomistic : is_complemented α ↔ is_atomistic α := begin split; introsI, { exact is_atomistic_of_is_complemented }, { exact is_complemented_of_is_atomistic } end end
6f3cfb8b94612559732ea46e4036dc677ac6a474
398b53a5e02ce35196531591f84bb2f6b034ce5a
/paper/proof.lean
ac4bb10bdfb708788a8b5a622dfa122656876fac
[ "MIT" ]
permissive
crockeo/math-exercises
64f07a9371a72895bbd97f49a854dcb6821b18ab
cf9150ef9e025f1b7929ba070a783e7a71f24f31
refs/heads/master
1,607,910,221,030
1,581,231,762,000
1,581,231,762,000
234,595,189
0
0
null
null
null
null
UTF-8
Lean
false
false
6,418
lean
-- Title: Generation in Optimality Theory with Lexical Insertion is Undecidable -- -- Author: Cerek Hillen -- -- Description: -- Here we show that PCP is reducible to OT. In particular, we show that when -- there exists a solution to PCP, there exists a solution to OT, and when -- there does not exist a solution to PCP, there does not exist a solution to -- OT. -- -- Because PCP is known to be Turing Complete, this reduction proves that OT -- is also Turing Complete. import data.vector universes u v -------------------------------------------------------------------------------- -- PCP -- -------------------------------------------------------------------------------- -- Defining PCP structure pcp {n : ℕ} (Γ : Type) (tops : vector (list Γ) n) (bottoms : vector (list Γ) n) : Type namespace pcp open vector -- Defining the composition of a vector of symbols by a sequence. Used to -- define the existence of a solution for PCP. def compose {Γ : Type} {n : ℕ} : Π (symbols : vector (list Γ) n), list (fin n) → list Γ | symbols list.nil := list.nil | symbols (list.cons i l) := list.append (nth symbols i) (compose symbols l) -- The property of an instance of PCP having a solution. In plain English, -- an instance of PCP has a solution iff there exists a sequence of indicies -- such that the composition of the indexed tops and bottoms are equal. def has_solution {n : ℕ} {Γ : Type} {tops : vector (list Γ) n} {bottoms : vector (list Γ) n} : pcp Γ tops bottoms → Prop | _ := ∃ (seq : list (fin n)), compose tops seq = compose bottoms seq end pcp -------------------------------------------------------------------------------- -- Optimality Theory -- -------------------------------------------------------------------------------- namespace ot open vector -- We define a score to be a vector of natural numbers of length n. Each value -- score_i corresponds to the number of violations that occurred in the ith -- constraint. def score (n : ℕ) := vector ℕ n -- We define an ordering on scores such that s₁ ≤ s₂ iff they are equal up to -- some index i, wherein s₁[i] ≤ s₂[i]. -- -- TODO: This definition isn't going to work, because you can prove it by -- using an index larger than n for i. def score_lte {n : ℕ} (s1 : score n) (s2 : score n) : Prop := ∃ (i : ℕ), Π (ltin : i < n), (nth s1 (fin.mk i ltin)) ≤ (nth s2 (fin.mk i ltin)) ∧ ∀ (j : ℕ), Π (ltji : j < i), (nth s1 ⟨j, lt.trans ltji ltin⟩) = (nth s2 ⟨j, lt.trans ltji ltin⟩) -- TODO: Define the rest of OT end ot -------------------------------------------------------------------------------- -- Proof -- -------------------------------------------------------------------------------- -- Step 1. Reduce from an arbitrary case of PCP to a case of PCP where there -- exist only two characters. -- Definition of a binary language inductive bin | a : bin | b : bin def alphabet_width : Type → ℕ := sorry def map_to_binary {n : ℕ} {Γ : Type} {tops : vector (list Γ) n} {bottoms : vector (list Γ) n} {new_tops : vector (list bin) (n * alphabet_width Γ)} {new_bottoms : vector (list bin) (n * alphabet_width Γ)}: pcp Γ tops bottoms → pcp bin new_tops new_bottoms := sorry -- TODO: Debug it -- theorem binary_equivalence {n : ℕ} -- {Γ : Type} -- {tops bottoms : vector (list Γ) n} -- (problem : pcp Γ tops bottoms) : -- problem.has_solution ↔ (map_to_binary problem).has_solution := -- begin -- split, -- sorry, -- end -- Step 2. Provide our mapping from an arbitrary instance of PCP to an arbitrary -- instance of OT. -- TODO -- Step 3. Show that PCP has a solution if and only if our mapped version of OT -- has a solution. -- TODO -------------------------------------------------------------------------------- -- Misc / Testing -- -------------------------------------------------------------------------------- -- Proving that a simple instance of PCP has a solution. namespace hidden_has_solution inductive Γ | a : Γ | b : Γ open Γ def top_l := [[b], [a]] def bot_l := [[], [b, a]] def tops : vector (list Γ) 2 := ⟨top_l, by refl⟩ def bottoms : vector (list Γ) 2 := ⟨bot_l, by refl⟩ theorem simple_pcp (problem : pcp Γ tops bottoms) : problem.has_solution := begin existsi [[ (0 : fin 2), (1 : fin 2) ]], refl, end #print simple_pcp end hidden_has_solution namespace hidden_score open ot open vector def x : score 5 := ⟨[0, 0, 1, 3, 5], by refl⟩ def y : score 5 := ⟨[0, 0, 2, 1, 7], by refl⟩ example : (score_lte x y) := begin existsi 2, intro ltin, rw x, rw y, split, { repeat {rw nth}, repeat {rw list.nth_le}, exact nat.less_than_or_equal.step (nat.less_than_or_equal.refl 1), }, { intros j ltji, repeat {rw nth}, cases j, any_goals { cases j }, any_goals { repeat {rw list.nth_le}, }, have h : j < 0, from nat.le_of_succ_le_succ (nat.le_of_succ_le_succ ltji), exfalso, exact (nat.not_lt_zero j) h, }, end end hidden_score -- NOTE: This example shows that our definition of ordering for score vectors is -- broken. We can show that x ≤ y, even though in fact x > y. I should -- change the defn above to be a conjunct, rather than an implication. -- I.e. (i < n) ∧ ..., not (Π (ltin : i < n), ... namespace hidden_break_score open ot open vector def x : score 5 := ⟨[0, 0, 2, 3, 5], by refl⟩ def y : score 5 := ⟨[0, 0, 1, 1, 7], by refl⟩ example : (score_lte x y) := begin existsi 5, assume h, have h' : 0 < 0, sorry, exfalso, exact (nat.not_lt_zero 0) h', end end hidden_break_score
58a2da61c8d04fe19d8c9d0c2dc36526b64d1917
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1585.lean
4911c4a3c45ba9c7135e659b76a32497f8f1cae8
[ "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
85
lean
structure foo (α : Type) extends has_le α structure bar (α : Type) extends foo α
bff08966b0e31a8d0a69652bf30489b6c4008f48
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/init/meta/interactive_base.lean
70743f486dd691902f64ff45ac30df67693b1d4d
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,307
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.data.option.instances import init.meta.lean.parser init.meta.tactic init.meta.has_reflect open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace interactive /-- (parse p) as the parameter type of an interactive tactic will instruct the Lean parser to run `p` when parsing the parameter and to pass the parsed value as an argument to the tactic. -/ @[reducible] meta def parse {α : Type} [has_reflect α] (p : parser α) : Type := α inductive loc : Type | wildcard : loc | ns : list name → loc meta instance : has_reflect loc | loc.wildcard := `(_) | (loc.ns xs) := `(_) meta def loc.include_goal : loc → bool | loc.wildcard := tt | (loc.ns []) := tt | _ := ff meta def loc.get_locals : loc → tactic (list expr) | loc.wildcard := tactic.local_context | (loc.ns xs) := mmap tactic.get_local xs namespace types variables {α β : Type} -- optimized pretty printer meta def brackets (l r : string) (p : parser α) := tk l *> p <* tk r meta def list_of (p : parser α) := brackets "[" "]" $ sep_by (skip_info (tk ",")) p /-- A 'tactic expression', which uses right-binding power 2 so that it is terminated by '<|>' (rbp 2), ';' (rbp 1), and ',' (rbp 0). It should be used for any (potentially) trailing expression parameters. -/ meta def texpr := qexpr 2 /-- Parse an identifier or a '_' -/ meta def ident_ : parser name := ident <|> tk "_" *> return `_ meta def using_ident := (tk "using" *> ident)? meta def with_ident_list := (tk "with" *> ident_*) <|> return [] meta def without_ident_list := (tk "without" *> ident*) <|> return [] meta def location := (tk "at" *> (tk "*" *> return loc.wildcard <|> (loc.ns <$> ident*))) <|> return (loc.ns []) meta def qexpr_list := list_of (qexpr 0) meta def opt_qexpr_list := qexpr_list <|> return [] meta def qexpr_list_or_texpr := qexpr_list <|> list.ret <$> texpr meta def only_flag : parser bool := (tk "only" *> return tt) <|> return ff end types precedence only:0 /-- Use `desc` as the interactive description of `p`. -/ meta def with_desc {α : Type} (desc : format) (p : parser α) : parser α := p open expr format tactic types private meta def maybe_paren : list format → format | [] := "" | [f] := f | fs := paren (join fs) private meta def unfold (e : expr) : tactic expr := do (expr.const f_name f_lvls) ← return e.get_app_fn | failed, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, head_beta (expr.mk_app new_f e.get_app_args) private meta def concat (f₁ f₂ : list format) := if f₁.empty then f₂ else if f₂.empty then f₁ else f₁ ++ [" "] ++ f₂ private meta def parser_desc_aux : expr → tactic (list format) | `(ident) := return ["id"] | `(ident_) := return ["id"] | `(qexpr) := return ["expr"] | `(tk %%c) := list.ret <$> to_fmt <$> eval_expr string c | `(cur_pos) := return [] | `(pure ._) := return [] | `(._ <$> %%p) := parser_desc_aux p | `(skip_info %%p) := parser_desc_aux p | `(set_goal_info_pos %%p) := parser_desc_aux p | `(with_desc %%desc %%p) := list.ret <$> eval_expr format desc | `(%%p₁ <*> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ <* %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(%%p₁ *> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ concat f₁ f₂ | `(many %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "*"] | `(optional %%p) := do f ← parser_desc_aux p, return [maybe_paren f ++ "?"] | `(sep_by %%sep %%p) := do f₁ ← parser_desc_aux sep, f₂ ← parser_desc_aux p, return [maybe_paren f₂ ++ join f₁, " ..."] | `(%%p₁ <|> %%p₂) := do f₁ ← parser_desc_aux p₁, f₂ ← parser_desc_aux p₂, return $ if f₁.empty then [maybe_paren f₂ ++ "?"] else if f₂.empty then [maybe_paren f₁ ++ "?"] else [paren $ join $ f₁ ++ [to_fmt " | "] ++ f₂] | `(brackets %%l %%r %%p) := do f ← parser_desc_aux p, l ← eval_expr string l, r ← eval_expr string r, -- much better than the naive [l, " ", f, " ", r] return [to_fmt l ++ join f ++ to_fmt r] | e := do e' ← (do e' ← unfold e, guard $ e' ≠ e, return e') <|> (do f ← pp e, fail $ to_fmt "don't know how to pretty print " ++ f), parser_desc_aux e' meta def param_desc : expr → tactic format | `(parse %%p) := join <$> parser_desc_aux p | `(opt_param %%t ._) := (++ "?") <$> pp t | e := if is_constant e ∧ (const_name e).components.ilast = `itactic then return $ to_fmt "{ tactic }" else paren <$> pp e end interactive section macros open interaction_monad open interactive private meta def parse_format : string → list char → parser pexpr | acc [] := pure ``(to_fmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ format.line ++ %%f) | acc ('{'::'{'::s) := parse_format (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_format "" s, pure ``(to_fmt %%(reflect acc) ++ to_fmt %%e ++ %%f) | acc (c::s) := parse_format (acc.str c) s reserve prefix `format! `:100 @[user_notation] meta def format_macro (_ : parse $ tk "format!") (s : string) : parser pexpr := parse_format "" s.to_list private meta def parse_sformat : string → list char → parser pexpr | acc [] := pure $ pexpr.of_expr (reflect acc) | acc ('{'::'{'::s) := parse_sformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_sformat "" s, pure ``(%%(reflect acc) ++ to_string %%e ++ %%f) | acc (c::s) := parse_sformat (acc.str c) s reserve prefix `sformat! `:100 @[user_notation] meta def sformat_macro (_ : parse $ tk "sformat!") (s : string) : parser pexpr := parse_sformat "" s.to_list end macros
933430118e0ac2fd6764b167a5f53ad3ebd709bc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/liouville/liouville_constant.lean
6cebf03edd18f9ae25b4015a82af70b5c37e941b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,763
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Jujian Zhang -/ import number_theory.liouville.basic /-! # Liouville constants This file contains a construction of a family of Liouville numbers, indexed by a natural number $m$. The most important property is that they are examples of transcendental real numbers. This fact is recorded in `liouville.is_transcendental`. More precisely, for a real number $m$, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for $1 < m$. However, there is no restriction on $m$, since, if the series does not converge, then the sum of the series is defined to be zero. We prove that, for $m \in \mathbb{N}$ satisfying $2 \le m$, Liouville's constant associated to $m$ is a transcendental number. Classically, the Liouville number for $m = 2$ is the one called ``Liouville's constant''. ## Implementation notes The indexing $m$ is eventually a natural number satisfying $2 ≤ m$. However, we prove the first few lemmas for $m \in \mathbb{R}$. -/ noncomputable theory open_locale nat big_operators open real finset namespace liouville /-- For a real number `m`, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for `1 < m`. However, there is no restriction on `m`, since, if the series does not converge, then the sum of the series is defined to be zero. -/ def liouville_number (m : ℝ) : ℝ := ∑' (i : ℕ), 1 / m ^ i! /-- `liouville_number_initial_terms` is the sum of the first `k + 1` terms of Liouville's constant, i.e. $$ \sum_{i=0}^k\frac{1}{m^{i!}}. $$ -/ def liouville_number_initial_terms (m : ℝ) (k : ℕ) : ℝ := ∑ i in range (k+1), 1 / m ^ i! /-- `liouville_number_tail` is the sum of the series of the terms in `liouville_number m` starting from `k+1`, i.e $$ \sum_{i=k+1}^\infty\frac{1}{m^{i!}}. $$ -/ def liouville_number_tail (m : ℝ) (k : ℕ) : ℝ := ∑' i, 1 / m ^ (i + (k+1))! lemma liouville_number_tail_pos {m : ℝ} (hm : 1 < m) (k : ℕ) : 0 < liouville_number_tail m k := -- replace `0` with the constantly zero series `∑ i : ℕ, 0` calc (0 : ℝ) = ∑' i : ℕ, 0 : tsum_zero.symm ... < liouville_number_tail m k : -- to show that a series with non-negative terms has strictly positive sum it suffices -- to prove that tsum_lt_tsum_of_nonneg -- 1. the terms of the zero series are indeed non-negative (λ _, rfl.le) -- 2. the terms of our series are non-negative (λ i, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) -- 3. one term of our series is strictly positive -- they all are, we use the first term (one_div_pos.mpr (pow_pos (zero_lt_one.trans hm) (0 + (k + 1))!)) $ -- 4. our series converges -- it does since it is the tail of a converging series, though -- this is not the argument here. summable_one_div_pow_of_le hm (λ i, trans le_self_add (nat.self_le_factorial _)) /-- Split the sum definining a Liouville number into the first `k` term and the rest. -/ lemma liouville_number_eq_initial_terms_add_tail {m : ℝ} (hm : 1 < m) (k : ℕ) : liouville_number m = liouville_number_initial_terms m k + liouville_number_tail m k := (sum_add_tsum_nat_add _ (summable_one_div_pow_of_le hm (λ i, i.self_le_factorial))).symm /-! We now prove two useful inequalities, before collecting everything together. -/ /-- Partial inequality, works with `m ∈ ℝ` satisfying `1 < m`. -/ lemma tsum_one_div_pow_factorial_lt (n : ℕ) {m : ℝ} (m1 : 1 < m) : ∑' (i : ℕ), 1 / m ^ (i + (n + 1))! < (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) := -- two useful inequalities have m0 : 0 < m := (zero_lt_one.trans m1), have mi : |1 / m| < 1 := (le_of_eq (abs_of_pos (one_div_pos.mpr m0))).trans_lt ((div_lt_one m0).mpr m1), calc (∑' i, 1 / m ^ (i + (n + 1))!) < ∑' i, 1 / m ^ (i + (n + 1)!) : -- to show the strict inequality between these series, we prove that: tsum_lt_tsum_of_nonneg -- 1. the first series has non-negative terms (λ b, one_div_nonneg.mpr (pow_nonneg m0.le _)) -- 2. the second series dominates the first (λ b, one_div_pow_le_one_div_pow_of_le m1.le (b.add_factorial_succ_le_factorial_add_succ n)) -- 3. the term with index `i = 2` of the first series is strictly smaller than -- the corresponding term of the second series (one_div_pow_strict_anti m1 (n.add_factorial_succ_lt_factorial_add_succ rfl.le)) -- 4. the second series is summable, since its terms grow quickly (summable_one_div_pow_of_le m1 (λ j, nat.le.intro rfl)) ... = ∑' i, (1 / m) ^ i * (1 / m ^ (n + 1)!) : -- split the sum in the exponent and massage by { congr, ext i, rw [pow_add, ← div_div, div_eq_mul_one_div, one_div_pow] } -- factor the constant `(1 / m ^ (n + 1)!)` out of the series ... = (∑' i, (1 / m) ^ i) * (1 / m ^ (n + 1)!) : tsum_mul_right ... = (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) : -- the series if the geometric series mul_eq_mul_right_iff.mpr (or.inl (tsum_geometric_of_abs_lt_1 mi)) lemma aux_calc (n : ℕ) {m : ℝ} (hm : 2 ≤ m) : (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 1 / (m ^ n!) ^ n := calc (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 2 * (1 / m ^ (n + 1)!) : -- the second factors coincide (and are non-negative), -- the first factors, satisfy the inequality `sub_one_div_inv_le_two` mul_le_mul_of_nonneg_right (sub_one_div_inv_le_two hm) (by positivity) ... = 2 / m ^ (n + 1)! : mul_one_div 2 _ ... = 2 / m ^ (n! * (n + 1)) : congr_arg ((/) 2) (congr_arg (pow m) (mul_comm _ _)) ... ≤ 1 / m ^ (n! * n) : begin -- [ NB: in this block, I do not follow the brace convention for subgoals -- I wait until -- I solve all extraneous goals at once with `exact pow_pos (zero_lt_two.trans_le hm) _`. ] -- Clear denominators and massage* apply (div_le_div_iff _ _).mpr, conv_rhs { rw [one_mul, mul_add, pow_add, mul_one, pow_mul, mul_comm, ← pow_mul] }, -- the second factors coincide, so we prove the inequality of the first factors* refine (mul_le_mul_right _).mpr _, -- solve all the inequalities `0 < m ^ ??` any_goals { exact pow_pos (zero_lt_two.trans_le hm) _ }, -- `2 ≤ m ^ n!` is a consequence of monotonicity of exponentiation at `2 ≤ m`. exact trans (trans hm (pow_one _).symm.le) (pow_mono (one_le_two.trans hm) n.factorial_pos) end ... = 1 / (m ^ n!) ^ n : congr_arg ((/) 1) (pow_mul m n! n) /-! Starting from here, we specialize to the case in which `m` is a natural number. -/ /-- The sum of the `k` initial terms of the Liouville number to base `m` is a ratio of natural numbers where the denominator is `m ^ k!`. -/ lemma liouville_number_rat_initial_terms {m : ℕ} (hm : 0 < m) (k : ℕ) : ∃ p : ℕ, liouville_number_initial_terms m k = p / m ^ k! := begin induction k with k h, { exact ⟨1, by rw [liouville_number_initial_terms, range_one, sum_singleton, nat.cast_one]⟩ }, { rcases h with ⟨p_k, h_k⟩, use p_k * (m ^ ((k + 1)! - k!)) + 1, unfold liouville_number_initial_terms at h_k ⊢, rw [sum_range_succ, h_k, div_add_div, div_eq_div_iff, add_mul], { norm_cast, rw [add_mul, one_mul, nat.factorial_succ, show k.succ * k! - k! = (k.succ - 1) * k!, by rw [tsub_mul, one_mul], nat.succ_sub_one, add_mul, one_mul, pow_add], simp [mul_assoc] }, refine mul_ne_zero_iff.mpr ⟨_, _⟩, all_goals { exact pow_ne_zero _ (nat.cast_ne_zero.mpr hm.ne.symm) } } end theorem is_liouville {m : ℕ} (hm : 2 ≤ m) : liouville (liouville_number m) := begin -- two useful inequalities have mZ1 : 1 < (m : ℤ), { norm_cast, exact one_lt_two.trans_le hm }, have m1 : 1 < (m : ℝ), { norm_cast, exact one_lt_two.trans_le hm }, intro n, -- the first `n` terms sum to `p / m ^ k!` rcases liouville_number_rat_initial_terms (zero_lt_two.trans_le hm) n with ⟨p, hp⟩, refine ⟨p, m ^ n!, one_lt_pow mZ1 n.factorial_ne_zero, _⟩, push_cast, -- separate out the sum of the first `n` terms and the rest rw [liouville_number_eq_initial_terms_add_tail m1 n, ← hp, add_sub_cancel', abs_of_nonneg (liouville_number_tail_pos m1 _).le], exact ⟨((lt_add_iff_pos_right _).mpr (liouville_number_tail_pos m1 n)).ne.symm, (tsum_one_div_pow_factorial_lt n m1).trans_le (aux_calc _ (nat.cast_two.symm.le.trans (nat.cast_le.mpr hm)))⟩ end /- Placing this lemma outside of the `open/closed liouville`-namespace would allow to remove `_root_.`, at the cost of some other small weirdness. -/ lemma is_transcendental {m : ℕ} (hm : 2 ≤ m) : _root_.transcendental ℤ (liouville_number m) := transcendental (is_liouville hm) end liouville
a4ff7594d40b58f45abf4181fb3a9f176b140144
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/order/complete_lattice.lean
91ebe091ffa3ccaa76ade576ef40d01e435e7573
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
27,743
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 Theory of complete lattices. -/ import order.bounded_lattice data.set.basic tactic.pi_instances set_option old_structure_cmd true universes u v w w₂ variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂} namespace lattice /-- class for the `Sup` operator -/ class has_Sup (α : Type u) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type u) := (Inf : set α → α) /-- Supremum of a set -/ def Sup [has_Sup α] : set α → α := has_Sup.Sup /-- Infimum of a set -/ def Inf [has_Inf α] : set α → α := has_Inf.Inf /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α := (le_Sup : ∀s, ∀a∈s, a ≤ Sup s) (Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a) (Inf_le : ∀s, ∀a∈s, Inf s ≤ a) (le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type u) extends complete_lattice α, linear_order α /-- Indexed supremum -/ def supr [complete_lattice α] (s : ι → α) : α := Sup {a : α | ∃i : ι, a = s i} /-- Indexed infimum -/ def infi [complete_lattice α] (s : ι → α) : α := Inf {a : α | ∃i : ι, a = s i} notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r section open set variables [complete_lattice α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha) theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha) @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) := ⟨assume : Sup s ≤ a, assume b, assume : b ∈ s, le_trans (le_Sup ‹b ∈ s›) ‹Sup s ≤ a›, Sup_le⟩ @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) := ⟨assume : a ≤ Inf s, assume b, assume : b ∈ s, le_trans ‹a ≤ Inf s› (Inf_le ‹b ∈ s›), le_Inf⟩ -- how to state this? instead a parameter `a`, use `∃a, a ∈ s` or `s ≠ ∅`? theorem Inf_le_Sup (h : a ∈ s) : Inf s ≤ Sup s := by have := le_Sup h; finish --Inf_le_of_le h (le_Sup h) -- TODO: it is weird that we have to add union_def theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := le_antisymm (by finish) (sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _)) /- old proof: le_antisymm (Sup_le $ assume a h, or.rec_on h (le_sup_left_of_le ∘ le_Sup) (le_sup_right_of_le ∘ le_Sup)) (sup_le (Sup_le_Sup $ subset_union_left _ _) (Sup_le_Sup $ subset_union_right _ _)) -/ theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := by finish /- Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := le_antisymm (le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _)) (by finish) /- old proof: le_antisymm (le_inf (Inf_le_Inf $ subset_union_left _ _) (Inf_le_Inf $ subset_union_right _ _)) (le_Inf $ assume a h, or.rec_on h (inf_le_left_of_le ∘ Inf_le) (inf_le_right_of_le ∘ Inf_le)) -/ theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := by finish /- le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t)) -/ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := le_antisymm (by finish) (by finish) -- le_antisymm (Sup_le (assume _, false.elim)) bot_le @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := le_antisymm (by finish) (by finish) --le_antisymm le_top (le_Inf (assume _, false.elim)) @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := le_antisymm (by finish) (le_Sup ⟨⟩) -- finish fails because ⊤ ≤ a simplifies to a = ⊤ --le_antisymm le_top (le_Sup ⟨⟩) @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := le_antisymm (Inf_le ⟨⟩) bot_le -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := have Sup {b | b = a} = a, from le_antisymm (Sup_le $ assume b b_eq, b_eq ▸ le_refl _) (le_Sup rfl), calc Sup (insert a s) = Sup {b | b = a} ⊔ Sup s : Sup_union ... = a ⊔ Sup s : by rw [this] @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := have Inf {b | b = a} = a, from le_antisymm (Inf_le rfl) (le_Inf $ assume b b_eq, b_eq ▸ le_refl _), calc Inf (insert a s) = Inf {b | b = a} ⊓ Inf s : Inf_union ... = a ⊓ Inf s : by rw [this] @[simp] theorem Sup_singleton {a : α} : Sup {a} = a := by finish [singleton_def] --eq.trans Sup_insert $ by simp @[simp] theorem Inf_singleton {a : α} : Inf {a} = a := by finish [singleton_def] --eq.trans Inf_insert $ by simp end section complete_linear_order variables [complete_linear_order α] {s t : set α} {a b : α} lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) := iff.intro (assume : Inf s < b, classical.by_contradiction $ assume : ¬ (∃a∈s, a < b), have b ≤ Inf s, from le_Inf $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩, lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›)) (assume ⟨a, ha, h⟩, lt_of_le_of_lt (Inf_le ha) h) lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) := iff.intro (assume : b < Sup s, classical.by_contradiction $ assume : ¬ (∃a∈s, b < a), have Sup s ≤ b, from Sup_le $ assume a ha, le_of_not_gt $ assume h, this ⟨a, ha, h⟩, lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›)) (assume ⟨a, ha, h⟩, lt_of_lt_of_le h $ le_Sup ha) lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) := iff.intro (assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (assume h, top_unique $ le_of_not_gt $ assume h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) := iff.trans lt_Sup_iff $ iff.intro (assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩) (assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩) lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) := iff.trans Inf_lt_iff $ iff.intro (assume ⟨a', ⟨i, rfl⟩, ha⟩, ⟨i, ha⟩) (assume ⟨i, hi⟩, ⟨f i, ⟨i, rfl⟩, hi⟩) end complete_linear_order /- supr & infi -/ section open set variables [complete_lattice α] {s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s := le_Sup ⟨i, rfl⟩ @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) := le_Sup ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) := le_Sup ⟨i, rfl⟩ -/ theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s := le_trans h (le_supr _ i) theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a := Sup_le $ assume b ⟨i, eq⟩, eq.symm ▸ h i theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t := supr_le $ assume i, le_supr_of_le i (h i) theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t := supr_le $ assume j, exists.elim (h j) le_supr_of_le theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) := supr_le $ le_supr _ ∘ h @[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) := ⟨assume : supr s ≤ a, assume i, le_trans (le_supr _ _) this, supr_le⟩ -- TODO: finish doesn't do well here. @[congr] theorem supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := le_antisymm (supr_le_supr2 $ assume j, ⟨pq.mp j, le_of_eq $ f _⟩) (supr_le_supr2 $ assume j, ⟨pq.mpr j, le_of_eq $ (f j).symm⟩) theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i := Inf_le ⟨i, rfl⟩ @[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) := Inf_le ⟨i, rfl⟩ /- I wanted to see if this would help for infi_comm; it doesn't. @[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂): (: ⨅ i j, s i j :) ≤ (: s i j :) := begin transitivity, apply (infi_le (λ i, ⨅ j, s i j) i), apply infi_le end -/ theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a := le_trans (infi_le _ i) h theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s := le_Inf $ assume b ⟨i, eq⟩, eq.symm ▸ h i theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t := le_infi $ assume i, infi_le_of_le i (h i) theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t := le_infi $ assume j, exists.elim (h j) infi_le_of_le theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) := le_infi $ infi_le _ ∘ h @[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) := ⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩ @[congr] theorem infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := le_antisymm (infi_le_infi2 $ assume j, ⟨pq.mpr j, le_of_eq $ f j⟩) (infi_le_infi2 $ assume j, ⟨pq.mp j, le_of_eq $ (f _).symm⟩) @[simp] theorem infi_const {a : α} [inhabited ι] : (⨅ b:ι, a) = a := le_antisymm (Inf_le ⟨arbitrary ι, rfl⟩) (by finish) @[simp] theorem supr_const {a : α} [inhabited ι] : (⨆ b:ι, a) = a := le_antisymm (by finish) (le_Sup ⟨arbitrary ι, rfl⟩) @[simp] lemma infi_top [complete_lattice α] : (⨅i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ assume i, le_refl _ @[simp] lemma supr_bot [complete_lattice α] : (⨆i:ι, ⊥ : α) = ⊥ := bot_unique $ supr_le $ assume i, le_refl _ @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _) @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ assume h, (hp h).elim @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ assume h, (hp h).elim) bot_le -- TODO: should this be @[simp]? theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i) (le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j) /- TODO: this is strange. In the proof below, we get exactly the desired among the equalities, but close does not get it. begin apply @le_antisymm, simp, intros, begin [smt] ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i), trace_state, close end end -/ -- TODO: should this be @[simp]? theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) := le_antisymm (supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i) (supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j) @[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl := le_antisymm (infi_le_of_le b $ infi_le _ rfl) (le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end) @[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) @[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl := le_antisymm (supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end) (le_supr_of_le b $ le_supr _ rfl) attribute [ematch] le_refl theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (le_infi $ assume i, infi_le_of_le i inf_le_left) (le_infi $ assume i, infi_le_of_le i inf_le_right)) (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) (inf_le_right_of_le $ infi_le _ _)) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) := le_antisymm (le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right)) lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf i]; simp [inf_comm] lemma binfi_inf {ι : Sort*} {p : ι → Prop} {f : Πi, p i → α} {a : α} {i : ι} (hi : p i) : (⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right) (le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left) (infi_le_of_le i $ infi_le_of_le hi $ inf_le_right)) theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := le_antisymm (supr_le $ assume i, sup_le (le_sup_left_of_le $ le_supr _ _) (le_sup_right_of_le $ le_supr _ _)) (sup_le (supr_le $ assume i, le_supr_of_le i le_sup_left) (supr_le $ assume i, le_supr_of_le i le_sup_right)) /- supr and infi under Prop -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, false.elim i) bot_le @[simp] theorem infi_true {s : true → α} : infi s = s trivial := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_true {s : true → α} : supr s = s trivial := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) @[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) @[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume i, match i with | or.inl i := inf_le_left_of_le $ infi_le _ _ | or.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := le_antisymm (supr_le $ assume s, match s with | or.inl i := le_sup_left_of_le $ le_supr _ i | or.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩)) theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) := le_antisymm (le_infi $ assume b, le_infi $ assume h, Inf_le h) (le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h) theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) := le_antisymm (Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h) (supr_le $ assume b, supr_le $ assume h, le_Sup h) lemma Sup_range {f : ι → α} : Sup (range f) = supr f := le_antisymm (Sup_le $ forall_range_iff.mpr $ assume i, le_supr _ _) (supr_le $ assume i, le_Sup (mem_range_self _)) lemma Inf_range {f : ι → α} : Inf (range f) = infi f := le_antisymm (le_infi $ assume i, Inf_le (mem_range_self _)) (le_Inf $ forall_range_iff.mpr $ assume i, infi_le _ _) lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) := le_antisymm (supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i) (supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _)) lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) := le_antisymm (le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _)) (le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i) theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) := calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi ... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm] ... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm] ... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) := calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr ... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm] ... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm] ... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm] ... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left] /- supr and infi under set constructions -/ /- should work using the simplifier! -/ @[simp] theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := le_antisymm le_top (le_infi $ assume x, le_infi false.elim) @[simp] theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := le_antisymm (supr_le $ assume x, supr_le false.elim) bot_le @[simp] theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := show (⨅ (x : β) (H : true), f x) = ⨅ (x : β), f x, from congr_arg infi $ funext $ assume x, infi_const @[simp] theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := show (⨆ (x : β) (H : true), f x) = ⨆ (x : β), f x, from congr_arg supr $ funext $ assume x, supr_const @[simp] theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or ... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq @[simp] theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or ... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq @[simp] theorem insert_of_has_insert (x : α) (a : set α) : has_insert.insert x a = insert x a := rfl @[simp] theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) := eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left @[simp] theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) := eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left @[simp] theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := show (⨅ x ∈ insert b (∅ : set β), f x) = f b, by simp @[simp] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := show (⨆ x ∈ insert b (∅ : set β), f x) = f b, by simp /- supr and infi under Type -/ @[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i) @[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ := le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le @[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () := le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _) @[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () := le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _) lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := le_antisymm (supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end) (sup_le (le_supr _ _) (le_supr _ _)) lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := le_antisymm (le_inf (infi_le _ _) (infi_le _ _)) (le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end) theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) := le_antisymm (le_infi $ assume i, le_infi $ assume : p i, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _) (supr_le $ assume i, supr_le $ assume : p i, le_supr _ _) theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := le_antisymm (le_infi $ assume i, le_infi $ assume j, infi_le _ _) (le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _) theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := le_antisymm (supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _) (supr_le $ assume i, supr_le $ assume j, le_supr _ _) theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := le_antisymm (le_inf (infi_le_infi2 $ assume i, ⟨_, le_refl _⟩) (infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)) (le_infi $ assume s, match s with | sum.inl i := inf_le_left_of_le $ infi_le _ _ | sum.inr j := inf_le_right_of_le $ infi_le _ _ end) theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := le_antisymm (supr_le $ assume s, match s with | sum.inl i := le_sup_left_of_le $ le_supr _ i | sum.inr j := le_sup_right_of_le $ le_supr _ j end) (sup_le (supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩) (supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩)) end /- Instances -/ instance complete_lattice_Prop : complete_lattice Prop := { Sup := λs, ∃a∈s, a, le_Sup := assume s a h p, ⟨a, h, p⟩, Sup_le := assume s a h ⟨b, h', p⟩, h b h' p, Inf := λs, ∀a:Prop, a∈s → a, Inf_le := assume s a h p, p a h, le_Inf := assume s a h p b hb, h b hb p, ..lattice.bounded_lattice_Prop } instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := by { pi_instance; { intros, intro, apply_field, intros, simp at H, rcases H with ⟨ x, H₀, H₁ ⟩, subst b, apply a_1 _ H₀ i, } } section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) := assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) := assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h end complete_lattice end lattice section ord_continuous open lattice variables [complete_lattice α] [complete_lattice β] /-- A function `f` between complete lattices is order-continuous if it preserves all suprema. -/ def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i) lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ := have h : f (Sup {a₁, a₂}) = (⨆i∈({a₁, a₂} : set α), f i), from hf _, have h₁ : {a₁, a₂} = (insert a₂ {a₁} : set α), from rfl, begin rw [h₁, Sup_insert, Sup_singleton, sup_comm] at h, rw [h, supr_insert, supr_singleton, sup_comm] end lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f := assume a₁ a₂ h, calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left ... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm ... = _ : by rw [sup_of_le_right h] end ord_continuous /- Classical statements: @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) := _ @[simp] theorem infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) := _ @[simp] theorem Sup_eq_bot : Sup s = ⊤ ↔ (∀a∈s, a = ⊥) := _ @[simp] theorem supr_eq_top : supr s = ⊤ ↔ (∀i, s i = ⊥) := _ -/
0a6c7442253b790a4d55be49fddc1adeac2aa109
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Lean/PrettyPrinter/Parenthesizer.lean
3ce78c03637e7e3a32d917983c08c3effd8ff4a6
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,801
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The parenthesizer inserts parentheses into a `Syntax` object where syntactically necessary, usually as an intermediary step between the delaborator and the formatter. While the delaborator outputs structurally well-formed syntax trees that can be re-elaborated without post-processing, this tree structure is lost in the formatter and thus needs to be preserved by proper insertion of parentheses. # The abstract problem & solution The Lean 4 grammar is unstructured and extensible with arbitrary new parsers, so in general it is undecidable whether parentheses are necessary or even allowed at any point in the syntax tree. Parentheses for different categories, e.g. terms and levels, might not even have the same structure. In this module, we focus on the correct parenthesization of parsers defined via `Lean.Parser.prattParser`, which includes both aforementioned built-in categories. Custom parenthesizers can be added for new node kinds, but the data collected in the implementation below might not be appropriate for other parenthesization strategies. Usages of a parser defined via `prattParser` in general have the form `p prec`, where `prec` is the minimum precedence or binding power. Recall that a Pratt parser greedily runs a leading parser with precedence at least `prec` (otherwise it fails) followed by zero or more trailing parsers with precedence at least `prec`; the precedence of a parser is encoded in the call to `leadingNode/trailingNode`, respectively. Thus we should parenthesize a syntax node `stx` supposedly produced by `p prec` if 1. the leading/any trailing parser involved in `stx` has precedence < `prec` (because without parentheses, `p prec` would not produce all of `stx`), or 2. the trailing parser parsing the input to *the right of* `stx`, if any, has precedence >= `prec` (because without parentheses, `p prec` would have parsed it as well and made it a part of `stx`). We also check that the two parsers are from the same syntax category. Note that in case 2, it is also sufficient to parenthesize a *parent* node as long as the offending parser is still to the right of that node. For example, imagine the tree structure of `(f $ fun x => x) y` without parentheses. We need to insert *some* parentheses between `x` and `y` since the lambda body is parsed with precedence 0, while the identifier parser for `y` has precedence `maxPrec`. But we need to parenthesize the `$` node anyway since the precedence of its RHS (0) again is smaller than that of `y`. So it's better to only parenthesize the outer node than ending up with `(f $ (fun x => x)) y`. # Implementation We transform the syntax tree and collect the necessary precedence information for that in a single traversal. The traversal is right-to-left to cover case 2. More specifically, for every Pratt parser call, we store as monadic state the precedence of the left-most trailing parser and the minimum precedence of any parser (`contPrec`/`minPrec`) in this call, if any, and the precedence of the nested trailing Pratt parser call (`trailPrec`), if any. If `stP` is the state resulting from the traversal of a Pratt parser call `p prec`, and `st` is the state of the surrounding call, we parenthesize if `prec > stP.minPrec` (case 1) or if `stP.trailPrec <= st.contPrec` (case 2). The traversal can be customized for each `[*Parser]` parser declaration `c` (more specifically, each `SyntaxNodeKind` `c`) using the `[parenthesizer c]` attribute. Otherwise, a default parenthesizer will be synthesized from the used parser combinators by recursively replacing them with declarations tagged as `[combinatorParenthesizer]` for the respective combinator. If a called function does not have a registered combinator parenthesizer and is not reducible, the synthesizer fails. This happens mostly at the `Parser.mk` decl, which is irreducible, when some parser primitive has not been handled yet. The traversal over the `Syntax` object is complicated by the fact that a parser does not produce exactly one syntax node, but an arbitrary (but constant, for each parser) amount that it pushes on top of the parser stack. This amount can even be zero for parsers such as `checkWsBefore`. Thus we cannot simply pass and return a `Syntax` object to and from `visit`. Instead, we use a `Syntax.Traverser` that allows arbitrary movement and modification inside the syntax tree. Our traversal invariant is that a parser interpreter should stop at the syntax object to the *left* of all syntax objects its parser produced, except when it is already at the left-most child. This special case is not an issue in practice since if there is another parser to the left that produced zero nodes in this case, it should always do so, so there is no danger of the left-most child being processed multiple times. Ultimately, most parenthesizers are implemented via three primitives that do all the actual syntax traversal: `maybeParenthesize mkParen prec x` runs `x` and afterwards transforms it with `mkParen` if the above condition for `p prec` is fulfilled. `visitToken` advances to the preceding sibling and is used on atoms. `visitArgs x` executes `x` on the last child of the current node and then advances to the preceding sibling (of the original current node). -/ import Lean.CoreM import Lean.KeyedDeclsAttribute import Lean.Parser.Extension import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic namespace Lean namespace PrettyPrinter namespace Parenthesizer structure Context where -- We need to store this `categoryParser` argument to deal with the implicit Pratt parser call in `trailingNode.parenthesizer`. cat : Name := Name.anonymous structure State where stxTrav : Syntax.Traverser --- precedence and category of the current left-most trailing parser, if any; see module doc for details contPrec : Option Nat := none contCat : Name := Name.anonymous -- current minimum precedence in this Pratt parser call, if any; see module doc for details minPrec : Option Nat := none -- precedence and category of the trailing Pratt parser call if any; see module doc for details trailPrec : Option Nat := none trailCat : Name := Name.anonymous -- true iff we have already visited a token on this parser level; used for detecting trailing parsers visitedToken : Bool := false end Parenthesizer abbrev ParenthesizerM := ReaderT Parenthesizer.Context $ StateRefT Parenthesizer.State CoreM abbrev Parenthesizer := ParenthesizerM Unit @[inline] def ParenthesizerM.orelse {α} (p₁ p₂ : ParenthesizerM α) : ParenthesizerM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂) instance {α} : OrElse (ParenthesizerM α) := ⟨ParenthesizerM.orelse⟩ unsafe def mkParenthesizerAttribute : IO (KeyedDeclsAttribute Parenthesizer) := KeyedDeclsAttribute.init { builtinName := `builtinParenthesizer, name := `parenthesizer, descr := "Register a parenthesizer for a parser. [parenthesizer k] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Parenthesizer, evalKey := fun builtin stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a parenthesizer for it immediately, so we just check for a declaration in this case if (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id then pure id else throwError "invalid [parenthesizer] argument, unknown syntax kind '{id}'" } `Lean.PrettyPrinter.parenthesizerAttribute @[builtinInit mkParenthesizerAttribute] constant parenthesizerAttribute : KeyedDeclsAttribute Parenthesizer abbrev CategoryParenthesizer := forall (prec : Nat), Parenthesizer unsafe def mkCategoryParenthesizerAttribute : IO (KeyedDeclsAttribute CategoryParenthesizer) := KeyedDeclsAttribute.init { builtinName := `builtinCategoryParenthesizer, name := `categoryParenthesizer, descr := "Register a parenthesizer for a syntax category. [parenthesizer cat] registers a declaration of type `Lean.PrettyPrinter.CategoryParenthesizer` for the category `cat`, which is used when parenthesizing calls of `categoryParser cat prec`. Implementations should call `maybeParenthesize` with the precedence and `cat`. If no category parenthesizer is registered, the category will never be parenthesized, but still be traversed for parenthesizing nested categories.", valueTypeName := `Lean.PrettyPrinter.CategoryParenthesizer, evalKey := fun _ stx => do let env ← getEnv let id ← Attribute.Builtin.getId stx if Parser.isParserCategory env id then pure id else throwError "invalid [parenthesizer] argument, unknown parser category '{toString id}'" } `Lean.PrettyPrinter.categoryParenthesizerAttribute @[builtinInit mkCategoryParenthesizerAttribute] constant categoryParenthesizerAttribute : KeyedDeclsAttribute CategoryParenthesizer unsafe def mkCombinatorParenthesizerAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinatorParenthesizer "Register a parenthesizer for a parser combinator. [combinatorParenthesizer c] registers a declaration of type `Lean.PrettyPrinter.Parenthesizer` for the `Parser` declaration `c`. Note that, unlike with [parenthesizer], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Parenthesizer` in the parameter types." @[builtinInit mkCombinatorParenthesizerAttribute] constant combinatorParenthesizerAttribute : ParserCompiler.CombinatorAttribute namespace Parenthesizer open Lean.Core open Std.Format def throwBacktrack {α} : ParenthesizerM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser ParenthesizerM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def addPrecCheck (prec : Nat) : ParenthesizerM Unit := modify fun st => { st with contPrec := Nat.min (st.contPrec.getD prec) prec, minPrec := Nat.min (st.minPrec.getD prec) prec } /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : ParenthesizerM Unit) : ParenthesizerM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft -- Macro scopes in the parenthesizer output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : MonadQuotation ParenthesizerM := { getCurrMacroScope := pure arbitrary, getMainModule := pure arbitrary, withFreshMacroScope := fun x => x, } /-- Run `x` and parenthesize the result using `mkParen` if necessary. If `canJuxtapose` is false, we assume the category does not have a token-less juxtaposition syntax a la function application and deactivate rule 2. -/ def maybeParenthesize (cat : Name) (canJuxtapose : Bool) (mkParen : Syntax → Syntax) (prec : Nat) (x : ParenthesizerM Unit) : ParenthesizerM Unit := do let stx ← getCur let idx ← getIdx let st ← get -- reset precs for the recursive call set { stxTrav := st.stxTrav : State } trace[PrettyPrinter.parenthesize] "parenthesizing (cont := {(st.contPrec, st.contCat)}){indentD (fmt stx)}" x let { minPrec := some minPrec, trailPrec := trailPrec, trailCat := trailCat, .. } ← get | trace[PrettyPrinter.parenthesize] "visited a syntax tree without precedences?!{line ++ fmt stx}" trace[PrettyPrinter.parenthesize] ("...precedences are {prec} >? {minPrec}" ++ if canJuxtapose then m!", {(trailPrec, trailCat)} <=? {(st.contPrec, st.contCat)}" else "") -- Should we parenthesize? if (prec > minPrec || canJuxtapose && match trailPrec, st.contPrec with | some trailPrec, some contPrec => trailCat == st.contCat && trailPrec <= contPrec | _, _ => false) then -- The recursive `visit` call, by the invariant, has moved to the preceding node. In order to parenthesize -- the original node, we must first move to the right, except if we already were at the left-most child in the first -- place. if idx > 0 then goRight let mut stx ← getCur -- Move leading/trailing whitespace of `stx` outside of parentheses if let SourceInfo.original _ pos trail := stx.getHeadInfo then stx := stx.setHeadInfo (SourceInfo.original "".toSubstring pos trail) if let SourceInfo.original lead pos _ := stx.getTailInfo then stx := stx.setTailInfo (SourceInfo.original lead pos "".toSubstring) let mut stx' := mkParen stx if let SourceInfo.original lead pos _ := stx.getHeadInfo then stx' := stx'.setHeadInfo (SourceInfo.original lead pos "".toSubstring) if let SourceInfo.original _ pos trail := stx.getTailInfo then stx' := stx'.setTailInfo (SourceInfo.original "".toSubstring pos trail) trace[PrettyPrinter.parenthesize] "parenthesized: {stx'.formatStx none}" setCur stx' goLeft -- after parenthesization, there is no more trailing parser modify (fun st => { st with contPrec := Parser.maxPrec, contCat := cat, trailPrec := none }) let { trailPrec := trailPrec, .. } ← get -- If we already had a token at this level, keep the trailing parser. Otherwise, use the minimum of -- `prec` and `trailPrec`. if st.visitedToken then modify fun stP => { stP with trailPrec := st.trailPrec, trailCat := st.trailCat } else let trailPrec := match trailPrec with | some trailPrec => Nat.min trailPrec prec | _ => prec modify fun stP => { stP with trailPrec := trailPrec, trailCat := cat } modify fun stP => { stP with minPrec := st.minPrec } /-- Adjust state and advance. -/ def visitToken : Parenthesizer := do modify fun st => { st with contPrec := none, contCat := Name.anonymous, visitedToken := true } goLeft @[combinatorParenthesizer Lean.Parser.orelse] def orelse.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer := do let st ← get -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its parenthesizer synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern 8 "lean_mk_antiquot_parenthesizer"] constant mkAntiquot.parenthesizer' (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parenthesizer @[inline] def liftCoreM {α} (x : CoreM α) : ParenthesizerM α := liftM x -- break up big mutual recursion @[extern "lean_pretty_printer_parenthesizer_interpret_parser_descr"] constant interpretParserDescr' : ParserDescr → CoreM Parenthesizer unsafe def parenthesizerForKindUnsafe (k : SyntaxNodeKind) : Parenthesizer := do if k == `missing then pure () else let p ← runForNodeKind parenthesizerAttribute k interpretParserDescr' p @[implementedBy parenthesizerForKindUnsafe] constant parenthesizerForKind (k : SyntaxNodeKind) : Parenthesizer @[combinatorParenthesizer Lean.Parser.withAntiquot] def withAntiquot.parenthesizer (antiP p : Parenthesizer) : Parenthesizer := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.parenthesizer antiP p @[combinatorParenthesizer Lean.Parser.withAntiquotSuffixSplice] def withAntiquotSuffixSplice.parenthesizer (k : SyntaxNodeKind) (p suffix : Parenthesizer) : Parenthesizer := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinatorParenthesizer Lean.Parser.tokenWithAntiquot] def tokenWithAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do if (← getCur).isTokenAntiquot then visitArgs p else p def parenthesizeCategoryCore (cat : Name) (prec : Nat) : Parenthesizer := withReader (fun ctx => { ctx with cat := cat }) do let stx ← getCur if stx.getKind == `choice then visitArgs $ stx.getArgs.size.forM fun _ => do let stx ← getCur parenthesizerForKind stx.getKind else withAntiquot.parenthesizer (mkAntiquot.parenthesizer' cat.toString none) (parenthesizerForKind stx.getKind) modify fun st => { st with contCat := cat } @[combinatorParenthesizer Lean.Parser.categoryParser] def categoryParser.parenthesizer (cat : Name) (prec : Nat) : Parenthesizer := do let env ← getEnv match categoryParenthesizerAttribute.getValues env cat with | p::_ => p prec -- Fall back to the generic parenthesizer. -- In this case this node will never be parenthesized since we don't know which parentheses to use. | _ => parenthesizeCategoryCore cat prec @[combinatorParenthesizer Lean.Parser.categoryParserOfStack] def categoryParserOfStack.parenthesizer (offset : Nat) (prec : Nat) : Parenthesizer := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) categoryParser.parenthesizer stx.getId prec @[combinatorParenthesizer Lean.Parser.parserOfStack] def parserOfStack.parenthesizer (offset : Nat) (prec : Nat := 0) : Parenthesizer := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) parenthesizerForKind stx.getKind @[builtinCategoryParenthesizer term] def term.parenthesizer : CategoryParenthesizer | prec => do let stx ← getCur -- this can happen at `termParser <|> many1 commandParser` in `Term.stxQuot` if stx.getKind == nullKind then throwBacktrack else do maybeParenthesize `term true (fun stx => Unhygienic.run `(($stx))) prec $ parenthesizeCategoryCore `term prec @[builtinCategoryParenthesizer tactic] def tactic.parenthesizer : CategoryParenthesizer | prec => do maybeParenthesize `tactic false (fun stx => Unhygienic.run `(tactic|($stx))) prec $ parenthesizeCategoryCore `tactic prec @[builtinCategoryParenthesizer level] def level.parenthesizer : CategoryParenthesizer | prec => do maybeParenthesize `level false (fun stx => Unhygienic.run `(level|($stx))) prec $ parenthesizeCategoryCore `level prec @[combinatorParenthesizer Lean.Parser.error] def error.parenthesizer (msg : String) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.errorAtSavedPos] def errorAtSavedPos.parenthesizer (msg : String) (delta : Bool) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.atomic] def atomic.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.lookahead] def lookahead.parenthesizer (p : Parenthesizer) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.notFollowedBy] def notFollowedBy.parenthesizer (p : Parenthesizer) : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.andthen] def andthen.parenthesizer (p1 p2 : Parenthesizer) : Parenthesizer := p2 *> p1 @[combinatorParenthesizer Lean.Parser.node] def node.parenthesizer (k : SyntaxNodeKind) (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.parenthesize.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" -- HACK; see `orelse.parenthesizer` throwBacktrack visitArgs p @[combinatorParenthesizer Lean.Parser.checkPrec] def checkPrec.parenthesizer (prec : Nat) : Parenthesizer := addPrecCheck prec @[combinatorParenthesizer Lean.Parser.leadingNode] def leadingNode.parenthesizer (k : SyntaxNodeKind) (prec : Nat) (p : Parenthesizer) : Parenthesizer := do node.parenthesizer k p addPrecCheck prec -- Limit `cont` precedence to `maxPrec-1`. -- This is because `maxPrec-1` is the precedence of function application, which is the only way to turn a leading parser -- into a trailing one. modify fun st => { st with contPrec := Nat.min (Parser.maxPrec-1) prec } @[combinatorParenthesizer Lean.Parser.trailingNode] def trailingNode.parenthesizer (k : SyntaxNodeKind) (prec _ : Nat) (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.parenthesize.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" -- HACK; see `orelse.parenthesizer` throwBacktrack visitArgs do p addPrecCheck prec let ctx ← read modify fun st => { st with contCat := ctx.cat } -- After visiting the nodes actually produced by the parser passed to `trailingNode`, we are positioned on the -- left-most child, which is the term injected by `trailingNode` in place of the recursion. Left recursion is not an -- issue for the parenthesizer, so we can think of this child being produced by `termParser 0`, or whichever Pratt -- parser is calling us. categoryParser.parenthesizer ctx.cat 0 @[combinatorParenthesizer Lean.Parser.symbolNoAntiquot] def symbolNoAntiquot.parenthesizer (sym : String) := visitToken @[combinatorParenthesizer Lean.Parser.unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.parenthesizer (sym asciiSym : String) := visitToken @[combinatorParenthesizer Lean.Parser.identNoAntiquot] def identNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.rawIdentNoAntiquot] def rawIdentNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.identEq] def identEq.parenthesizer (id : Name) := visitToken @[combinatorParenthesizer Lean.Parser.nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.parenthesizer (sym : String) (includeIdent : Bool) := visitToken @[combinatorParenthesizer Lean.Parser.charLitNoAntiquot] def charLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.strLitNoAntiquot] def strLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.nameLitNoAntiquot] def nameLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.numLitNoAntiquot] def numLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.scientificLitNoAntiquot] def scientificLitNoAntiquot.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.fieldIdx] def fieldIdx.parenthesizer := visitToken @[combinatorParenthesizer Lean.Parser.manyNoAntiquot] def manyNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinatorParenthesizer Lean.Parser.many1NoAntiquot] def many1NoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do manyNoAntiquot.parenthesizer p @[combinatorParenthesizer Lean.Parser.many1Unbox] def many1Unbox.parenthesizer (p : Parenthesizer) : Parenthesizer := do let stx ← getCur if stx.getKind == nullKind then manyNoAntiquot.parenthesizer p else p @[combinatorParenthesizer Lean.Parser.optionalNoAntiquot] def optionalNoAntiquot.parenthesizer (p : Parenthesizer) : Parenthesizer := do visitArgs p @[combinatorParenthesizer Lean.Parser.sepByNoAntiquot] def sepByNoAntiquot.parenthesizer (p pSep : Parenthesizer) : Parenthesizer := do let stx ← getCur visitArgs $ (List.range stx.getArgs.size).reverse.forM $ fun i => if i % 2 == 0 then p else pSep @[combinatorParenthesizer Lean.Parser.sepBy1NoAntiquot] def sepBy1NoAntiquot.parenthesizer := sepByNoAntiquot.parenthesizer @[combinatorParenthesizer Lean.Parser.withPosition] def withPosition.parenthesizer (p : Parenthesizer) : Parenthesizer := do -- We assume the formatter will indent syntax sufficiently such that parenthesizing a `withPosition` node is never necessary modify fun st => { st with contPrec := none } p @[combinatorParenthesizer Lean.Parser.withoutPosition] def withoutPosition.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withForbidden] def withForbidden.parenthesizer (tk : Parser.Token) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withoutForbidden] def withoutForbidden.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.withoutInfo] def withoutInfo.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.setExpected] def setExpected.parenthesizer (expected : List String) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.incQuotDepth] def incQuotDepth.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.decQuotDepth] def decQuotDepth.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.suppressInsideQuot] def suppressInsideQuot.parenthesizer (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.evalInsideQuot] def evalInsideQuot.parenthesizer (declName : Name) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer Lean.Parser.checkStackTop] def checkStackTop.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkWsBefore] def checkWsBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkNoWsBefore] def checkNoWsBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkLinebreakBefore] def checkLinebreakBefore.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkTailWs] def checkTailWs.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkColGe] def checkColGe.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkColGt] def checkColGt.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkLineEq] def checkLineEq.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.eoi] def eoi.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.notFollowedByCategoryToken] def notFollowedByCategoryToken.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkNoImmediateColon] def checkNoImmediateColon.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkInsideQuot] def checkInsideQuot.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.checkOutsideQuot] def checkOutsideQuot.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.skip] def skip.parenthesizer : Parenthesizer := pure () @[combinatorParenthesizer Lean.Parser.pushNone] def pushNone.parenthesizer : Parenthesizer := goLeft @[combinatorParenthesizer Lean.Parser.interpolatedStr] def interpolatedStr.parenthesizer (p : Parenthesizer) : Parenthesizer := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => if chunk.isOfKind interpolatedStrLitKind then goLeft else p @[combinatorParenthesizer Lean.Parser.dbgTraceState] def dbgTraceState.parenthesizer (label : String) (p : Parenthesizer) : Parenthesizer := p @[combinatorParenthesizer ite, macroInline] def ite {α : Type} (c : Prop) [h : Decidable c] (t e : Parenthesizer) : Parenthesizer := if c then t else e open Parser abbrev ParenthesizerAliasValue := AliasValue Parenthesizer builtin_initialize parenthesizerAliasesRef : IO.Ref (NameMap ParenthesizerAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : ParenthesizerAliasValue) : IO Unit := do Parser.registerAliasCore parenthesizerAliasesRef aliasName v instance : Coe Parenthesizer ParenthesizerAliasValue := { coe := AliasValue.const } instance : Coe (Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.unary } instance : Coe (Parenthesizer → Parenthesizer → Parenthesizer) ParenthesizerAliasValue := { coe := AliasValue.binary } builtin_initialize registerAlias "ws" checkWsBefore.parenthesizer registerAlias "noWs" checkNoWsBefore.parenthesizer registerAlias "linebreak" checkLinebreakBefore.parenthesizer registerAlias "colGt" checkColGt.parenthesizer registerAlias "colGe" checkColGe.parenthesizer registerAlias "lookahead" lookahead.parenthesizer registerAlias "atomic" atomic.parenthesizer registerAlias "notFollowedBy" notFollowedBy.parenthesizer registerAlias "withPosition" withPosition.parenthesizer registerAlias "interpolatedStr" interpolatedStr.parenthesizer registerAlias "orelse" orelse.parenthesizer registerAlias "andthen" andthen.parenthesizer end Parenthesizer open Parenthesizer /-- Add necessary parentheses in `stx` parsed by `parser`. -/ def parenthesize (parenthesizer : Parenthesizer) (stx : Syntax) : CoreM Syntax := do trace[PrettyPrinter.parenthesize.input] "{fmt stx}" catchInternalId backtrackExceptionId (do let (_, st) ← (parenthesizer {}).run { stxTrav := Syntax.Traverser.fromSyntax stx } pure st.stxTrav.cur) (fun _ => throwError "parenthesize: uncaught backtrack exception") def parenthesizeTerm := parenthesize $ categoryParser.parenthesizer `term 0 def parenthesizeCommand := parenthesize $ categoryParser.parenthesizer `command 0 builtin_initialize registerTraceClass `PrettyPrinter.parenthesize end PrettyPrinter end Lean
e19c5d872a95f1225bf21f0b0ea9c2fa9d27745c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/LOption.lean
9534ae184f611f3c3cf2b9069573c2237e28d5ec
[ "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
757
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ universe u namespace Lean inductive LOption (α : Type u) where | none : LOption α | some : α → LOption α | undef : LOption α deriving Inhabited, BEq instance [ToString α] : ToString (LOption α) where toString | .none => "none" | .undef => "undef" | .some a => "(some " ++ toString a ++ ")" end Lean def Option.toLOption {α : Type u} : Option α → Lean.LOption α | none => .none | some a => .some a @[inline] def toLOptionM {α} {m : Type → Type} [Monad m] (x : m (Option α)) : m (Lean.LOption α) := do let b ← x return b.toLOption
f243a0fd5610cc2ec856e291b9bff6e714edebc8
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Std/Data/DList.lean
1d95287b55ebf400212c8948e0e7d486a5f285c9
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,813
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace Std universes u /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `concat` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) where apply : List α → List α invariant : ∀ l, apply l = apply [] ++ l namespace DList variables {α : Type u} open List def ofList (l : List α) : DList α := ⟨(l ++ ·), fun t => by show _ = (l ++ []) ++ _; rw appendNil⟩ def empty : DList α := ⟨id, fun t => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ def toList : DList α → List α | ⟨f, h⟩ => f [] def singleton (a : α) : DList α := { apply := fun t => a :: t, invariant := fun t => rfl } def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t, invariant := by intro t show a :: f t = a :: f [] ++ t rw [consAppend, h] } def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g, invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← appendAssoc (f []) (g []) t, ← h₁ (g [])] } def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t), invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), appendAssoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ end DList end Std
8872a1f6ff70a514ca0a67dd08b81c50f233941d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/imo/imo2008_q4.lean
74230a759b263a2dbe357062450fd869bacdd289
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,645
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic import data.real.sqrt import data.real.nnreal /-! # IMO 2008 Q4 Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real numbers to the positive real numbers) such that ``` (f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2) ``` for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`. # Solution The desired theorem is that either `f = λ x, x` or `f = λ x, 1/x` -/ open real lemma abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : abs x = 1 := begin let x₀ := real.to_nnreal (abs x), have h' : (abs x) ^ n = 1, { rwa [pow_abs, h, abs_one] }, have : (x₀ : ℝ) ^ n = 1, rw (real.coe_to_nnreal (abs x) (abs_nonneg x)), exact h', have : x₀ = 1 := eq_one_of_pow_eq_one hn (show x₀ ^ n = 1, by assumption_mod_cast), rwa ← real.coe_to_nnreal (abs x) (abs_nonneg x), assumption_mod_cast, end theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f(x) > 0) : (∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z → (f(w) ^ 2 + f(x) ^ 2) / (f(y ^ 2) + f(z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔ ((∀ x > 0, f(x) = x) ∨ (∀ x > 0, f(x) = 1 / x)) := begin split, swap, -- proof that f(x) = x and f(x) = 1/x satisfy the condition { rintros (h | h), { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] }, { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)], have hy2z2 : y ^ 2 + z ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hy 2) (pow_pos hz 2)), have hz2y2 : z ^ 2 + y ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hz 2) (pow_pos hy 2)), have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2, { rw [← mul_pow w x 2, ← mul_pow y z 2, hprod] }, field_simp [ne_of_gt hw, ne_of_gt hx, ne_of_gt hy, ne_of_gt hz, hy2z2, hz2y2, hp2], ring } }, -- proof that the only solutions are f(x) = x or f(x) = 1/x intro H₂, have h₀ : f(1) ≠ 0, { specialize H₁ 1 zero_lt_one, exact ne_of_gt H₁ }, have h₁ : f(1) = 1, { specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl, norm_num at H₂, simp only [← two_mul] at H₂, rw mul_div_mul_left (f(1) ^ 2) (f 1) two_ne_zero at H₂, rwa ← (div_eq_iff h₀).mpr (sq (f 1)) }, have h₂ : ∀ x > 0, (f(x) - x) * (f(x) - 1 / x) = 0, { intros x hx, have h1xss : 1 * x = (sqrt x) * (sqrt x), { rw [one_mul, mul_self_sqrt (le_of_lt hx)] }, specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss, rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f(x)), ← two_mul x] at H₂, have hx_ne_0 : x ≠ 0 := ne_of_gt hx, have hfx_ne_0 : f(x) ≠ 0, { specialize H₁ x hx, exact ne_of_gt H₁ }, field_simp at H₂, have h1 : (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 0, { calc (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 2 * (f(x) - x) * (x * f(x) - x * 1 / x) : by ring ... = 2 * (f(x) - x) * (x * f(x) - 1) : by rw (mul_div_cancel_left 1 hx_ne_0) ... = ((1 + f(x) ^ 2) * (2 * x) - (1 + x ^ 2) * (2 * f(x))) : by ring ... = 0 : sub_eq_zero.mpr H₂ }, have h2x_ne_0 : 2 * x ≠ 0 := mul_ne_zero two_ne_zero hx_ne_0, calc ((f(x) - x) * (f(x) - 1 / x)) = (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) / (2 * x) : (mul_div_cancel_left _ h2x_ne_0).symm ... = 0 : by { rw h1, exact zero_div (2 * x) } }, have h₃ : ∀ x > 0, f(x) = x ∨ f(x) = 1 / x, { simpa [sub_eq_zero] using h₂ }, by_contradiction, push_neg at h, rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩, obtain hfa₂ := or.resolve_right (h₃ a ha) hfa₁, -- f(a) ≠ 1/a, f(a) = a obtain hfb₂ := or.resolve_left (h₃ b hb) hfb₁, -- f(b) ≠ b, f(b) = 1/b have hab : a * b > 0 := mul_pos ha hb, have habss : a * b = sqrt(a * b) * sqrt(a * b) := (mul_self_sqrt (le_of_lt hab)).symm, specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss, rw [sq_sqrt (le_of_lt hab), ← two_mul (f(a * b)), ← two_mul (a * b)] at H₂, rw [hfa₂, hfb₂] at H₂, have h2ab_ne_0 : 2 * (a * b) ≠ 0 := mul_ne_zero two_ne_zero (ne_of_gt hab), specialize h₃ (a * b) hab, cases h₃ with hab₁ hab₂, -- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false { rw hab₁ at H₂, field_simp at H₂, obtain hb₁ := or.resolve_right H₂ h2ab_ne_0, field_simp [ne_of_gt hb] at hb₁, rw (show b ^ 2 * b ^ 2 = b ^ 4, by ring) at hb₁, obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0, by norm_num) hb₁.symm, rw abs_of_pos hb at hb₂, rw hb₂ at hfb₁, exact hfb₁ h₁ }, -- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false { have hb_ne_0 : b ≠ 0 := ne_of_gt hb, rw hab₂ at H₂, field_simp at H₂, rw ← sub_eq_zero at H₂, rw (show (a ^ 2 * b ^ 2 + 1) * (a * b) * (2 * (a * b)) - (a ^ 2 + b ^ 2) * (b ^ 2 * 2) = 2 * (b ^ 4) * (a ^ 4 - 1), by ring) at H₂, have h2b4_ne_0 : 2 * (b ^ 4) ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0), have ha₁ : a ^ 4 = 1, { simpa [sub_eq_zero, h2b4_ne_0] using H₂ }, obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0, by norm_num) ha₁, rw abs_of_pos ha at ha₂, rw ha₂ at hfa₁, norm_num at hfa₁ }, end
1fd87508a7465ea4da626130dac058ef41d39b97
94e33a31faa76775069b071adea97e86e218a8ee
/src/model_theory/substructures.lean
68187258f94971ebe1c1b74d5b714b48c2e2e1f3
[ "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
29,583
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.closure import model_theory.semantics import model_theory.encoding /-! # First-Order Substructures This file defines substructures of first-order structures in a similar manner to the various substructures appearing in the algebra library. ## Main Definitions * A `first_order.language.substructure` is defined so that `L.substructure M` is the type of all substructures of the `L`-structure `M`. * `first_order.language.substructure.closure` is defined so that if `s : set M`, `closure L s` is the least substructure of `M` containing `s`. * `first_order.language.substructure.comap` is defined so that `s.comap f` is the preimage of the substructure `s` under the homomorphism `f`, as a substructure. * `first_order.language.substructure.map` is defined so that `s.map f` is the image of the substructure `s` under the homomorphism `f`, as a substructure. * `first_order.language.hom.range` is defined so that `f.map` is the range of the the homomorphism `f`, as a substructure. * `first_order.language.hom.dom_restrict` and `first_order.language.hom.cod_restrict` restrict the domain and codomain respectively of first-order homomorphisms to substructures. * `first_order.language.embedding.dom_restrict` and `first_order.language.embedding.cod_restrict` restrict the domain and codomain respectively of first-order embeddings to substructures. * `first_order.language.substructure.inclusion` is the inclusion embedding between substructures. ## Main Results * `L.substructure M` forms a `complete_lattice`. -/ universes u v w namespace first_order namespace language variables {L : language.{u v}} {M : Type w} {N P : Type*} variables [L.Structure M] [L.Structure N] [L.Structure P] open_locale first_order cardinal open Structure cardinal section closed_under open set variables {n : ℕ} (f : L.functions n) (s : set M) /-- Indicates that a set in a given structure is a closed under a function symbol. -/ def closed_under : Prop := ∀ (x : fin n → M), (∀ i : fin n, x i ∈ s) → fun_map f x ∈ s variable (L) @[simp] lemma closed_under_univ : closed_under f (univ : set M) := λ _ _, mem_univ _ variables {L f s} {t : set M} namespace closed_under lemma inter (hs : closed_under f s) (ht : closed_under f t) : closed_under f (s ∩ t) := λ x h, mem_inter (hs x (λ i, mem_of_mem_inter_left (h i))) (ht x (λ i, mem_of_mem_inter_right (h i))) lemma inf (hs : closed_under f s) (ht : closed_under f t) : closed_under f (s ⊓ t) := hs.inter ht variables {S : set (set M)} lemma Inf (hS : ∀ s, s ∈ S → closed_under f s) : closed_under f (Inf S) := λ x h s hs, hS s hs x (λ i, h i s hs) end closed_under end closed_under variables (L) (M) /-- A substructure of a structure `M` is a set closed under application of function symbols. -/ structure substructure := (carrier : set M) (fun_mem : ∀{n}, ∀ (f : L.functions n), closed_under f carrier) variables {L} {M} namespace substructure instance : set_like (L.substructure M) M := ⟨substructure.carrier, λ p q h, by cases p; cases q; congr'⟩ /-- See Note [custom simps projection] -/ def simps.coe (S : L.substructure M) : set M := S initialize_simps_projections substructure (carrier → coe) @[simp] lemma mem_carrier {s : L.substructure M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two substructures are equal if they have the same elements. -/ @[ext] theorem ext {S T : L.substructure M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy a substructure replacing `carrier` with a set that is equal to it. -/ protected def copy (S : L.substructure M) (s : set M) (hs : s = S) : L.substructure M := { carrier := s, fun_mem := λ n f, hs.symm ▸ (S.fun_mem f) } end substructure variable {S : L.substructure M} lemma term.realize_mem {α : Type*} (t : L.term α) (xs : α → M) (h : ∀ a, xs a ∈ S) : t.realize xs ∈ S := begin induction t with a n f ts ih, { exact h a }, { exact substructure.fun_mem _ _ _ ih } end namespace substructure @[simp] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := set_like.coe_injective hs lemma constants_mem (c : L.constants) : ↑c ∈ S := mem_carrier.2 (S.fun_mem c _ fin.elim0) /-- The substructure `M` of the structure `M`. -/ instance : has_top (L.substructure M) := ⟨{ carrier := set.univ, fun_mem := λ n f x h, set.mem_univ _ }⟩ instance : inhabited (L.substructure M) := ⟨⊤⟩ @[simp] lemma mem_top (x : M) : x ∈ (⊤ : L.substructure M) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : L.substructure M) : set M) = set.univ := rfl /-- The inf of two substructures is their intersection. -/ instance : has_inf (L.substructure M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, fun_mem := λ n f, (S₁.fun_mem f).inf (S₂.fun_mem f) }⟩ @[simp] lemma coe_inf (p p' : L.substructure M) : ((p ⊓ p' : L.substructure M) : set M) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : L.substructure M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (L.substructure M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, fun_mem := λ n f, closed_under.Inf begin rintro _ ⟨t, rfl⟩, by_cases h : t ∈ s, { simpa [h] using t.fun_mem f }, { simp [h] } end }⟩ @[simp, norm_cast] lemma coe_Inf (S : set (L.substructure M)) : ((Inf S : L.substructure M) : set M) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (L.substructure M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ lemma mem_infi {ι : Sort*} {S : ι → L.substructure M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, norm_cast] lemma coe_infi {ι : Sort*} {S : ι → L.substructure M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] /-- Substructures of a structure form a complete lattice. -/ instance : complete_lattice (L.substructure M) := { le := (≤), lt := (<), top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (L.substructure M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from set_like.coe_subset_coe) is_glb_binfi } variable (L) /-- The `L.substructure` generated by a set. -/ def closure : lower_adjoint (coe : L.substructure M → set M) := ⟨λ s, Inf {S | s ⊆ S}, λ s S, ⟨set.subset.trans (λ x hx, mem_Inf.2 $ λ S hS, hS hx), λ h, Inf_le h⟩⟩ variables {L} {s : set M} lemma mem_closure {x : M} : x ∈ closure L s ↔ ∀ S : L.substructure M, s ⊆ S → x ∈ S := mem_Inf /-- The substructure generated by a set includes the set. -/ @[simp] lemma subset_closure : s ⊆ closure L s := (closure L).le_closure s lemma not_mem_of_not_mem_closure {P : M} (hP : P ∉ closure L s) : P ∉ s := λ h, hP (subset_closure h) @[simp] lemma closed (S : L.substructure M) : (closure L).closed (S : set M) := congr rfl ((closure L).eq_of_le set.subset.rfl (λ x xS, mem_closure.2 (λ T hT, hT xS))) open set /-- A substructure `S` includes `closure L s` if and only if it includes `s`. -/ @[simp] lemma closure_le : closure L s ≤ S ↔ s ⊆ S := (closure L).closure_le_closed_iff_le s S.closed /-- Substructure closure of a set is monotone in its argument: if `s ⊆ t`, then `closure L s ≤ closure L t`. -/ lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure L s ≤ closure L t := (closure L).monotone h lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure L s) : closure L s = S := (closure L).eq_of_le h₁ h₂ lemma coe_closure_eq_range_term_realize : (closure L s : set M) = range (@term.realize L _ _ _ (coe : s → M)) := begin let S : L.substructure M := ⟨range (term.realize coe), λ n f x hx, _⟩, { change _ = (S : set M), rw ← set_like.ext'_iff, refine closure_eq_of_le (λ x hx, ⟨var ⟨x, hx⟩, rfl⟩) (le_Inf (λ S' hS', _)), { rintro _ ⟨t, rfl⟩, exact t.realize_mem _ (λ i, hS' i.2) } }, { simp only [mem_range] at *, refine ⟨func f (λ i, (classical.some (hx i))), _⟩, simp only [term.realize, λ i, classical.some_spec (hx i)] } end instance small_closure [small.{u} s] : small.{u} (closure L s) := begin rw [← set_like.coe_sort_coe, substructure.coe_closure_eq_range_term_realize], exact small_range _, end lemma mem_closure_iff_exists_term {x : M} : x ∈ closure L s ↔ ∃ (t : L.term s), t.realize (coe : s → M) = x := by rw [← set_like.mem_coe, coe_closure_eq_range_term_realize, mem_range] lemma lift_card_closure_le_card_term : cardinal.lift.{max u w} (# (closure L s)) ≤ # (L.term s) := begin rw [← set_like.coe_sort_coe, coe_closure_eq_range_term_realize], rw [← cardinal.lift_id'.{w (max u w)} (# (L.term s))], exact cardinal.mk_range_le_lift, end theorem lift_card_closure_le : cardinal.lift.{u w} (# (closure L s)) ≤ max ℵ₀ (cardinal.lift.{u w} (#s) + cardinal.lift.{w u} (#(Σ i, L.functions i))) := begin rw ←lift_umax, refine lift_card_closure_le_card_term.trans (term.card_le.trans _), rw [mk_sum, lift_umax], end variable (L) lemma _root_.set.countable.substructure_closure [L.countable_functions] (h : s.countable) : nonempty (encodable (closure L s)) := begin haveI : nonempty (encodable s) := h, rw [encodable_iff, ← lift_le_aleph_0], exact lift_card_closure_le_card_term.trans term.card_le_aleph_0, end variables {L} (S) /-- An induction principle for closure membership. If `p` holds for all elements of `s`, and is preserved under function symbols, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure L s) (Hs : ∀ x ∈ s, p x) (Hfun : ∀ {n : ℕ} (f : L.functions n), closed_under f (set_of p)) : p x := (@closure_le L M _ ⟨set_of p, λ n, Hfun⟩ _).2 Hs h /-- If `s` is a dense set in a structure `M`, `substructure.closure L s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, and verify that `p` is preserved under function symbols. -/ @[elab_as_eliminator] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure L s = ⊤) (Hs : ∀ x ∈ s, p x) (Hfun : ∀ {n : ℕ} (f : L.functions n), closed_under f (set_of p)) : p x := have ∀ x ∈ closure L s, p x, from λ x hx, closure_induction hx Hs (λ n, Hfun), by simpa [hs] using this x variables (L) (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure L M _) coe := { choice := λ s _, closure L s, gc := (closure L).gc, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variables {L} {M} /-- Closure of a substructure `S` equals `S`. -/ @[simp] lemma closure_eq : closure L (S : set M) = S := (substructure.gi L M).l_u_eq S @[simp] lemma closure_empty : closure L (∅ : set M) = ⊥ := (substructure.gi L M).gc.l_bot @[simp] lemma closure_univ : closure L (univ : set M) = ⊤ := @coe_top L M _ ▸ closure_eq ⊤ lemma closure_union (s t : set M) : closure L (s ∪ t) = closure L s ⊔ closure L t := (substructure.gi L M).gc.l_sup lemma closure_Union {ι} (s : ι → set M) : closure L (⋃ i, s i) = ⨆ i, closure L (s i) := (substructure.gi L M).gc.l_supr instance small_bot : small.{u} (⊥ : L.substructure M) := begin rw ← closure_empty, exact substructure.small_closure end /-! ### `comap` and `map` -/ /-- The preimage of a substructure along a homomorphism is a substructure. -/ @[simps] def comap (φ : M →[L] N) (S : L.substructure N) : L.substructure M := { carrier := (φ ⁻¹' S), fun_mem := λ n f x hx, begin rw [mem_preimage, φ.map_fun], exact S.fun_mem f (φ ∘ x) hx, end } @[simp] lemma mem_comap {S : L.substructure N} {f : M →[L] N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl lemma comap_comap (S : L.substructure P) (g : N →[L] P) (f : M →[L] N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp] lemma comap_id (S : L.substructure P) : S.comap (hom.id _ _) = S := ext (by simp) /-- The image of a substructure along a homomorphism is a substructure. -/ @[simps] def map (φ : M →[L] N) (S : L.substructure M) : L.substructure N := { carrier := (φ '' S), fun_mem := λ n f x hx, (mem_image _ _ _).1 ⟨fun_map f (λ i, classical.some (hx i)), S.fun_mem f _ (λ i, (classical.some_spec (hx i)).1), begin simp only [hom.map_fun, set_like.mem_coe], exact congr rfl (funext (λ i, (classical.some_spec (hx i)).2)), end⟩ } @[simp] lemma mem_map {f : M →[L] N} {S : L.substructure M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex lemma mem_map_of_mem (f : M →[L] N) {S : L.substructure M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx lemma apply_coe_mem_map (f : M →[L] N) (S : L.substructure M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop lemma map_map (g : N →[L] P) (f : M →[L] N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ lemma map_le_iff_le_comap {f : M →[L] N} {S : L.substructure M} {T : L.substructure N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff lemma gc_map_comap (f : M →[L] N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap lemma map_le_of_le_comap {T : L.substructure N} {f : M →[L] N} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le lemma le_comap_of_map_le {T : L.substructure N} {f : M →[L] N} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u lemma le_comap_map {f : M →[L] N} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le {S : L.substructure N} {f : M →[L] N} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ lemma monotone_map {f : M →[L] N} : monotone (map f) := (gc_map_comap f).monotone_l lemma monotone_comap {f : M →[L] N} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp] lemma map_comap_map {f : M →[L] N} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp] lemma comap_map_comap {S : L.substructure N} {f : M →[L] N} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ lemma map_sup (S T : L.substructure M) (f : M →[L] N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : M →[L] N) (s : ι → L.substructure M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (S T : L.substructure N) (f : M →[L] N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : M →[L] N) (s : ι → L.substructure N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : M →[L] N) : (⊥ : L.substructure M).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : M →[L] N) : (⊤ : L.substructure N).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma map_id (S : L.substructure M) : S.map (hom.id L M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) lemma map_closure (f : M →[L] N) (s : set M) : (closure L s).map f = closure L (f '' s) := eq.symm $ closure_eq_of_le (set.image_subset f subset_closure) $ map_le_iff_le_comap.2 $ closure_le.2 $ λ x hx, subset_closure ⟨x, hx, rfl⟩ @[simp] lemma closure_image (f : M →[L] N) : closure L (f '' s) = map f (closure L s) := (map_closure f s).symm section galois_coinsertion variables {ι : Type*} {f : M →[L] N} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (S : L.substructure M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (S T : L.substructure M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → L.substructure M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (S T : L.substructure M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → L.substructure M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective {S T : L.substructure M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : M →[L] N} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) lemma map_comap_eq_of_surjective (S : L.substructure N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective lemma map_inf_comap_of_surjective (S T : L.substructure N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (S : ι → L.substructure N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ lemma map_sup_comap_of_surjective (S T : L.substructure N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (S : ι → L.substructure N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ lemma comap_le_comap_iff_of_surjective {S T : L.substructure N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion instance induced_Structure {S : L.substructure M} : L.Structure S := { fun_map := λ n f x, ⟨fun_map f (λ i, x i), S.fun_mem f (λ i, x i) (λ i, (x i).2)⟩, rel_map := λ n r x, rel_map r (λ i, (x i : M)) } /-- The natural embedding of an `L.substructure` of `M` into `M`. -/ def subtype (S : L.substructure M) : S ↪[L] M := { to_fun := coe, inj' := subtype.coe_injective } @[simp] theorem coe_subtype : ⇑S.subtype = coe := rfl /-- The equivalence between the maximal substructure of a structure and the structure itself. -/ def top_equiv : (⊤ : L.substructure M) ≃[L] M := { to_fun := subtype ⊤, inv_fun := λ m, ⟨m, mem_top m⟩, left_inv := λ m, by simp, right_inv := λ m, rfl } @[simp] lemma coe_top_equiv : ⇑(top_equiv : (⊤ : L.substructure M) ≃[L] M) = coe := rfl /-- A dependent version of `substructure.closure_induction`. -/ @[elab_as_eliminator] lemma closure_induction' (s : set M) {p : Π x, x ∈ closure L s → Prop} (Hs : ∀ x (h : x ∈ s), p x (subset_closure h)) (Hfun : ∀ {n : ℕ} (f : L.functions n), closed_under f {x | ∃ hx, p x hx}) {x} (hx : x ∈ closure L s) : p x hx := begin refine exists.elim _ (λ (hx : x ∈ closure L s) (hc : p x hx), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hs x hx⟩) @Hfun end end substructure namespace Lhom open substructure variables {L' : language} [L'.Structure M] (φ : L →ᴸ L') [φ.is_expansion_on M] include φ /-- Reduces the language of a substructure along a language hom. -/ def substructure_reduct : L'.substructure M ↪o L.substructure M := { to_fun := λ S, { carrier := S, fun_mem := λ n f x hx, begin have h := S.fun_mem (φ.on_function f) x hx, simp only [is_expansion_on.map_on_function, substructure.mem_carrier] at h, exact h, end }, inj' := λ S T h, begin simp only [set_like.coe_set_eq] at h, exact h, end, map_rel_iff' := λ S T, iff.rfl } @[simp] lemma mem_substructure_reduct {x : M} {S : L'.substructure M} : x ∈ φ.substructure_reduct S ↔ x ∈ S := iff.rfl @[simp] lemma coe_substructure_reduct {S : L'.substructure M} : (φ.substructure_reduct S : set M) = ↑S := rfl end Lhom namespace substructure /-- Turns any substructure containing a constant set `A` into a `L[[A]]`-substructure. -/ def with_constants (S : L.substructure M) {A : set M} (h : A ⊆ S) : L[[A]].substructure M := { carrier := S, fun_mem := λ n f, begin cases f, { exact S.fun_mem f }, { cases n, { exact λ _ _, h f.2 }, { exact is_empty_elim f } } end } variables {A : set M} {s : set M} (h : A ⊆ S) @[simp] lemma mem_with_constants {x : M} : x ∈ S.with_constants h ↔ x ∈ S := iff.rfl @[simp] lemma coe_with_constants : (S.with_constants h : set M) = ↑S := rfl @[simp] lemma reduct_with_constants : (L.Lhom_with_constants A).substructure_reduct (S.with_constants h) = S := by { ext, simp } lemma subset_closure_with_constants : A ⊆ (closure (L[[A]]) s) := begin intros a ha, simp only [set_like.mem_coe], let a' : (L[[A]]).constants := sum.inr ⟨a, ha⟩, exact constants_mem a', end lemma closure_with_constants_eq : (closure (L[[A]]) s) = (closure L (A ∪ s)).with_constants ((A.subset_union_left s).trans subset_closure) := begin refine closure_eq_of_le ((A.subset_union_right s).trans subset_closure) _, rw ← ((L.Lhom_with_constants A).substructure_reduct).le_iff_le, simp only [subset_closure, reduct_with_constants, closure_le, Lhom.coe_substructure_reduct, set.union_subset_iff, and_true], { exact subset_closure_with_constants }, { apply_instance }, { apply_instance }, end end substructure namespace hom open substructure /-- The restriction of a first-order hom to a substructure `s ⊆ M` gives a hom `s → N`. -/ @[simps] def dom_restrict (f : M →[L] N) (p : L.substructure M) : p →[L] N := f.comp p.subtype.to_hom /-- A first-order hom `f : M → N` whose values lie in a substructure `p ⊆ N` can be restricted to a hom `M → p`. -/ @[simps] def cod_restrict (p : L.substructure N) (f : M →[L] N) (h : ∀c, f c ∈ p) : M →[L] p := { to_fun := λc, ⟨f c, h c⟩, map_rel' := λ n R x h, f.map_rel R x h } @[simp] lemma comp_cod_restrict (f : M →[L] N) (g : N →[L] P) (p : L.substructure P) (h : ∀b, g b ∈ p) : ((cod_restrict p g h).comp f : M →[L] p) = cod_restrict p (g.comp f) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (f : M →[L] N) (p : L.substructure N) (h : ∀b, f b ∈ p) : p.subtype.to_hom.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- The range of a first-order hom `f : M → N` is a submodule of `N`. See Note [range copy pattern]. -/ def range (f : M →[L] N) : L.substructure N := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe (f : M →[L] N) : (range f : set N) = set.range f := rfl @[simp] theorem mem_range {f : M →[L] N} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map (f : M →[L] N) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self (f : M →[L] N) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (id L M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp (f : M →[L] N) (g : N →[L] P) : range (g.comp f : M →[L] P) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range (f : M →[L] N) (g : N →[L] P) : range (g.comp f : M →[L] P) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top {f : M →[L] N} : range f = ⊤ ↔ function.surjective f := by rw [set_like.ext'_iff, range_coe, coe_top, set.range_iff_surjective] lemma range_le_iff_comap {f : M →[L] N} {p : L.substructure N} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →[L] N} {p : L.substructure M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) /-- The substructure of elements `x : M` such that `f x = g x` -/ def eq_locus (f g : M →[L] N) : substructure L M := { carrier := {x : M | f x = g x}, fun_mem := λ n fn x hx, by { have h : f ∘ x = g ∘ x := by { ext, repeat {rw function.comp_apply}, apply hx, }, simp [h], } } /-- If two `L.hom`s are equal on a set, then they are equal on its substructure closure. -/ lemma eq_on_closure {f g : M →[L] N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure L s) := show closure L s ≤ f.eq_locus g, from closure_le.2 h lemma eq_of_eq_on_top {f g : M →[L] N} (h : set.eq_on f g (⊤ : substructure L M)) : f = g := ext $ λ x, h trivial variable {s : set M} lemma eq_of_eq_on_dense (hs : closure L s = ⊤) {f g : M →[L] N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h end hom namespace embedding open substructure /-- The restriction of a first-order embedding to a substructure `s ⊆ M` gives an embedding `s → N`. -/ def dom_restrict (f : M ↪[L] N) (p : L.substructure M) : p ↪[L] N := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M ↪[L] N) (p : L.substructure M) (x : p) : f.dom_restrict p x = f x := rfl /-- A first-order embedding `f : M → N` whose values lie in a substructure `p ⊆ N` can be restricted to an embedding `M → p`. -/ def cod_restrict (p : L.substructure N) (f : M ↪[L] N) (h : ∀c, f c ∈ p) : M ↪[L] p := { to_fun := f.to_hom.cod_restrict p h, inj' := λ a b ab, f.injective (subtype.mk_eq_mk.1 ab), map_fun' := λ n F x, (f.to_hom.cod_restrict p h).map_fun' F x, map_rel' := λ n r x, begin simp only, rw [← p.subtype.map_rel, function.comp.assoc], change rel_map r ((hom.comp p.subtype.to_hom (f.to_hom.cod_restrict p h)) ∘ x) ↔ _, rw [hom.subtype_comp_cod_restrict, ← f.map_rel], refl, end } @[simp] theorem cod_restrict_apply (p : L.substructure N) (f : M ↪[L] N) {h} (x : M) : (cod_restrict p f h x : N) = f x := rfl @[simp] lemma comp_cod_restrict (f : M ↪[L] N) (g : N ↪[L] P) (p : L.substructure P) (h : ∀b, g b ∈ p) : ((cod_restrict p g h).comp f : M ↪[L] p) = cod_restrict p (g.comp f) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (f : M ↪[L] N) (p : L.substructure N) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- The equivalence between a substructure `s` and its image `s.map f.to_hom`, where `f` is an embedding. -/ noncomputable def substructure_equiv_map (f : M ↪[L] N) (s : L.substructure M) : s ≃[L] s.map f.to_hom := { to_fun := cod_restrict (s.map f.to_hom) (f.dom_restrict s) (λ ⟨m, hm⟩, ⟨m, hm, rfl⟩), inv_fun := λ n, ⟨classical.some n.2, (classical.some_spec n.2).1⟩, left_inv := λ ⟨m, hm⟩, subtype.mk_eq_mk.2 (f.injective ((classical.some_spec (cod_restrict (s.map f.to_hom) (f.dom_restrict s) (λ ⟨m, hm⟩, ⟨m, hm, rfl⟩) ⟨m, hm⟩).2).2)), right_inv := λ ⟨n, hn⟩, subtype.mk_eq_mk.2 (classical.some_spec hn).2 } @[simp] lemma substructure_equiv_map_apply (f : M ↪[L] N) (p : L.substructure M) (x : p) : (f.substructure_equiv_map p x : N) = f x := rfl /-- The equivalence between the domain and the range of an embedding `f`. -/ noncomputable def equiv_range (f : M ↪[L] N) : M ≃[L] f.to_hom.range := { to_fun := cod_restrict f.to_hom.range f f.to_hom.mem_range_self, inv_fun := λ n, classical.some n.2, left_inv := λ m, f.injective (classical.some_spec (cod_restrict f.to_hom.range f f.to_hom.mem_range_self m).2), right_inv := λ ⟨n, hn⟩, subtype.mk_eq_mk.2 (classical.some_spec hn) } @[simp] lemma equiv_range_apply (f : M ↪[L] N) (x : M) : (f.equiv_range x : N) = f x := rfl end embedding namespace equiv lemma to_hom_range (f : M ≃[L] N) : f.to_hom.range = ⊤ := begin ext n, simp only [hom.mem_range, coe_to_hom, substructure.mem_top, iff_true], exact ⟨f.symm n, apply_symm_apply _ _⟩ end end equiv namespace substructure /-- The embedding associated to an inclusion of substructures. -/ def inclusion {S T : L.substructure M} (h : S ≤ T) : S ↪[L] T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp] lemma coe_inclusion {S T : L.substructure M} (h : S ≤ T) : (inclusion h : S → T) = set.inclusion h := rfl lemma range_subtype (S : L.substructure M) : S.subtype.to_hom.range = S := begin ext x, simp only [hom.mem_range, embedding.coe_to_hom, coe_subtype], refine ⟨_, λ h, ⟨⟨x, h⟩, rfl⟩⟩, rintros ⟨⟨y, hy⟩, rfl⟩, exact hy, end end substructure end language end first_order
a3a7cf3c9e0fb6a27f26877ea94d131ccef1ec14
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/nat/gcd.lean
29b196a1f4aa222507e04f0036b5e71b336df5d7
[ "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
16,957
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 -/ import data.nat.pow /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := iff.intro (λ h, ⟨dvd_trans h (gcd_dvd m n).left, dvd_trans h (gcd_dvd m n).right⟩) (λ h, dvd_gcd h.left h.right) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m := ⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left], λ h, h ▸ gcd_dvd_right m n⟩ theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m := by rw gcd_comm; apply gcd_eq_left_iff_dvd theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) id (assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd (dvd.trans (gcd_dvd_left m n) H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) (dvd.trans (gcd_dvd_right n m) H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd (dvd_refl _) H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) (dvd_refl _)) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) (dvd_refl _)) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] lemma gcd_add_mul_self (m n k : ℕ) : gcd m (n + k * m) = gcd m n := by simp [gcd_rec m (n + k * m), gcd_rec m n] theorem gcd_eq_zero_iff {i j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin split, { intro h, exact ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩, }, { intro h, rw [h.1, h.2], exact nat.gcd_zero_right _ } end /-! ### `lcm` -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' (dvd.trans (gcd_dvd_left m n) (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) (dvd.trans (dvd_lcm_left n k) (dvd_lcm_right m (lcm n k)))) (dvd.trans (dvd_lcm_right n k) (dvd_lcm_right m (lcm n k)))) (lcm_dvd (dvd.trans (dvd_lcm_left m n) (dvd_lcm_left (lcm m n) k)) (lcm_dvd (dvd.trans (dvd_lcm_right m n) (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) theorem lcm_ne_zero {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := by { intro h, simpa [h, hm, hn] using gcd_mul_lcm m n, } /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime_iff_gcd_eq_one {m n : ℕ} : coprime m n ↔ gcd m n = 1 := iff.rfl theorem coprime.gcd_eq_one {m n : ℕ} : coprime m n → gcd m n = 1 := id theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime_comm {m n : ℕ} : coprime n m ↔ coprime m n := ⟨coprime.symm, coprime.symm⟩ theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by rw [coprime_iff_gcd_eq_one, gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ co, not_lt_of_ge (le_of_dvd zero_lt_one $ by rw [←co.gcd_eq_one]; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := begin by_cases a_split : (a = 0), { subst a_split, rw zero_dvd_iff at dvd, simpa [dvd] using cmn, }, { rcases dvd with ⟨k, rfl⟩, rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split), exact coprime.coprime_mul_left cmn, }, end theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := (coprime.coprime_div_left cmn.symm dvd).symm lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime_iff_gcd_eq_one, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by simpa only [coprime_comm] using coprime_mul_iff_left lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := hmn.coprime_dvd_left $ gcd_dvd_right k m lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := hmn.coprime_dvd_right $ gcd_dvd_right k n lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := (hmn.gcd_left k).gcd_right l lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true := by simp [coprime] @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true := by simp [coprime] @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := by simp [coprime] /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) : { d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } := begin cases h0 : (gcd k m), case nat.zero { have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this, have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this, exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ }, case nat.succ : tmp { have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp, have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)), refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩, apply dvd_of_mul_dvd_mul_left hpos, rw [hd, ← gcd_mul_right], exact dvd_gcd (dvd_mul_right _ _) H } end theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := begin rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩, replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) ((h.gcd_both k k).mul_dvd_of_dvd_of_dvd (gcd_dvd_gcd_mul_right_right _ _ _) (gcd_dvd_gcd_mul_left_right _ _ _)) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pow_pos g0' _) h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end lemma gcd_mul_gcd_of_coprime_of_mul_eq_mul {a b c d : ℕ} (cop : c.coprime d) (h : a * b = c * d) : a.gcd c * b.gcd c = c := begin apply dvd_antisymm, { apply nat.coprime.dvd_of_dvd_mul_right (nat.coprime.mul (cop.gcd_left _) (cop.gcd_left _)), rw ← h, apply mul_dvd_mul (gcd_dvd _ _).1 (gcd_dvd _ _).1 }, { rw [gcd_comm a _, gcd_comm b _], transitivity c.gcd (a * b), rw [h, gcd_mul_right_right d c], apply gcd_mul_dvd_mul_gcd } end end nat
5eda64e3fa708dfe7d70277a48aa91c4331cfc06
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/metric_space/gromov_hausdorff.lean
e188636c80699482f76b5694ccdad237bdeceaa6
[ "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
55,397
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion import topology.metric_space.kuratowski /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λ x y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λ x, ⟨isometric.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding X⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ @[nolint has_inhabited_instance] definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e, use λ x, f x, split, { apply isometry_subtype_coe.comp f.isometry }, { rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding X).val) = (p.val ≃ᵢ range (Kuratowski_embedding X)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λ x, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩, apply isometry_subtype_coe end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y).val) = ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding.isometry X).isometric_on_range, have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry Y).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) = ((nonempty_compacts.Kuratowski_embedding X).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λ x y, Inf $ (λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X] [metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] {γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty X with ⟨xX, _⟩, let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λ x y, ha x y, have IΨ' : isometry Ψ' := λ x y, hb x y, have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xX⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _, (is_compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _, (is_compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have AX : ⟦A⟧ = to_GH_space X, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ }, have BY : ⟦B⟧ = to_GH_space Y, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [AX, BY] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y := begin inhabit X, inhabit Y, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y) → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y), { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y), { rw Ψrange, have : Φ xX ∈ p.val := Φrange ▸ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) + diam (univ : set Y) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring }, let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end, let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates X Y, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λ x y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λ x y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λ x y, dist_comm _ _ }, { exact λ x y z, dist_triangle _ _ _ }, { exact λ x y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p.2.2.union q.2.2).bounded, end ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)), have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀ p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set X) + 1 + diam (univ : set Y), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD (candidates_b_dist X Y) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X] (Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] : ∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling X Y), let Φ := F ∘ optimal_GH_injl X Y, let Ψ := F ∘ optimal_GH_injr X Y, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance : metric_space GH_space := { dist_self := λ x, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λ x y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := λ x y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λ x y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X] (p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {X : Type u} [metric_space X] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p.val → X) := isometry_subtype_coe, have hb : isometry (coe : q.val → X) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val → X), by simp, have J : q.val = range (coe : q.val → X), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃) (H : ∀ x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) : GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine le_of_forall_pos_le_add (λ δ δ0, _), rcases exists_mem_of_nonempty X with ⟨xX, _⟩, rcases hs xX with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λ p q, calc abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `X` and `Y` along the almost matching subsets letI : metric_space (X ⊕ Y) := glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl X Y, let Fr := @sum.inr X Y, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λ x y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λ x y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `X ⊕ Y`). -/ have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x) (λ x hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty Y with ⟨xY, _⟩, rcases hs' xY with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa⟩) (λ x _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λ δ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀ p:GH_space, ∃ s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λ p, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀ p:GH_space, ∀ t:set (p.rep), finite t → ∃ n:ℕ, ∃ e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λ p:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λ p:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λ p, ⟨N p, λ a b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩, refine ⟨_, by apply_instance, F, λ p q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀ x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀ p:GH_space, ∃ s : set (p.rep), ∃ N ≤ K n, ∃ E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λ a b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λ p, F p), _⟩, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀ x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)), by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).symm_apply_apply] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).symm_apply_apply] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) := ⟨{ space := A, metric := by apply_instance, embed := id, isom := λ x y, rfl }⟩ /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λ x y, rfl } (λ n Y, by letI : metric_space Y.space := Y.metric; exact { space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))), metric := by apply_instance, embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1)))) ∘ (optimal_GH_injr (X n) (X (n+1))), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space GH_space := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _), -- `X n` is a representative of `u n` let X := λ n, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : ∀ n, metric_space (Y n).space := λ n, (Y n).metric, have E : ∀ n : ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λ n, by { simp [Y, aux_gluing], refl }, let c := λ n, cast (E n), have ic : ∀ n, isometry (c n) := λ n x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Πn, (Y n).space → (Y n.succ).space := λ n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀ n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λ n, ⟨X2 n, ⟨range_nonempty _, is_compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀ n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
8289ab0dc6d337110c09ba0d27bb41194d70be5d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/Attributes.lean
7ecc9432a0515f3f7fcd2e482737fdffd97470e7
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,786
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, Sebastian Ullrich -/ import Lean.Elab.Util namespace Lean.Elab structure Attribute where kind : AttributeKind := AttributeKind.global name : Name stx : Syntax := Syntax.missing deriving Inhabited instance : ToFormat Attribute where format attr := let kindStr := match attr.kind with | AttributeKind.global => "" | AttributeKind.local => "local " | AttributeKind.scoped => "scoped " Format.bracket "@[" f!"{kindStr}{attr.name}{toString attr.stx}" "]" /-- ``` attrKind := leading_parser optional («scoped» <|> «local») ``` -/ def toAttributeKind (attrKindStx : Syntax) : MacroM AttributeKind := do if attrKindStx[0].isNone then return AttributeKind.global else if attrKindStx[0][0].getKind == ``Lean.Parser.Term.scoped then if (← Macro.getCurrNamespace).isAnonymous then throw <| Macro.Exception.error (← getRef) "scoped attributes must be used inside namespaces" return AttributeKind.scoped else return AttributeKind.local def mkAttrKindGlobal : Syntax := mkNode ``Lean.Parser.Term.attrKind #[mkNullNode] def elabAttr [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstance : Syntax) : m Attribute := do /- attrInstance := ppGroup $ leading_parser attrKind >> attrParser -/ let attrKind ← liftMacroM <| toAttributeKind attrInstance[0] let attr := attrInstance[1] let attr ← liftMacroM <| expandMacros attr let attrName ← if attr.getKind == ``Parser.Attr.simple then pure attr[0].getId.eraseMacroScopes else match attr.getKind with | .str _ s => pure <| Name.mkSimple s | _ => throwErrorAt attr "unknown attribute" let .ok impl := getAttributeImpl (← getEnv) attrName | throwError "unknown attribute [{attrName}]" let attrSyntaxNodeKind := attrInstance[1].getKind -- `Lean.Parser.Attr.simple` is a generic `attribute` parser used in simple attributes. -- We don't want to create an info tree node from a simple attribute to the generic parser. let declTarget := if attrSyntaxNodeKind == ``Lean.Parser.Attr.simple then impl.ref else attrSyntaxNodeKind if (← getEnv).contains declTarget && (← getInfoState).enabled then pushInfoLeaf <| .ofCommandInfo { elaborator := declTarget -- not truly an elaborator, but a sensible target for go-to-definition stx := attrInstance[1][0] -- We want to associate the information to the first atom only } /- The `AttrM` does not have sufficient information for expanding macros in `args`. So, we expand them before here before we invoke the attributer handlers implemented using `AttrM`. -/ return { kind := attrKind, name := attrName, stx := attr } def elabAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (attrInstances : Array Syntax) : m (Array Attribute) := do let mut attrs := #[] for attr in attrInstances do try attrs := attrs.push (← withRef attr do elabAttr attr) catch ex => logException ex return attrs -- leading_parser "@[" >> sepBy1 attrInstance ", " >> "]" def elabDeclAttrs [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] (stx : Syntax) : m (Array Attribute) := elabAttrs stx[1].getSepArgs end Lean.Elab
e626f1be460746619d491285bb3261171c3e4453
49bd2218ae088932d847f9030c8dbff1c5607bb7
/src/algebra/big_operators.lean
180d839fe0824f279e784adca26334ec7c01bf4b
[ "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
35,408
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset data.nat.enat import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : ({a, b} : finset α).prod f = f a * f b := by simp [prod_insert (not_mem_singleton.2 h.symm), mul_comm] @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, by simp only [disjoint_iff_ne, mem_image]; rintro ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩ ⟨_, _, _⟩ ⟨_, _⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := by { delta finset.prod, rw [← multiset.map_map, multiset.prod_hom _ g] } @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_ite [comm_monoid γ] {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : s.prod (λ x, h (if p x then f x else g x)) = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) := by letI := classical.dec_eq α; exact calc s.prod (λ x, h (if p x then f x else g x)) = (s.filter p ∪ s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : by rw [filter_union_filter_neg_eq] ... = (s.filter p).prod (λ x, h (if p x then f x else g x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (if p x then f x else g x)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (s.filter p).prod (λ x, h (f x)) * (s.filter (λ x, ¬ p x)).prod (λ x, h (g x)) : congr_arg2 _ (prod_congr rfl (by simp {contextual := tt})) (prod_congr rfl (by simp {contextual := tt})) @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : β) : s.prod (λ x, (ite (a = x) b 1)) = ite (a ∈ s) b 1 := begin rw ←finset.prod_filter, split_ifs; simp only [filter_eq, if_true, if_false, h, prod_empty, prod_singleton, insert_empty_eq_singleton], end @[to_additive] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ lemma sum_Ico_add {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) (m n k : ℕ) : (Ico m n).sum (λ l, f (k + l)) = (Ico (m + k) (n + k)).sum f := Ico.image_add m n k ▸ eq.symm $ sum_image $ λ x hx y hy h, nat.add_left_cancel h @[to_additive] lemma prod_Ico_add (f : ℕ → β) (m n k : ℕ) : (Ico m n).prod (λ l, f (k + l)) = (Ico (m + k) (n + k)).prod f := Ico.image_add m n k ▸ eq.symm $ prod_image $ λ x hx y hy h, nat.add_left_cancel h lemma sum_Ico_succ_top {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a ≤ b) (f : ℕ → δ) : (Ico a (b + 1)).sum f = (Ico a b).sum f + f b := by rw [Ico.succ_top hab, sum_insert Ico.not_mem_top, add_comm] @[to_additive] lemma prod_Ico_succ_top {a b : ℕ} (hab : a ≤ b) (f : ℕ → β) : (Ico a b.succ).prod f = (Ico a b).prod f * f b := @sum_Ico_succ_top (additive β) _ _ _ hab _ lemma sum_eq_sum_Ico_succ_bot {δ : Type*} [add_comm_monoid δ] {a b : ℕ} (hab : a < b) (f : ℕ → δ) : (Ico a b).sum f = f a + (Ico (a + 1) b).sum f := have ha : a ∉ Ico (a + 1) b, by simp, by rw [← sum_insert ha, Ico.insert_succ_bot hab] @[to_additive] lemma prod_eq_prod_Ico_succ_bot {a b : ℕ} (hab : a < b) (f : ℕ → β) : (Ico a b).prod f = f a * (Ico (a + 1) b).prod f := @sum_eq_sum_Ico_succ_bot (additive β) _ _ _ hab _ @[to_additive] lemma prod_Ico_consecutive (f : ℕ → β) {m n k : ℕ} (hmn : m ≤ n) (hnk : n ≤ k) : (Ico m n).prod f * (Ico n k).prod f = (Ico m k).prod f := Ico.union_consecutive hmn hnk ▸ eq.symm $ prod_union $ Ico.disjoint_consecutive m n k @[to_additive] lemma prod_range_mul_prod_Ico (f : ℕ → β) {m n : ℕ} (h : m ≤ n) : (range m).prod f * (Ico m n).prod f = (range n).prod f := Ico.zero_bot m ▸ Ico.zero_bot n ▸ prod_Ico_consecutive f (nat.zero_le m) h @[to_additive sum_Ico_eq_add_neg] lemma prod_Ico_eq_div {δ : Type*} [comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).prod f = (range n).prod f * ((range m).prod f)⁻¹ := eq_mul_inv_iff_mul_eq.2 $ by rw [mul_comm]; exact prod_range_mul_prod_Ico f h lemma sum_Ico_eq_sub {δ : Type*} [add_comm_group δ] (f : ℕ → δ) {m n : ℕ} (h : m ≤ n) : (Ico m n).sum f = (range n).sum f - (range m).sum f := sum_Ico_eq_add_neg f h @[to_additive] lemma prod_Ico_eq_prod_range (f : ℕ → β) (m n : ℕ) : (Ico m n).prod f = (range (n - m)).prod (λ l, f (m + l)) := begin by_cases h : m ≤ n, { rw [← Ico.zero_bot, prod_Ico_add, zero_add, nat.sub_add_cancel h] }, { replace h : n ≤ m := le_of_not_ge h, rw [Ico.eq_empty_of_le h, nat.sub_eq_zero_of_le h, range_zero, prod_empty, prod_empty] } end @[to_additive] lemma prod_range_zero (f : ℕ → β) : (range 0).prod f = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (range 1).prod f = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (range 1).sum f = f 0 := by { rw [range_one], apply @sum_singleton ℕ δ 0 f } attribute [to_additive finset.sum_range_one] prod_range_one @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_smul' [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_smul'] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (s.sum_hom _).symm lemma prod_nat_cast [comm_semiring β] (s : finset α) (f : α → ℕ) : ↑(s.prod f) = s.prod (λa, f a : α → β) := (s.prod_hom _).symm protected lemma sum_nat_coe_enat [decidable_eq α] (s : finset α) (f : α → ℕ) : s.sum (λ x, (f x : enat)) = (s.sum f : ℕ) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has, ih] } end theorem dvd_sum [comm_semiring α] {a : α} {s : finset β} {f : β → α} (h : ∀ x ∈ s, a ∣ f x) : a ∣ s.sum f := multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx) lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext.2 $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_bind (by simp [disjoint_left, finset.ext] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (s.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (s.sum_hom (λ x, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (s.sum_hom _).symm @[simp] lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end @[simp] lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) : s.sum (λ x, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 := begin convert sum_ite_eq s a (f a), funext, split_ifs with h; simp [h], end end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)), { assume x hx y hy h, simp only [disjoint_iff_ne, mem_image], rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq₂, eq₃, eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union sdiff_disjoint).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero [@decidable_rel β (≤)] (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section linear_ordered_comm_ring variables [decidable_eq α] [linear_ordered_comm_ring β] /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_le_one] }, { simp [has], apply mul_nonneg, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < s.prod f := begin induction s using finset.induction with a s has ih h, { simp [zero_lt_one] }, { simp [has], apply mul_pos, apply h0 a (mem_insert_self a s), exact ih (λ x H, h0 x (mem_insert_of_mem H)) } end /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : s.prod f ≤ s.prod g := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end end linear_ordered_comm_ring @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ theorem card_le_mul_card_image [decidable_eq β] {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := calc s.card = (s.image f).sum (λ a, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_image _ _ ... ≤ (s.image f).sum (λ _, n) : sum_le_sum hn ... = _ : by simp [mul_comm] @[simp] lemma prod_Ico_id_eq_fact (n : ℕ) : (Ico 1 n.succ).prod (λ x, x) = nat.fact n := calc (Ico 1 n.succ).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, by simp [*, nat.lt_succ_iff, nat.succ_le_iff] at *) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero, nat.succ_le_iff] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum lemma card_eq_sum_ones (s : finset α) : s.card = s.sum (λ _, 1) := by simp end finset section group open list variables [group α] [group β] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (s.prod f) = s.prod (λx, g (f x)) := (s.prod_hom g).symm @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset namespace with_top open finset variables [decidable_eq α] /-- sum of finte numbers is still finite -/ lemma sum_lt_top [ordered_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := finset.induction_on s (by { intro h, rw sum_empty, exact coe_lt_top _ }) (λa s ha ih h, begin rw [sum_insert ha, add_lt_top], split, { apply h, apply mem_insert_self }, { apply ih, intros a ha, apply h, apply mem_insert_of_mem ha } end) /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_monoid β] {s : finset α} {f : α → with_top β} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top end with_top
0b815117d5b8864f2fdebccc0fe16924fbf0875b
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Tactic/Simp.lean
5a9d006634f7d4be4c01a97af99e9a6d3c163226
[ "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
434
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp.SimpLemmas import Lean.Meta.Tactic.Simp.CongrLemmas import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.Simp.Main import Lean.Meta.Tactic.Simp.Rewrite namespace Lean builtin_initialize registerTraceClass `Meta.Tactic.simp end Lean
ce169c6dab27722aa5133fa889231fb4f410f9cb
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/thursday/afternoon/category_theory/exercise7.lean
816376c3c9a0fc801146ac27995b127f44f3cdce
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,471
lean
import category_theory.monoidal.category import algebra.category.CommRing.basic /-! Let's define the category of monoid objects in a monoidal category. -/ open category_theory variables (C : Type*) [category C] [monoidal_category C] structure Mon_in := (X : C) (ι : 𝟙_ C ⟶ X) (μ : X ⊗ X ⟶ X) -- There are three missing axioms here! -- Use `λ_ X`, `ρ_ X` and `α_ X Y Z` for unitors and associators. sorry namespace Mon_in variables {C} @[ext] structure hom (M N : Mon_in C) := sorry instance : category (Mon_in C) := sorry end Mon_in /-! Bonus projects (all but the first will be non-trivial with today's mathlib): * Construct the category of module objects for a fixed monoid object. * Check that `Mon_in Type ≌ Mon`. * Check that `Mon_in Mon ≌ CommMon`, via the Eckmann-Hilton argument. (You'll have to hook up the cartesian monoidal structure on `Mon` first.) * Check that `Mon_in AddCommGroup ≌ Ring`. (You'll have to hook up the monoidal structure on `AddCommGroup`. Currently we have the monoidal structure on `Module R`; perhaps one could specialize to `R = ℤ` and transport the monoidal structure across an equivalence? This sounds like some work!) * Check that `Mon_in (Module R) ≌ Algebra R`. * Show that if `C` is braided (you'll have to define that first!) then `Mon_in C` is naturally monoidal. * Can you transport this monoidal structure to `Ring` or `Algebra R`? How does it compare to the "native" one? -/
caf09874699062cd390fd7709b21d4cdad553d1d
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/star/algebra.lean
7e7cae6e6676815c2a6018b3c9837ab1c75d3e41
[ "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,100
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison. -/ import algebra.algebra.basic import algebra.star.basic /-! # Star algebras Introduces the notion of a star algebra over a star ring. -/ universes u v /-- A star algebra `A` over a star ring `R` is an algebra which is a star ring, and the two star structures are compatible in the sense `star (r • a) = star r • star a`. -/ -- Note that we take `star_ring A` as a typeclass argument, rather than extending it, -- to avoid having multiple definitions of the star operation. class star_algebra (R : Type u) (A : Type v) [comm_semiring R] [star_ring R] [semiring A] [star_ring A] [algebra R A] := (star_smul : ∀ (r : R) (a : A), star (r • a) = (@has_star.star R _ r) • star a) variables {A : Type v} @[simp] lemma star_smul (R : Type u) (A : Type v) [comm_semiring R] [star_ring R] [semiring A] [star_ring A] [algebra R A] [star_algebra R A] (r : R) (a : A) : star (r • a) = star r • star a := star_algebra.star_smul r a
7a226b0202201ea9749bd6a8aff543e5fe6b1e55
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/monoidal/category.lean
5f9b49a1fb0e905c7118d1f3909e3e9d41665e0a
[ "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
16,135
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.products.basic import category_theory.natural_isomorphism import tactic.basic import tactic.slice open category_theory universes v u open category_theory open category_theory.category open category_theory.iso namespace category_theory /-- In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`. Tensor product does not need to be strictly associative on objects, but there is a specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`, with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`. These associators and unitors satisfy the pentagon and triangle equations. -/ class monoidal_category (C : Type u) [𝒞 : category.{v} C] := -- curried tensor product of objects: (tensor_obj : C → C → C) (infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary -- curried tensor product of morphisms: (tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))) (infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary -- tensor product laws: (tensor_id' : ∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously) (tensor_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), (f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously) -- tensor unit: (tensor_unit : C) (notation `𝟙_` := tensor_unit) -- associator: (associator : Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)) (notation `α_` := associator) (associator_naturality' : ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), ((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously) -- left unitor: (left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X) (notation `λ_` := left_unitor) (left_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously) -- right unitor: (right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X) (notation `ρ_` := right_unitor) (right_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously) -- pentagon identity: (pentagon' : ∀ W X Y Z : C, ((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom) = (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously) -- triangle identity: (triangle' : ∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously) restate_axiom monoidal_category.tensor_id' attribute [simp] monoidal_category.tensor_id restate_axiom monoidal_category.tensor_comp' attribute [simp] monoidal_category.tensor_comp restate_axiom monoidal_category.associator_naturality' restate_axiom monoidal_category.left_unitor_naturality' restate_axiom monoidal_category.right_unitor_naturality' restate_axiom monoidal_category.pentagon' restate_axiom monoidal_category.triangle' attribute [simp] monoidal_category.triangle open monoidal_category infixr ` ⊗ `:70 := tensor_obj infixr ` ⊗ `:70 := tensor_hom notation `𝟙_` := tensor_unit notation `α_` := associator notation `λ_` := left_unitor notation `ρ_` := right_unitor /-- The tensor product of two isomorphisms is an isomorphism. -/ def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' := { hom := f.hom ⊗ g.hom, inv := f.inv ⊗ g.inv, hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id], inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] } infixr ` ⊗ `:70 := tensor_iso namespace monoidal_category section variables {C : Type u} [category.{v} C] [𝒞 : monoidal_category.{v} C] include 𝒞 instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := { ..(as_iso f ⊗ as_iso g) } @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g := rfl variables {U V W X Y Z : C} -- When `rewrite_search` lands, add @[search] attributes to -- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality -- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality -- monoidal_category.pentagon monoidal_category.triangle -- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id -- triangle_assoc_comp_left triangle_assoc_comp_right triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv -- left_unitor_tensor left_unitor_tensor_inv -- right_unitor_tensor right_unitor_tensor_inv -- pentagon_inv -- associator_inv_naturality -- left_unitor_inv_naturality -- right_unitor_inv_naturality @[simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) : (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := by { rw ←tensor_comp, simp } @[simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) : (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := by { rw ←tensor_comp, simp } @[simp] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) : ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) : (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f := by { rw [←tensor_comp], simp } lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) := begin apply (cancel_mono (λ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) := begin apply (cancel_mono (ρ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end @[simp] lemma tensor_left_iff {X Y : C} (f g : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) := begin split, { intro h, have h' := congr_arg (λ k, (λ_ _).inv ≫ k) h, dsimp at h', rw [←left_unitor_inv_naturality, ←left_unitor_inv_naturality] at h', exact (cancel_mono _).1 h', }, { intro h, subst h, } end @[simp] lemma tensor_right_iff {X Y : C} (f g : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) := begin split, { intro h, have h' := congr_arg (λ k, (ρ_ _).inv ≫ k) h, dsimp at h', rw [←right_unitor_inv_naturality, ←right_unitor_inv_naturality] at h', exact (cancel_mono _).1 h' }, { intro h, subst h, } end -- We now prove: -- ((α_ (𝟙_ C) X Y).hom) ≫ -- ((λ_ (X ⊗ Y)).hom) -- = ((λ_ X).hom ⊗ (𝟙 Y)) -- (and the corresponding fact for right unitors) -- following the proof on nLab: -- Lemma 2.2 at <https://ncatlab.org/nlab/revision/monoidal+category/115> lemma left_unitor_product_aux_perimeter (X Y : C) : ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom) = (((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := begin conv_lhs { congr, skip, rw [←category.assoc] }, rw [←category.assoc, monoidal_category.pentagon, associator_naturality, tensor_id, ←monoidal_category.triangle, ←category.assoc] end lemma left_unitor_product_aux_triangle (X Y : C) : ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫ (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) = ((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) := by rw [←comp_tensor_id, ←monoidal_category.triangle] lemma left_unitor_product_aux_square (X Y : C) : (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom ⊗ (𝟙 Y)) = (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := by rw associator_naturality lemma left_unitor_product_aux (X Y : C) : ((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom) = (𝟙 (𝟙_ C)) ⊗ ((λ_ X).hom ⊗ (𝟙 Y)) := begin rw ←(cancel_epi (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom), rw left_unitor_product_aux_square, rw ←(cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y))), slice_rhs 1 2 { rw left_unitor_product_aux_triangle }, conv_lhs { rw [left_unitor_product_aux_perimeter] } end lemma right_unitor_product_aux_perimeter (X Y : C) : ((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom) = ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X Y (𝟙_ C)).hom := begin transitivity (((α_ X Y _).hom ⊗ 𝟙 _) ≫ (α_ X _ _).hom ≫ (𝟙 X ⊗ (α_ Y _ _).hom)) ≫ (𝟙 X ⊗ 𝟙 Y ⊗ (λ_ _).hom), { conv_lhs { congr, skip, rw [←category.assoc] }, conv_rhs { rw [category.assoc] } }, { conv_lhs { congr, rw [monoidal_category.pentagon] }, conv_rhs { congr, rw [←monoidal_category.triangle] }, conv_rhs { rw [category.assoc] }, conv_rhs { congr, skip, congr, congr, rw [←tensor_id] }, conv_rhs { congr, skip, rw [associator_naturality] }, conv_rhs { rw [←category.assoc] } } end lemma right_unitor_product_aux_triangle (X Y : C) : ((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom) = (𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)) := by rw [←id_tensor_comp, ←monoidal_category.triangle] lemma right_unitor_product_aux_square (X Y : C) : (α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C))) = (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X Y (𝟙_ C)).hom := by rw [associator_naturality] lemma right_unitor_product_aux (X Y : C) : ((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) = ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) := begin rw ←(cancel_mono (α_ X Y (𝟙_ C)).hom), slice_lhs 2 3 { rw ←right_unitor_product_aux_square }, rw [←right_unitor_product_aux_triangle, ←right_unitor_product_aux_perimeter], end -- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> @[simp] lemma left_unitor_tensor (X Y : C) : ((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) := by rw [←tensor_left_iff, id_tensor_comp, left_unitor_product_aux] @[simp] lemma left_unitor_tensor_inv (X Y : C) : ((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) := eq_of_inv_eq_inv (by simp) @[simp] lemma right_unitor_tensor (X Y : C) : ((α_ X Y (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) = ((ρ_ (X ⊗ Y)).hom) := by rw [←tensor_right_iff, comp_tensor_id, right_unitor_product_aux] @[simp] lemma right_unitor_tensor_inv (X Y : C) : ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) = ((ρ_ (X ⊗ Y)).inv) := eq_of_inv_eq_inv (by simp) lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := begin apply (cancel_mono (α_ X' Y' Z').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [associator_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end lemma pentagon_inv (W X Y Z : C) : ((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv := begin apply category_theory.eq_of_inv_eq_inv, dsimp, rw [category.assoc, monoidal_category.pentagon] end lemma triangle_assoc_comp_left (X Y : C) : (α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y := monoidal_category.triangle C X Y @[simp] lemma triangle_assoc_comp_right (X Y : C) : (α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) := by rw [←triangle_assoc_comp_left, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma triangle_assoc_comp_right_inv (X Y : C) : ((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) := begin apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1, simp only [assoc, triangle_assoc_comp_left], rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id] end @[simp] lemma triangle_assoc_comp_left_inv (X Y : C) : ((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) := begin apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1, simp only [triangle_assoc_comp_right, assoc], rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id] end end section variables (C : Type u) [category.{v} C] [𝒞 : monoidal_category.{v} C] include 𝒞 /-- The tensor product expressed as a functor. -/ def tensor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } /-- The left-associated triple tensor product as a functor. -/ def left_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } @[simp] lemma left_assoc_tensor_obj (X) : (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl /-- The right-associated triple tensor product as a functor. -/ def right_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } @[simp] lemma right_assoc_tensor_obj (X) : (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl /-- The functor `λ X, 𝟙_ C ⊗ X`. -/ def tensor_unit_left : C ⥤ C := { obj := λ X, 𝟙_ C ⊗ X, map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f } /-- The functor `λ X, X ⊗ 𝟙_ C`. -/ def tensor_unit_right : C ⥤ C := { obj := λ X, X ⊗ 𝟙_ C, map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) } -- We can express the associator and the unitors, given componentwise above, -- as natural isomorphisms. /-- The associator as a natural isomorphism. -/ def associator_nat_iso : left_assoc_tensor C ≅ right_assoc_tensor C := nat_iso.of_components (by { intros, apply monoidal_category.associator }) (by { intros, apply monoidal_category.associator_naturality }) /-- The left unitor as a natural isomorphism. -/ def left_unitor_nat_iso : tensor_unit_left C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.left_unitor }) (by { intros, apply monoidal_category.left_unitor_naturality }) /-- The right unitor as a natural isomorphism. -/ def right_unitor_nat_iso : tensor_unit_right C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.right_unitor }) (by { intros, apply monoidal_category.right_unitor_naturality }) end end monoidal_category end category_theory
51984b99dcc6d468563a2ef8351093a6eab15e3c
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/topology/metric_space/basic.lean
ab3413a6075ae5edc29d79688df1a42ca4154377
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
76,533
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 topology.metric_space.emetric_space import topology.algebra.ordered open set filter classical topological_space noncomputable theory open_locale uniformity topological_space big_operators filter nnreal 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, 𝓟 {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 h zero_lt_two) (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) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- 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. -/ 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, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) 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) ≤ ∑ i in finset.Ico m n, 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 _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, 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) ≤ ∑ i in finset.Ico m n, d i := 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) ≤ ∑ i in finset.range n, d i := 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 zero_lt_two @[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 only [not_le] using not_congr dist_le_zero @[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 : α) : ℝ≥0 := ⟨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] } @[simp, norm_cast] lemma ennreal_coe_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--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 /--In a metric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ := ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y) /--`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 @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.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, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] 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, ← dist_nndist, 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, ← dist_nndist, 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_coe] 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_coe] 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_coe] 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 @[simp] lemma nonempty_ball (h : 0 < ε) : (ball x ε).nonempty := ⟨x, by simp [h]⟩ lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } /-- `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 /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by { rw dist_comm, refl } lemma nonempty_closed_ball (h : 0 ≤ ε) : (closed_ball x ε).nonempty := ⟨x, by simp [h]⟩ theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm] 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' (@zero_lt_two ℝ _ _)] 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⟩ @[simp] theorem ball_eq_empty_iff_nonpos : ball x ε = ∅ ↔ ε ≤ 0 := 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⟩ @[simp] theorem closed_ball_eq_empty_iff_neg : closed_ball x ε = ∅ ↔ ε < 0 := eq_empty_iff_forall_not_mem.trans ⟨λ h, not_le.1 $ λ ε0, h x $ mem_closed_ball_self ε0, λ ε0 y h, not_lt_of_le (mem_closed_ball.1 h) (lt_of_lt_of_le ε0 dist_nonneg)⟩ @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty_iff_nonpos] @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw ← metric_space.uniformity_dist.symm, refine has_basis_binfi_principal _ nonempty_Ioi, exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩) /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ 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) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := begin dsimp [uniform_continuous_on], rw (metric.uniformity_basis_dist.inf_principal (s.prod s)).tendsto_iff metric.uniformity_basis_dist, simp only [and_imp, exists_prop, prod.forall, mem_inter_eq, gt_iff_lt, mem_set_of_eq, mem_prod], finish, end 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 {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, 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 theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_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) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_sets_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] 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 tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (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 < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {X : Type*} [metric_space X] {x : X} : is_open ({x} : set X) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] end metric open metric @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated_space α := 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.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [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⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := metric.uniformity_basis_edist.eq_binfi /-- 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, 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 := metric.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 ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- 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 /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ emetric_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 m.replace_uniformity $ by { rw [uniformity_edist, metric.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 [sub_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 : order_topology ℝ := order_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [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] /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ 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) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- 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) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- 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) ≤ 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, 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 /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ 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 coe (λ x y, subtype.ext) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl section nnreal instance : metric_space ℝ≥0 := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : 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_coe.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] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, 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 filter.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)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] 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 uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) 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 : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-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 < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] 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) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] 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 [hs.closure_eq] using @mem_closure_iff _ _ s a end metric section pi open finset 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)) : ℝ≥0) : ℝ)) _ _, 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_pi_def, finset.sup_lt_iff this, edist_lt_top] }, 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, simp only [edist_nndist], norm_cast } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := subtype.eta _ _ lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := 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 ℝ≥0 using hr.le, simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from 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 ℝ≥0 using hr, simp [nndist_pi_def] end lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- 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 : is_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 ← is_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, is_compact (closed_ball x r)) lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, proper_space.compact_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- 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 → is_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, is_closed_ball.compact⟩ /-- 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 hf.1.nonempty_of_mem 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 /- It suffices to show that `α` admits a countable dense subset. -/ suffices : separable_space α, { resetI, apply emetric.second_countable_of_separable }, constructor, /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ rcases _root_.em (nonempty α) with (⟨⟨x⟩⟩|hα), swap, { exact ⟨∅, countable_empty, λ x, (hα ⟨x⟩).elim⟩ }, /- 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. -/ choose T T_sub T_count T_closure 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 _ _), use [⋃n:ℕ, T (n : ℝ), countable_Union (λ n, T_count n)], intro y, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := n_large.le, rw [T_closure] at h, exact closure_mono (subset_Union _ _) h 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 dense_t : dense t, { refine (λx, 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, dense_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*) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, 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 : is_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 : is_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, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- 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⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases 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 lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := begin cases h with C h, replace h : ∀ p : α × α, p ∈ set.prod s s → dist p.1 p.2 ∈ { d | d ≤ C }, { rintros ⟨x, y⟩ ⟨x_in, y_in⟩, exact h x y x_in y_in }, use C, suffices : ∀ p : α × α, p ∈ closure (set.prod s s) → dist p.1 p.2 ∈ { d | d ≤ C }, { rw closure_prod_eq at this, intros x y x_in y_in, exact this (x, y) (mk_mem_prod x_in y_in) }, intros p p_in, have := map_mem_closure continuous_dist p_in h, rwa (is_closed_le' C).closure_eq at this end alias bounded_closure_of_bounded ← bounded.closure /-- 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 : is_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 ← is_compact.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.is_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 _) /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, begin rintro ⟨hc, hb⟩, cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]}, rcases 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 : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, have C : is_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 z : α} /-- 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 := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le_of_forall_edist_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam 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 _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h /-- 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 := dist_le_diam_of_mem' h.ediam_ne_top hx hy /-- 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_ediam_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.subset h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h 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 := begin classical, by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.subset (subset_union_left _ _), have ht : bounded t, from H.subset (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- 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).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases 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 : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b 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 : 0 ≤ r) : 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
b9a14a19f9b3cea8dc804bcca8dca2c9c6369448
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/list/func.lean
f075c0c84e28f90ed9dd514cf640b50e97f92216
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
11,244
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ import data.nat.order.basic /-! # Lists as Functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Definitions for using lists as finite representations of finitely-supported functions with domain ℕ. These include pointwise operations on lists, as well as get and set operations. ## Notations An index notation is introduced in this file for setting a particular element of a list. With `as` as a list `m` as an index, and `a` as a new element, the notation is `as {m ↦ a}`. So, for example `[1, 3, 5] {1 ↦ 9}` would result in `[1, 9, 5]` This notation is in the locale `list.func`. -/ open list universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace list namespace func variables {a : α} variables {as as1 as2 as3 : list α} /-- Elementwise negation of a list -/ def neg [has_neg α] (as : list α) := as.map (λ a, -a) variables [inhabited α] [inhabited β] /-- Update element of a list by index. If the index is out of range, extend the list with default elements -/ @[simp] def set (a : α) : list α → ℕ → list α | (_::as) 0 := a::as | [] 0 := [a] | (h::as) (k+1) := h::(set as k) | [] (k+1) := default::(set ([] : list α) k) localized "notation (name := list.func.set) as ` {` m ` ↦ ` a `}` := list.func.set a as m" in list.func /-- Get element of a list by index. If the index is out of range, return the default element -/ @[simp] def get : ℕ → list α → α | _ [] := default | 0 (a::as) := a | (n+1) (a::as) := get n as /-- Pointwise equality of lists. If lists are different lengths, compare with the default element. -/ def equiv (as1 as2 : list α) : Prop := ∀ (m : nat), get m as1 = get m as2 /-- Pointwise operations on lists. If lists are different lengths, use the default element. -/ @[simp] def pointwise (f : α → β → γ) : list α → list β → list γ | [] [] := [] | [] (b::bs) := map (f default) (b::bs) | (a::as) [] := map (λ x, f x default) (a::as) | (a::as) (b::bs) := (f a b)::(pointwise as bs) /-- Pointwise addition on lists. If lists are different lengths, use zero. -/ def add {α : Type u} [has_zero α] [has_add α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (+) /-- Pointwise subtraction on lists. If lists are different lengths, use zero. -/ def sub {α : Type u} [has_zero α] [has_sub α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (@has_sub.sub α _) /- set -/ lemma length_set : ∀ {m : ℕ} {as : list α}, (as {m ↦ a}).length = max as.length (m+1) | 0 [] := rfl | 0 (a::as) := by {rw max_eq_left, refl, simp [nat.le_add_right]} | (m+1) [] := by simp only [set, nat.zero_max, length, @length_set m] | (m+1) (a::as) := by simp only [set, nat.max_succ_succ, length, @length_set m] @[simp] lemma get_nil {k : ℕ} : (get k [] : α) = default := by {cases k; refl} lemma get_eq_default_of_le : ∀ (k : ℕ) {as : list α}, as.length ≤ k → get k as = default | 0 [] h1 := rfl | 0 (a::as) h1 := by cases h1 | (k+1) [] h1 := rfl | (k+1) (a::as) h1 := begin apply get_eq_default_of_le k, rw ← nat.succ_le_succ_iff, apply h1, end @[simp] lemma get_set {a : α} : ∀ {k : ℕ} {as : list α}, get k (as {k ↦ a}) = a | 0 as := by {cases as; refl, } | (k+1) as := by {cases as; simp [get_set]} lemma eq_get_of_mem {a : α} : ∀ {as : list α}, a ∈ as → ∃ n : nat, ∀ d : α, a = (get n as) | [] h := by cases h | (b::as) h := begin rw mem_cons_iff at h, cases h, { existsi 0, intro d, apply h }, { cases eq_get_of_mem h with n h2, existsi (n+1), apply h2 } end lemma mem_get_of_le : ∀ {n : ℕ} {as : list α}, n < as.length → get n as ∈ as | _ [] h1 := by cases h1 | 0 (a::as) _ := or.inl rfl | (n+1) (a::as) h1 := begin apply or.inr, unfold get, apply mem_get_of_le, apply nat.lt_of_succ_lt_succ h1, end lemma mem_get_of_ne_zero : ∀ {n : ℕ} {as : list α}, get n as ≠ default → get n as ∈ as | _ [] h1 := begin exfalso, apply h1, rw get_nil end | 0 (a::as) h1 := or.inl rfl | (n+1) (a::as) h1 := begin unfold get, apply (or.inr (mem_get_of_ne_zero _)), apply h1 end lemma get_set_eq_of_ne {a : α} : ∀ {as : list α} (k : ℕ) (m : ℕ), m ≠ k → get m (as {k ↦ a}) = get m as | as 0 m h1 := by { cases m, contradiction, cases as; simp only [set, get, get_nil] } | as (k+1) m h1 := begin cases as; cases m, simp only [set, get], { have h3 : get m (nil {k ↦ a}) = default, { rw [get_set_eq_of_ne k m, get_nil], intro hc, apply h1, simp [hc] }, apply h3 }, simp only [set, get], { apply get_set_eq_of_ne k m, intro hc, apply h1, simp [hc], } end lemma get_map {f : α → β} : ∀ {n : ℕ} {as : list α}, n < as.length → get n (as.map f) = f (get n as) | _ [] h := by cases h | 0 (a::as) h := rfl | (n+1) (a::as) h1 := begin have h2 : n < length as, { rw [← nat.succ_le_iff, ← nat.lt_succ_iff], apply h1 }, apply get_map h2, end lemma get_map' {f : α → β} {n : ℕ} {as : list α} : f default = default → get n (as.map f) = f (get n as) := begin intro h1, by_cases h2 : n < as.length, { apply get_map h2, }, { rw not_lt at h2, rw [get_eq_default_of_le _ h2, get_eq_default_of_le, h1], rw [length_map], apply h2 } end lemma forall_val_of_forall_mem {as : list α} {p : α → Prop} : p default → (∀ x ∈ as, p x) → (∀ n, p (get n as)) := begin intros h1 h2 n, by_cases h3 : n < as.length, { apply h2 _ (mem_get_of_le h3) }, { rw not_lt at h3, rw get_eq_default_of_le _ h3, apply h1 } end /- equiv -/ lemma equiv_refl : equiv as as := λ k, rfl lemma equiv_symm : equiv as1 as2 → equiv as2 as1 := λ h1 k, (h1 k).symm lemma equiv_trans : equiv as1 as2 → equiv as2 as3 → equiv as1 as3 := λ h1 h2 k, eq.trans (h1 k) (h2 k) lemma equiv_of_eq : as1 = as2 → equiv as1 as2 := begin intro h1, rw h1, apply equiv_refl end lemma eq_of_equiv : ∀ {as1 as2 : list α}, as1.length = as2.length → equiv as1 as2 → as1 = as2 | [] [] h1 h2 := rfl | (_::_) [] h1 h2 := by cases h1 | [] (_::_) h1 h2 := by cases h1 | (a1::as1) (a2::as2) h1 h2 := begin congr, { apply h2 0 }, have h3 : as1.length = as2.length, { simpa [add_left_inj, add_comm, length] using h1 }, apply eq_of_equiv h3, intro m, apply h2 (m+1) end end func -- We want to drop the `inhabited` instances for a moment, -- so we close and open the namespace namespace func /- neg -/ @[simp] lemma get_neg [add_group α] {k : ℕ} {as : list α} : @get α ⟨0⟩ k (neg as) = -(@get α ⟨0⟩ k as) := by {unfold neg, rw (@get_map' α α ⟨0⟩), apply neg_zero} @[simp] lemma length_neg [has_neg α] (as : list α) : (neg as).length = as.length := by simp only [neg, length_map] variables [inhabited α] [inhabited β] /- pointwise -/ lemma nil_pointwise {f : α → β → γ} : ∀ bs : list β, pointwise f [] bs = bs.map (f default) | [] := rfl | (b::bs) := by simp only [nil_pointwise bs, pointwise, eq_self_iff_true, and_self, map] lemma pointwise_nil {f : α → β → γ} : ∀ as : list α, pointwise f as [] = as.map (λ a, f a default) | [] := rfl | (a::as) := by simp only [pointwise_nil as, pointwise, eq_self_iff_true, and_self, list.map] lemma get_pointwise [inhabited γ] {f : α → β → γ} (h1 : f default default = default) : ∀ (k : nat) (as : list α) (bs : list β), get k (pointwise f as bs) = f (get k as) (get k bs) | k [] [] := by simp only [h1, get_nil, pointwise, get] | 0 [] (b::bs) := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) [] (b::bs) := by { have : get k (map (f default) bs) = f default (get k bs), { simpa [nil_pointwise, get_nil] using (get_pointwise k [] bs) }, simpa [get, get_nil, pointwise, map] } | 0 (a::as) [] := by simp only [get_pointwise, get_nil, pointwise, get, nat.nat_zero_eq_zero, map] | (k+1) (a::as) [] := by simpa [get, get_nil, pointwise, map, pointwise_nil, get_nil] using get_pointwise k as [] | 0 (a::as) (b::bs) := by simp only [pointwise, get] | (k+1) (a::as) (b::bs) := by simp only [pointwise, get, get_pointwise k] lemma length_pointwise {f : α → β → γ} : ∀ {as : list α} {bs : list β}, (pointwise f as bs).length = max as.length bs.length | [] [] := rfl | [] (b::bs) := by simp only [pointwise, length, length_map, max_eq_right (nat.zero_le (length bs + 1))] | (a::as) [] := by simp only [pointwise, length, length_map, max_eq_left (nat.zero_le (length as + 1))] | (a::as) (b::bs) := by simp only [pointwise, length, nat.max_succ_succ, @length_pointwise as bs] end func namespace func /- add -/ @[simp] lemma get_add {α : Type u} [add_monoid α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (add xs ys) = ( @get α ⟨0⟩ k xs + @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply zero_add} @[simp] lemma length_add {α : Type u} [has_zero α] [has_add α] {xs ys : list α} : (add xs ys).length = max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_add {α : Type u} [add_monoid α] (as : list α) : add [] as = as := begin rw [add, @nil_pointwise α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr' with x, rw [zero_add, id] end @[simp] lemma add_nil {α : Type u} [add_monoid α] (as : list α) : add as [] = as := begin rw [add, @pointwise_nil α α α ⟨0⟩ ⟨0⟩], apply eq.trans _ (map_id as), congr' with x, rw [add_zero, id] end lemma map_add_map {α : Type u} [add_monoid α] (f g : α → α) {as : list α} : add (as.map f) (as.map g) = as.map (λ x, f x + g x) := begin apply @eq_of_equiv _ (⟨0⟩ : inhabited α), { rw [length_map, length_add, max_eq_left, length_map], apply le_of_eq, rw [length_map, length_map] }, intros m, rw [get_add], by_cases h : m < length as, { repeat {rw [@get_map α α ⟨0⟩ ⟨0⟩ _ _ _ h]} }, rw not_lt at h, repeat {rw [get_eq_default_of_le m]}; try {rw length_map, apply h}, apply zero_add end /- sub -/ @[simp] lemma get_sub {α : Type u} [add_group α] {k : ℕ} {xs ys : list α} : @get α ⟨0⟩ k (sub xs ys) = (@get α ⟨0⟩ k xs - @get α ⟨0⟩ k ys) := by {apply get_pointwise, apply sub_zero} @[simp] lemma length_sub [has_zero α] [has_sub α] {xs ys : list α} : (sub xs ys).length = max xs.length ys.length := @length_pointwise α α α ⟨0⟩ ⟨0⟩ _ _ _ @[simp] lemma nil_sub {α : Type} [add_group α] (as : list α) : sub [] as = neg as := begin rw [sub, nil_pointwise], congr' with x, rw [zero_sub] end @[simp] lemma sub_nil {α : Type} [add_group α] (as : list α) : sub as [] = as := begin rw [sub, pointwise_nil], apply eq.trans _ (map_id as), congr' with x, rw [sub_zero, id] end end func end list
fae4888634901f6533eb774b2484aba01b1b55d9
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/measure_theory/measurable_space.lean
dce8f73f0f334b7168c62250a0f9afe2b211e60a
[ "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
44,003
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 Measurable spaces -- σ-algberas -/ import data.set.disjointed order.galois_connection data.set.countable /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set α form a complete lattice. Here we order σ-algebras by writing m₁ ≤ m₂ if every set which is m₁-measurable is also m₂-measurable (that is, m₁ is a subset of m₂). In particular, any collection of subsets of α generates a smallest σ-algebra which contains all of them. A function f : α → β induces a Galois connection between the lattices of σ-algebras on α and β. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose s is a collection of subsets of α such that the intersection of two members of s belongs to s whenever it is nonempty. Let m be the σ-algebra generated by s. In order to check that a predicate C holds on every member of m, it suffices to check that C holds on the members of s and that C is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function f : α → β between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ local attribute [instance] classical.prop_decidable open set encodable open_locale classical universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort x} {s t u : set α} structure measurable_space (α : Type u) := (is_measurable : set α → Prop) (is_measurable_empty : is_measurable ∅) (is_measurable_compl : ∀s, is_measurable s → is_measurable (- s)) (is_measurable_Union : ∀f:ℕ → set α, (∀i, is_measurable (f i)) → is_measurable (⋃i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable (-s) := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.compl_iff : is_measurable (-s) ↔ is_measurable s := ⟨λ h, by simpa using h.compl, is_measurable.compl⟩ lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma encodable.Union_decode2 {α} [encodable β] (f : β → set α) : (⋃ b, f b) = ⋃ (i : ℕ) (b ∈ decode2 β i), f b := ext $ by simp [mem_decode2, exists_swap] @[elab_as_eliminator] lemma encodable.Union_decode2_cases {α} [encodable β] {f : β → set α} {C : set α → Prop} (H0 : C ∅) (H1 : ∀ b, C (f b)) {n} : C (⋃ b ∈ decode2 β n, f b) := match decode2 β n with | none := by simp; apply H0 | (some b) := by convert H1 b; simp [ext_iff] end lemma is_measurable.Union [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by rw encodable.Union_decode2; exact ‹measurable_space α›.is_measurable_Union (λ n, ⋃ b ∈ decode2 β n, f b) (λ n, encodable.Union_decode2_cases is_measurable.empty h) lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋃b∈s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋃₀ s) := by rw sUnion_eq_bUnion; exact is_measurable.bUnion hs h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋃b, f b) := by by_cases p; simp [h, hf, is_measurable.empty] lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := is_measurable.compl_iff.1 $ by rw compl_Inter; exact is_measurable.Union (λ b, (h b).compl) lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀b∈s, is_measurable (f b)) : is_measurable (⋂b∈s, f b) := is_measurable.compl_iff.1 $ by rw compl_bInter; exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀t∈s, is_measurable t) : is_measurable (⋂₀ s) := by rw sInter_eq_bInter; exact is_measurable.bInter hs h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀b, is_measurable (f b)) : is_measurable (⋂b, f b) := by by_cases p; simp [h, hf, is_measurable.univ] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by rw union_eq_Union; exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by rw inter_eq_compl_compl_union_compl; exact (h₁.compl.union h₂.compl).compl lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl lemma is_measurable.sub {s₁ s₂ : set α} : is_measurable s₁ → is_measurable s₂ → is_measurable (s₁ - s₂) := is_measurable.diff lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ end @[ext] lemma measurable_space.ext : ∀{m₁ m₂ : measurable_space α}, (∀s:set α, m₁.is_measurable s ↔ m₂.is_measurable s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λm₁ m₂, m₁.is_measurable ≤ m₂.is_measurable, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀u∈s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀s, generate_measurable s → generate_measurable (-s) | union : ∀f:ℕ → set α, (∀n, generate_measurable (f n)) → generate_measurable (⋃i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable := generate_measurable s, is_measurable_empty := generate_measurable.empty s, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀t∈s, m.is_measurable t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} {m : measurable_space α} : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable t} = g) : measurable_space α := { is_measurable := λs, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by rw [← hs] {occs := occurrences.pos [1] }; refl def gi_generate_from : galois_insertion (@generate_from α) (λm, {t | @is_measurable α m t}) := { gc := assume s m, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λg hg, measurable_space.mk_of_closure g $ le_antisymm hg $ generate_from_le_iff.1 $ le_refl _, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable := λs, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (assume s, s.symm ▸ @is_measurable_empty _ ⊥) (assume s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂m∈ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λm, {s | @is_measurable _ m s }) (infi m) ↔ _, by rw (@gi_generate_from α).gc.u_infi; simp; refl theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable ∪ m₂.is_measurable) s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable (⋃₀ (measurable_space.is_measurable '' ms)) s := begin change @is_measurable _ (generate_from _) _ ↔ _, dsimp [generate_from], rw (show (⨆ (b : measurable_space α) (H : b ∈ ms), set_of (is_measurable b)) = (⋃₀(is_measurable '' ms)), { ext, simp only [exists_prop, mem_Union, sUnion_image, mem_set_of_eq], refl, }) end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable (⋃i, (m i).is_measurable) s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable := λs, m.is_measurable $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by rw [preimage_Union]; exact m.is_measurable_Union _ hf } @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable := λs, ∃s', m.is_measurable s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨-s', m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃i, s' i, m.is_measurable_Union _ (λi, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥:measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} :(⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤:measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [m₁ : measurable_space α] [m₂ : measurable_space β] (f : α → β) : Prop := m₂ ≤ m₁.map f lemma measurable_id [measurable_space α] : measurable (@id α) := le_refl _ lemma measurable.preimage [measurable_space α] [measurable_space β] {f : α → β} (hf : measurable f) {s : set β} : is_measurable s → is_measurable (f ⁻¹' s) := hf _ lemma measurable.comp [measurable_space α] [measurable_space β] [measurable_space γ] {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := le_trans hg $ map_mono hf lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀t∈s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := generate_from_le h lemma measurable.if [measurable_space α] [measurable_space β] {p : α → Prop} {h : decidable_pred p} {f g : α → β} (hp : is_measurable {a | p a}) (hf : measurable f) (hg : measurable g) : measurable (λa, if p a then f a else g a) := λ s hs, show is_measurable {a | (if p a then f a else g a) ∈ s}, begin convert (hp.inter $ hf s hs).union (hp.compl.inter $ hg s hs), exact ext (λ a, by by_cases p a ; { rw mem_def, simp [h] }) end lemma measurable_const {α β} [measurable_space α] [measurable_space β] {a : α} : measurable (λb:β, a) := assume s hs, show is_measurable {b : β | a ∈ s}, from classical.by_cases (assume h : a ∈ s, by simp [h]; from is_measurable.univ) (assume h : a ∉ s, by simp [h]; from is_measurable.empty) lemma measurable_zero {α β} [measurable_space α] [has_zero α] [measurable_space β] : measurable (λb:β, (0:α)) := measurable_const end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := have f = (λu, f ()) := funext $ assume ⟨⟩, rfl, by rw this; exact measurable_const section nat lemma measurable_from_nat [measurable_space α] {f : ℕ → α} : measurable f := assume s hs, show is_measurable {n : ℕ | f n ∈ s}, from trivial lemma measurable_to_nat [measurable_space α] {f : α → ℕ} : (∀ k, is_measurable {x | f x = k}) → measurable f := begin assume h s hs, show is_measurable {x | f x ∈ s}, have : {x | f x ∈ s} = ⋃ (n ∈ s), {x | f x = n}, { ext, simp }, rw this, simp [is_measurable.Union, is_measurable.Union_Prop, h] end lemma measurable_find_greatest [measurable_space α] {p : ℕ → α → Prop} : ∀ {N}, (∀ k ≤ N, is_measurable {x | nat.find_greatest (λ n, p n x) N = k}) → measurable (λ x, nat.find_greatest (λ n, p n x) N) | 0 := assume h s hs, show is_measurable {x : α | (nat.find_greatest (λ n, p n x) 0) ∈ s}, begin by_cases h : 0 ∈ s, { convert is_measurable.univ, simp only [nat.find_greatest_zero, h] }, { convert is_measurable.empty, simp only [nat.find_greatest_zero, h], refl } end | (n + 1) := assume h, begin apply measurable_to_nat, assume k, by_cases hk : k ≤ n + 1, { exact h k hk }, { have := is_measurable.empty, rw ← set_of_false at this, convert this, funext, rw eq_false, assume h, rw ← h at hk, have := nat.find_greatest_le, contradiction } end end nat section subtype instance {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap subtype.val lemma measurable.subtype_val [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λa:α, (f a).val) := measurable.comp (measurable_space.comap_le_iff_le_map.mp (le_refl _)) hf lemma measurable.subtype_mk [measurable_space α] [measurable_space β] {p : β → Prop} {f : α → subtype p} (hf : measurable (λa, (f a).val)) : measurable f := measurable_space.comap_le_iff_le_map.mpr $ by rw [measurable_space.map_comp]; exact hf lemma is_measurable_subtype_image [measurable_space α] {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, image_preimage_eq_inter_range, range_coe_subtype], exact is_measurable.inter hu hs end lemma measurable_of_measurable_union_cover [measurable_space α] [measurable_space β] {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λa:s, f a)) (hd : measurable (λa:t, f a)) : measurable f := assume u (hu : is_measurable u), show is_measurable (f ⁻¹' u), from begin rw show f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), by rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, range_coe_subtype, range_coe_subtype, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], exact is_measurable.union (is_measurable_subtype_image hs (hc _ hu)) (is_measurable_subtype_image ht (hd _ hu)) end end subtype section prod instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable.fst [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).1) := measurable.comp (measurable_space.comap_le_iff_le_map.mp le_sup_left) hf lemma measurable.snd [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf : measurable f) : measurable (λa:α, (f a).2) := measurable.comp (measurable_space.comap_le_iff_le_map.mp le_sup_right) hf lemma measurable.prod [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β × γ} (hf₁ : measurable (λa, (f a).1)) (hf₂ : measurable (λa, (f a).2)) : measurable f := sup_le (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₁) (by rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp]; exact hf₂) lemma measurable.prod_mk [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λa:α, (f a, g a)) := measurable.prod hf hg lemma is_measurable_set_prod [measurable_space α] [measurable_space β] {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (set.prod s t) := is_measurable.inter (measurable.fst measurable_id _ hs) (measurable.snd measurable_id _ ht) end prod section pi instance measurable_space.pi {α : Type u} {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (Πa, β a) := ⨆a, (m a).comap (λb, b a) lemma measurable_pi_apply {α : Type u} {β : α → Type v} [Πa, measurable_space (β a)] (a : α) : measurable (λf:Πa, β a, f a) := measurable_space.comap_le_iff_le_map.1 $ le_supr _ a lemma measurable_pi_lambda {α : Type u} {β : α → Type v} {γ : Type w} [Πa, measurable_space (β a)] [measurable_space γ] (f : γ → Πa, β a) (hf : ∀a, measurable (λc, f c a)) : measurable f := supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) end pi instance [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_inl : measurable (@sum.inl α β) := inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable_space.comap_le_iff_le_map.1 $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable_sum_rec {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : @measurable (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := measurable_sum hf hg lemma is_measurable_inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inl.inj), have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by rw [this]; exact is_measurable.empty⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable_inl_image is_measurable.univ lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by rw [this]; exact is_measurable.empty, show is_measurable (sum.inr ⁻¹' _), by rwa [preimage_image_eq]; exact (assume a b, sum.inr.inj)⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by rw [← image_univ]; exact is_measurable_inr_image is_measurable.univ end sum instance {β : α → Type v} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv instance (α β) [measurable_space α] [measurable_space β] : has_coe_to_fun (measurable_equiv α β) := ⟨λ_, α → β, λe, e.to_equiv⟩ lemma coe_eq {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } def trans [measurable_space α] [measurable_space β] [measurable_space γ] (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } lemma trans_to_equiv {α β} [measurable_space α] [measurable_space β] [measurable_space γ] (e : measurable_equiv α β) (f : measurable_equiv β γ) : (e.trans f).to_equiv = e.to_equiv.trans f.to_equiv := rfl def symm [measurable_space α] [measurable_space β] (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } lemma symm_to_equiv {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : e.symm.to_equiv = e.to_equiv.symm := rfl protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by unfreezeI; subst h; subst hi; exact measurable_id, measurable_inv_fun := by unfreezeI; subst h; subst hi; exact measurable_id } protected lemma measurable {α β} [measurable_space α] [measurable_space β] (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun protected lemma measurable_coe_iff {α β γ} [measurable_space α] [measurable_space β] [measurable_space γ] {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λh, h.comp e.measurable) def prod_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := measurable.prod_mk (ab.measurable_to_fun.comp (measurable.fst measurable_id)) (cd.measurable_to_fun.comp (measurable.snd measurable_id)), measurable_inv_fun := measurable.prod_mk (ab.measurable_inv_fun.comp (measurable.fst measurable_id)) (cd.measurable_inv_fun.comp (measurable.snd measurable_id)) } def prod_comm [measurable_space α] [measurable_space β] : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id), measurable_inv_fun := measurable.prod_mk (measurable.snd measurable_id) (measurable.fst measurable_id) } def sum_congr [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } def set.prod [measurable_space α] [measurable_space β] (s : set α) (t : set β) : measurable_equiv (set.prod s t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable.prod_mk (measurable.subtype_mk $ measurable.fst $ measurable.subtype_val $ measurable_id) (measurable.subtype_mk $ measurable.snd $ measurable.subtype_val $ measurable_id), measurable_inv_fun := measurable.subtype_mk $ measurable.prod_mk (measurable.subtype_val $ measurable.fst $ measurable_id) (measurable.subtype_val $ measurable.snd $ measurable_id) } def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable.subtype_val measurable_id, measurable_inv_fun := measurable.subtype_mk measurable_id } def set.singleton [measurable_space α] (a:α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable.subtype_mk $ show measurable (λu:unit, a), from measurable_const } noncomputable def set.image [measurable_space α] [measurable_space β] (f : α → β) (s : set α) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := begin have : measurable (λa:s, f a) := hfm.comp (measurable.subtype_val measurable_id), refine measurable.subtype_mk _, convert this, ext ⟨a, h⟩, refl end, measurable_inv_fun := assume t ⟨u, (hu : is_measurable u), eq⟩, begin clear_, subst eq, show is_measurable {x : f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u}, have : ∀(a ∈ s) (h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λa ha h, (classical.some_spec h).2, rw show {x:f '' s | ((equiv.set.image f s hf).inv_fun x).val ∈ u} = subtype.val ⁻¹' (f '' u), by ext ⟨b, a, hbs, rfl⟩; simp [equiv.set.image, equiv.set.image_of_inj_on, hf, this _ hbs], exact (measurable.subtype_val measurable_id) (f '' u) (hfi u hu) end } noncomputable def set.range [measurable_space α] [measurable_space β] (f : α → β) (hf : function.injective f) (hfm : measurable f) (hfi : ∀s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) def set.range_inl [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λa, ⟨sum.inl a, a, rfl⟩, left_inv := assume ⟨ab, a, eq⟩, by subst eq; refl, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inl_image hs, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } def set.range_inr [measurable_space α] [measurable_space β] : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by cases p; contradiction, this.elim end, inv_fun := λb, ⟨sum.inr b, b, rfl⟩, left_inv := assume ⟨ab, b, eq⟩, by subst eq; refl, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_set_prod is_measurable_range_inl is_measurable.univ) (is_measurable_set_prod is_measurable_range_inr is_measurable.univ) (assume ⟨ab, c⟩ s, by cases ab; simp [set.prod_eq]) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := begin refine measurable_sum _ _, { convert measurable.prod_mk (measurable_inl.comp (measurable.fst measurable_id)) (measurable.snd measurable_id), ext ⟨a, c⟩; refl }, { convert measurable.prod_mk (measurable_inr.comp (measurable.fst measurable_id)) (measurable.snd measurable_id), ext ⟨b, c⟩; refl } end } def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv namespace measurable_equiv end measurable_equiv namespace measurable_space /-- Dynkin systems The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀{a}, has a → has (-a)) (has_Union_nat : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, has (f i)) → has (⋃i, f i)) theorem Union_decode2_disjoint_on {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) : pairwise (disjoint on λ i, ⋃ b ∈ decode2 β i, f b) := begin rintro i j ij x ⟨h₁, h₂⟩, revert h₁ h₂, simp, intros b₁ e₁ h₁ b₂ e₂ h₂, refine hd _ _ _ ⟨h₁, h₂⟩, cases encodable.mem_decode2.1 e₁, cases encodable.mem_decode2.1 e₂, exact mt (congr_arg _) ij end namespace dynkin_system @[ext] lemma ext : ∀{d₁ d₂ : dynkin_system α}, (∀s:set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has (-a) ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀i, d.has (f i)) : d.has (⋃i, f i) := by rw encodable.Union_decode2; exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by rw union_eq_Union; exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := d.has_compl_iff.1 begin simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λm₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable, has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀t∈s, generate_has t | empty : generate_has ∅ | compl : ∀{a}, generate_has a → generate_has (-a) | Union : ∀{f:ℕ → set α}, pairwise (disjoint on f) → (∀i, generate_has (f i)) → generate_has (⋃i, f i) def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty s, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } instance : inhabited (dynkin_system α) := ⟨generate univ⟩ def to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λt, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have -t ∩ s = (- (t ∩ s)) \ -s, from set.ext $ assume x, by by_cases x ∈ s; simp [h], by rw [this]; from d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _), has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀t∈s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_inter {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty _) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ lemma generate_from_eq {s : set (set α)} (hs : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by rw [of_measurable_space_to_measurable_space]; from (generate_le _ $ assume t ht, is_measurable_generate_from ht)) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} {m : measurable_space α} (h_eq : m = generate_from s) (h_inter : ∀t₁ t₂ : set α, t₁ ∈ s → t₂ ∈ s → (t₁ ∩ t₂).nonempty → t₁ ∩ t₂ ∈ s) (h_empty : C ∅) (h_basic : ∀t∈s, C t) (h_compl : ∀t, m.is_measurable t → C t → C (- t)) (h_union : ∀f:ℕ → set α, (∀i j, i ≠ j → f i ∩ f j ⊆ ∅) → (∀i, m.is_measurable (f i)) → (∀i, C (f i)) → C (⋃i, f i)) : ∀{t}, m.is_measurable t → C t := have eq : m.is_measurable = dynkin_system.generate_has s, by rw [h_eq, dynkin_system.generate_from_eq h_inter]; refl, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by rw [eq]; exact ht) (assume f hf ht, h_union f hf $ assume i, by rw [eq]; exact ht _) end measurable_space
2e9788b5a815501eb84e2755a5a682db268e0cf2
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/thursday/afternoon/category_theory/exercise1.lean
5e0fb10a7518baa52afdaac5526b6f021597bb33
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
986
lean
import category_theory.isomorphism import category_theory.yoneda open category_theory open opposite variables {C : Type*} [category C] /-! Hint 1: `yoneda` is set up so that `(yoneda.obj X).obj (op Y) = (Y ⟶ X)` (we need to write `op Y` to explicitly move `Y` to the opposite category). -/ /-! Hint 2: If you have a natural isomorphism `α : F ≅ G`, you can access * the forward natural transformation as `α.hom` * the backwards natural transformation as `α.inv` * the component at `X`, as an isomorphism `F.obj X ≅ G.obj X` as `α.app X`. -/ def iso_of_hom_iso (X Y : C) (h : yoneda.obj X ≅ yoneda.obj Y) : X ≅ Y := -- sorry { hom := (h.app (op X)).hom (𝟙 X), inv := (h.symm.app (op Y)).hom (𝟙 Y), } -- sorry /-! There are some further hints in `src/hints/thursday/afternoon/category_theory/exercise1/` -/ -- omit /-! Notice that we didn't need to provide proofs for the fields `hom_inv_id'` and `inv_hom_id'`. These were filled in by automation. -/ -- omit
41a78c5b817648d438b5b1c7c008e3f72e60a96c
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sets/closeds.lean
0c1f1b10fced68c348da14bd0520856fd6390ea0
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,969
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, Yaël Dillies -/ import topology.sets.opens /-! # Closed sets We define a few types of closed sets in a topological space. ## Main Definitions For a topological space `α`, * `closeds α`: The type of closed sets. * `clopens α`: The type of clopen sets. -/ open set variables {α β : Type*} [topological_space α] [topological_space β] namespace topological_space /-! ### Closed sets -/ /-- The type of closed subsets of a topological space. -/ structure closeds (α : Type*) [topological_space α] := (carrier : set α) (closed' : is_closed carrier) namespace closeds variables {α} instance : set_like (closeds α) α := { coe := closeds.carrier, coe_injective' := λ s t h, by { cases s, cases t, congr' } } lemma closed (s : closeds α) : is_closed (s : set α) := s.closed' @[ext] protected lemma ext {s t : closeds α} (h : (s : set α) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl instance : has_sup (closeds α) := ⟨λ s t, ⟨s ∪ t, s.closed.union t.closed⟩⟩ instance : has_inf (closeds α) := ⟨λ s t, ⟨s ∩ t, s.closed.inter t.closed⟩⟩ instance : has_top (closeds α) := ⟨⟨univ, is_closed_univ⟩⟩ instance : has_bot (closeds α) := ⟨⟨∅, is_closed_empty⟩⟩ instance : distrib_lattice (closeds α) := set_like.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl) instance : bounded_order (closeds α) := bounded_order.lift (coe : _ → set α) (λ _ _, id) rfl rfl /-- The type of closed sets is inhabited, with default element the empty set. -/ instance : inhabited (closeds α) := ⟨⊥⟩ @[simp] lemma coe_sup (s t : closeds α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl @[simp] lemma coe_inf (s t : closeds α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl @[simp] lemma coe_top : (↑(⊤ : closeds α) : set α) = univ := rfl @[simp] lemma coe_bot : (↑(⊥ : closeds α) : set α) = ∅ := rfl end closeds /-! ### Clopen sets -/ /-- The type of clopen sets of a topological space. -/ structure clopens (α : Type*) [topological_space α] := (carrier : set α) (clopen' : is_clopen carrier) namespace clopens instance : set_like (clopens α) α := { coe := λ s, s.carrier, coe_injective' := λ s t h, by { cases s, cases t, congr' } } lemma clopen (s : clopens α) : is_clopen (s : set α) := s.clopen' /-- Reinterpret a compact open as an open. -/ @[simps] def to_opens (s : clopens α) : opens α := ⟨s, s.clopen.is_open⟩ @[ext] protected lemma ext {s t : clopens α} (h : (s : set α) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl instance : has_sup (clopens α) := ⟨λ s t, ⟨s ∪ t, s.clopen.union t.clopen⟩⟩ instance : has_inf (clopens α) := ⟨λ s t, ⟨s ∩ t, s.clopen.inter t.clopen⟩⟩ instance : has_top (clopens α) := ⟨⟨⊤, is_clopen_univ⟩⟩ instance : has_bot (clopens α) := ⟨⟨⊥, is_clopen_empty⟩⟩ instance : has_sdiff (clopens α) := ⟨λ s t, ⟨s \ t, s.clopen.diff t.clopen⟩⟩ instance : has_compl (clopens α) := ⟨λ s, ⟨sᶜ, s.clopen.compl⟩⟩ instance : boolean_algebra (clopens α) := set_like.coe_injective.boolean_algebra _ (λ _ _, rfl) (λ _ _, rfl) rfl rfl (λ _, rfl) (λ _ _, rfl) @[simp] lemma coe_sup (s t : clopens α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl @[simp] lemma coe_inf (s t : clopens α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl @[simp] lemma coe_top : (↑(⊤ : clopens α) : set α) = univ := rfl @[simp] lemma coe_bot : (↑(⊥ : clopens α) : set α) = ∅ := rfl @[simp] lemma coe_sdiff (s t : clopens α) : (↑(s \ t) : set α) = s \ t := rfl @[simp] lemma coe_compl (s : clopens α) : (↑sᶜ : set α) = sᶜ := rfl instance : inhabited (clopens α) := ⟨⊥⟩ end clopens end topological_space
36f02f715656756b72685c4dff40fd1172aae4af
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.28.lean
9897d0f04e489598b666a8c8a5d3812337d05f5a
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
383
lean
/- page 86 -/ import standard namespace hide inductive nat : Type := | zero : nat | succ : nat → nat namespace nat definition add (m n : nat) : nat := nat.rec_on n m (fun n add_m_n, succ add_m_n) -- BEGIN notation 0 := zero infix `+` := add theorem add_zero (m : nat) : m + 0 = m := rfl theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl -- END end nat end hide
5ac91bd9b236fda1610478995e9a6bafc9b001b1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Int.lean
55959e95bd895a564acdd67b11addd015dca80cd
[ "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
199
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.Data.Int.Basic
e145867f3febf48d8244805b0d094d238e621e4f
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/1093.lean
2a073470be1e2b6f12dc119b978acdc8172692cf
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
298
lean
open tactic nat constant zero_add (a : nat) : 0 + a = a constant le.refl (a : nat) : a ≤ a attribute zero_add [simp] example (a : nat) : 0 + a ≤ a := by do simp, trace_state, mk_const `le.refl >>= apply example (a : nat) : 0 + a ≥ a := by do simp, trace_state, mk_const `le.refl >>= apply
008b2944490d66efc3e06676cd5166c2e742ee75
42610cc2e5db9c90269470365e6056df0122eaa0
/library/data/real/complete.lean
a7b92cee4aa4952cd6f152bf2453e4c61f1a2d5c
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
32,224
lean
/- Copyright (c) 2015 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis The real numbers, constructed as equivalence classes of Cauchy sequences of rationals. This construction follows Bishop and Bridges (1985). At this point, we no longer proceed constructively: this file makes heavy use of decidability, excluded middle, and Hilbert choice. Two sets of definitions of Cauchy sequences, convergence, etc are available in the libray, one with rates and one without. The definitions here, with rates, are amenable to be used constructively if and when that development takes place. The second set of definitions available in /library/theories/analysis/metric_space.lean are the usual classical ones. Here, we show that ℝ is complete. The proofs of Cauchy completeness and the supremum property are independent of each other. -/ import data.real.basic data.real.order data.real.division data.rat data.nat data.pnat open rat local postfix ⁻¹ := pnat.inv open eq.ops pnat classical namespace rat_seq theorem rat_approx {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, ∃ N : ℕ+, ∀ m : ℕ+, m ≥ N → abs (s m - q) ≤ n⁻¹ := begin intro n, existsi (s (2 * n)), existsi 2 * n, intro m Hm, apply le.trans, apply H, rewrite -(pnat.add_halves n), apply add_le_add_right, apply inv_ge_of_le Hm end theorem rat_approx_seq {s : seq} (H : regular s) : ∀ n : ℕ+, ∃ q : ℚ, s_le (s_abs (sadd s (sneg (const q)))) (const n⁻¹) := begin intro m, rewrite ↑s_le, cases rat_approx H m with [q, Hq], cases Hq with [N, HN], existsi q, apply nonneg_of_bdd_within, repeat (apply reg_add_reg | apply reg_neg_reg | apply abs_reg_of_reg | apply const_reg | assumption), intro n, existsi N, intro p Hp, rewrite ↑[sadd, sneg, s_abs, const], apply le.trans, rotate 1, rewrite -sub_eq_add_neg, apply sub_le_sub_left, apply HN, apply pnat.le_trans, apply Hp, rewrite -*pnat.mul_assoc, apply pnat.mul_le_mul_left, rewrite [sub_self, -neg_zero], apply neg_le_neg, apply rat.le_of_lt, apply pnat.inv_pos end theorem r_rat_approx (s : reg_seq) : ∀ n : ℕ+, ∃ q : ℚ, r_le (r_abs (radd s (rneg (r_const q)))) (r_const n⁻¹) := rat_approx_seq (reg_seq.is_reg s) theorem const_bound {s : seq} (Hs : regular s) (n : ℕ+) : s_le (s_abs (sadd s (sneg (const (s n))))) (const n⁻¹) := begin rewrite ↑[s_le, nonneg, s_abs, sadd, sneg, const], intro m, rewrite -sub_eq_add_neg, apply iff.mp !le_add_iff_neg_le_sub_left, apply le.trans, apply Hs, apply add_le_add_right, rewrite -*pnat.mul_assoc, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem abs_const (a : ℚ) : const (abs a) ≡ s_abs (const a) := by apply equiv.refl theorem r_abs_const (a : ℚ) : requiv (r_const (abs a) ) (r_abs (r_const a)) := abs_const a theorem equiv_abs_of_ge_zero {s : seq} (Hs : regular s) (Hz : s_le zero s) : s_abs s ≡ s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply Hs, intro j, rewrite ↑s_abs, let Hz' := s_nonneg_of_ge_zero Hs Hz, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], rewrite [abs_of_nonneg Hpos, sub_self, abs_zero], apply rat.le_of_lt, apply pnat.inv_pos, let Hneg' := lt_of_not_ge Hneg, have Hsn : -s n - s n > 0, from add_pos (neg_pos_of_neg Hneg') (neg_pos_of_neg Hneg'), rewrite [abs_of_neg Hneg', abs_of_pos Hsn], apply le.trans, apply add_le_add, repeat (apply neg_le_neg; apply Hz'), rewrite neg_neg, apply le.trans, apply add_le_add, repeat (apply inv_ge_of_le; apply Hn), krewrite pnat.add_halves, end theorem equiv_neg_abs_of_le_zero {s : seq} (Hs : regular s) (Hz : s_le s zero) : s_abs s ≡ sneg s := begin apply eq_of_bdd, apply abs_reg_of_reg Hs, apply reg_neg_reg Hs, intro j, rewrite [↑s_abs, ↑s_le at Hz], have Hz' : nonneg (sneg s), begin apply nonneg_of_nonneg_equiv, rotate 3, apply Hz, rotate 2, apply s_zero_add, repeat (apply Hs | apply zero_is_reg | apply reg_neg_reg | apply reg_add_reg) end, existsi 2 * j, intro n Hn, cases em (s n ≥ 0) with [Hpos, Hneg], have Hsn : s n + s n ≥ 0, from add_nonneg Hpos Hpos, rewrite [abs_of_nonneg Hpos, ↑sneg, sub_neg_eq_add, abs_of_nonneg Hsn], rewrite [↑nonneg at Hz', ↑sneg at Hz'], apply le.trans, apply add_le_add, repeat apply (le_of_neg_le_neg !Hz'), apply le.trans, apply add_le_add, repeat (apply inv_ge_of_le; apply Hn), krewrite pnat.add_halves, let Hneg' := lt_of_not_ge Hneg, rewrite [abs_of_neg Hneg', ↑sneg, sub_neg_eq_add, neg_add_eq_sub, sub_self, abs_zero], apply rat.le_of_lt, apply pnat.inv_pos end theorem r_equiv_abs_of_ge_zero {s : reg_seq} (Hz : r_le r_zero s) : requiv (r_abs s) s := equiv_abs_of_ge_zero (reg_seq.is_reg s) Hz theorem r_equiv_neg_abs_of_le_zero {s : reg_seq} (Hz : r_le s r_zero) : requiv (r_abs s) (-s) := equiv_neg_abs_of_le_zero (reg_seq.is_reg s) Hz end rat_seq namespace real open [class] rat_seq private theorem rewrite_helper9 (a b c : ℝ) : b - c = (b - a) - (c - a) := by rewrite [-sub_add_eq_sub_sub_swap, sub_add_cancel] private theorem rewrite_helper10 (a b c d : ℝ) : c - d = (c - a) + (a - b) + (b - d) := by rewrite [*add_sub, *sub_add_cancel] noncomputable definition rep (x : ℝ) : rat_seq.reg_seq := some (quot.exists_rep x) definition re_abs (x : ℝ) : ℝ := quot.lift_on x (λ a, quot.mk (rat_seq.r_abs a)) (take a b Hab, quot.sound (rat_seq.r_abs_well_defined Hab)) theorem r_abs_nonneg {x : ℝ} : zero ≤ x → re_abs x = x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_abs_of_ge_zero Ha)) theorem r_abs_nonpos {x : ℝ} : x ≤ zero → re_abs x = -x := quot.induction_on x (λ a Ha, quot.sound (rat_seq.r_equiv_neg_abs_of_le_zero Ha)) private theorem abs_const' (a : ℚ) : of_rat (abs a) = re_abs (of_rat a) := quot.sound (rat_seq.r_abs_const a) private theorem re_abs_is_abs : re_abs = abs := funext (begin intro x, apply eq.symm, cases em (zero ≤ x) with [Hor1, Hor2], rewrite [abs_of_nonneg Hor1, r_abs_nonneg Hor1], have Hor2' : x ≤ zero, from le_of_lt (lt_of_not_ge Hor2), rewrite [abs_of_neg (lt_of_not_ge Hor2), r_abs_nonpos Hor2'] end) theorem abs_const (a : ℚ) : of_rat (abs a) = abs (of_rat a) := by rewrite -re_abs_is_abs private theorem rat_approx' (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, re_abs (x - of_rat q) ≤ of_rat n⁻¹ := quot.induction_on x (λ s n, rat_seq.r_rat_approx s n) theorem rat_approx (x : ℝ) : ∀ n : ℕ+, ∃ q : ℚ, abs (x - of_rat q) ≤ of_rat n⁻¹ := by rewrite -re_abs_is_abs; apply rat_approx' noncomputable definition approx (x : ℝ) (n : ℕ+) := some (rat_approx x n) theorem approx_spec (x : ℝ) (n : ℕ+) : abs (x - (of_rat (approx x n))) ≤ of_rat n⁻¹ := some_spec (rat_approx x n) theorem approx_spec' (x : ℝ) (n : ℕ+) : abs ((of_rat (approx x n)) - x) ≤ of_rat n⁻¹ := by rewrite abs_sub; apply approx_spec theorem ex_rat_pos_lower_bound_of_pos {x : ℝ} (H : x > 0) : ∃ q : ℚ, q > 0 ∧ of_rat q ≤ x := if Hgeo : x ≥ 1 then exists.intro 1 (and.intro zero_lt_one Hgeo) else have Hdp : 1 / x > 0, from one_div_pos_of_pos H, begin cases rat_approx (1 / x) 2 with q Hq, have Hqp : q > 0, begin apply lt_of_not_ge, intro Hq2, note Hx' := one_div_lt_one_div_of_lt H (lt_of_not_ge Hgeo), rewrite div_one at Hx', have Horqn : of_rat q ≤ 0, begin krewrite -of_rat_zero, apply of_rat_le_of_rat_of_le Hq2 end, have Hgt1 : 1 / x - of_rat q > 1, from calc 1 / x - of_rat q = 1 / x + -of_rat q : sub_eq_add_neg ... ≥ 1 / x : le_add_of_nonneg_right (neg_nonneg_of_nonpos Horqn) ... > 1 : Hx', have Hpos : 1 / x - of_rat q > 0, from gt.trans Hgt1 zero_lt_one, rewrite [abs_of_pos Hpos at Hq], apply not_le_of_gt Hgt1, apply le.trans, apply Hq, krewrite -of_rat_one, apply of_rat_le_of_rat_of_le, apply inv_le_one end, existsi 1 / (2⁻¹ + q), split, apply div_pos_of_pos_of_pos, exact zero_lt_one, apply add_pos, apply pnat.inv_pos, exact Hqp, note Hle2 := sub_le_of_abs_sub_le_right Hq, note Hle3 := le_add_of_sub_left_le Hle2, note Hle4 := one_div_le_of_one_div_le_of_pos H Hle3, rewrite [of_rat_divide, of_rat_add], exact Hle4 end theorem ex_rat_neg_upper_bound_of_neg {x : ℝ} (H : x < 0) : ∃ q : ℚ, q < 0 ∧ x ≤ of_rat q := have H' : -x > 0, from neg_pos_of_neg H, obtain q [Hq1 Hq2], from ex_rat_pos_lower_bound_of_pos H', exists.intro (-q) (and.intro (neg_neg_of_pos Hq1) (le_neg_of_le_neg Hq2)) notation `r_seq` := ℕ+ → ℝ noncomputable definition converges_to_with_rate (X : r_seq) (a : ℝ) (N : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ n : ℕ+, n ≥ N k → abs (X n - a) ≤ of_rat k⁻¹ noncomputable definition cauchy_with_rate (X : r_seq) (M : ℕ+ → ℕ+) := ∀ k : ℕ+, ∀ m n : ℕ+, m ≥ M k → n ≥ M k → abs (X m - X n) ≤ of_rat k⁻¹ theorem cauchy_with_rate_of_converges_to_with_rate {X : r_seq} {a : ℝ} {N : ℕ+ → ℕ+} (Hc : converges_to_with_rate X a N) : cauchy_with_rate X (λ k, N (2 * k)) := begin intro k m n Hm Hn, rewrite (rewrite_helper9 a), apply le.trans, apply abs_add_le_abs_add_abs, apply le.trans, apply add_le_add, apply Hc, apply Hm, krewrite abs_neg, apply Hc, apply Hn, xrewrite -of_rat_add, apply of_rat_le_of_rat_of_le, krewrite pnat.add_halves, end private definition Nb (M : ℕ+ → ℕ+) := λ k, pnat.max (3 * k) (M (2 * k)) private theorem Nb_spec_right (M : ℕ+ → ℕ+) (k : ℕ+) : M (2 * k) ≤ Nb M k := !pnat.max_right private theorem Nb_spec_left (M : ℕ+ → ℕ+) (k : ℕ+) : 3 * k ≤ Nb M k := !pnat.max_left section lim_seq parameter {X : r_seq} parameter {M : ℕ+ → ℕ+} hypothesis Hc : cauchy_with_rate X M include Hc noncomputable definition lim_seq : ℕ+ → ℚ := λ k, approx (X (Nb M k)) (2 * k) private theorem lim_seq_reg_helper {m n : ℕ+} (Hmn : M (2 * n) ≤M (2 * m)) : abs (of_rat (lim_seq m) - X (Nb M m)) + abs (X (Nb M m) - X (Nb M n)) + abs (X (Nb M n) - of_rat (lim_seq n)) ≤ of_rat (m⁻¹ + n⁻¹) := begin apply le.trans, apply add_le_add_three, apply approx_spec', rotate 1, apply approx_spec, rotate 1, apply Hc, rotate 1, apply Nb_spec_right, rotate 1, apply pnat.le_trans, apply Hmn, apply Nb_spec_right, krewrite [-+of_rat_add], change of_rat ((2 * m)⁻¹ + (2 * n)⁻¹ + (2 * n)⁻¹) ≤ of_rat (m⁻¹ + n⁻¹), rewrite [add.assoc], krewrite pnat.add_halves, apply of_rat_le_of_rat_of_le, apply add_le_add_right, apply inv_ge_of_le, apply pnat.mul_le_mul_left end theorem lim_seq_reg : rat_seq.regular lim_seq := begin rewrite ↑rat_seq.regular, intro m n, apply le_of_of_rat_le_of_rat, rewrite [abs_const, of_rat_sub, (rewrite_helper10 (X (Nb M m)) (X (Nb M n)))], apply le.trans, apply abs_add_three, cases em (M (2 * m) ≥ M (2 * n)) with [Hor1, Hor2], apply lim_seq_reg_helper Hor1, let Hor2' := pnat.le_of_lt (pnat.lt_of_not_le Hor2), krewrite [abs_sub (X (Nb M n)), abs_sub (X (Nb M m)), abs_sub, rat.add_comm, add_comm_three], apply lim_seq_reg_helper Hor2' end theorem lim_seq_spec (k : ℕ+) : rat_seq.s_le (rat_seq.s_abs (rat_seq.sadd lim_seq (rat_seq.sneg (rat_seq.const (lim_seq k))))) (rat_seq.const k⁻¹) := by apply rat_seq.const_bound; apply lim_seq_reg private noncomputable definition r_lim_seq : rat_seq.reg_seq := rat_seq.reg_seq.mk lim_seq lim_seq_reg private theorem r_lim_seq_spec (k : ℕ+) : rat_seq.r_le (rat_seq.r_abs ((rat_seq.radd r_lim_seq (rat_seq.rneg (rat_seq.r_const ((rat_seq.reg_seq.sq r_lim_seq) k)))))) (rat_seq.r_const k⁻¹) := lim_seq_spec k noncomputable definition lim : ℝ := quot.mk r_lim_seq theorem re_lim_spec (k : ℕ+) : re_abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := r_lim_seq_spec k theorem lim_spec' (k : ℕ+) : abs (lim - (of_rat (lim_seq k))) ≤ of_rat k⁻¹ := by rewrite -re_abs_is_abs; apply re_lim_spec theorem lim_spec (k : ℕ+) : abs ((of_rat (lim_seq k)) - lim) ≤ of_rat k⁻¹ := by rewrite abs_sub; apply lim_spec' theorem converges_to_with_rate_of_cauchy_with_rate : converges_to_with_rate X lim (Nb M) := begin intro k n Hn, rewrite (rewrite_helper10 (X (Nb M n)) (of_rat (lim_seq n))), apply le.trans, apply abs_add_three, apply le.trans, apply add_le_add_three, apply Hc, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_right, have HMk : M (2 * k) ≤ Nb M n, begin apply pnat.le_trans, apply Nb_spec_right, apply pnat.le_trans, apply Hn, apply pnat.le_trans, apply pnat.mul_le_mul_left 3, apply Nb_spec_left end, apply HMk, rewrite ↑lim_seq, apply approx_spec, apply lim_spec, krewrite [-+of_rat_add], change of_rat ((2 * k)⁻¹ + (2 * n)⁻¹ + n⁻¹) ≤ of_rat k⁻¹, apply of_rat_le_of_rat_of_le, apply le.trans, apply add_le_add_three, apply rat.le_refl, apply inv_ge_of_le, apply pnat_mul_le_mul_left', apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, apply inv_ge_of_le, apply pnat.le_trans, rotate 1, apply Hn, rotate_right 1, apply Nb_spec_left, rewrite -*pnat.mul_assoc, krewrite pnat.p_add_fractions, end end lim_seq ------------------------------------------- -- int embedding theorems -- archimedean properties, integer floor and ceiling section ints open int theorem archimedean_upper (x : ℝ) : ∃ z : ℤ, x ≤ of_int z := begin apply quot.induction_on x, intro s, cases rat_seq.bdd_of_regular (rat_seq.reg_seq.is_reg s) with [b, Hb], existsi ubound b, have H : rat_seq.s_le (rat_seq.reg_seq.sq s) (rat_seq.const (rat.of_nat (ubound b))), begin apply rat_seq.s_le_of_le_pointwise (rat_seq.reg_seq.is_reg s), apply rat_seq.const_reg, intro n, apply rat.le_trans, apply Hb, apply ubound_ge end, apply H end theorem archimedean_upper_strict (x : ℝ) : ∃ z : ℤ, x < of_int z := begin cases archimedean_upper x with [z, Hz], existsi z + 1, apply lt_of_le_of_lt, apply Hz, apply of_int_lt_of_int_of_lt, apply lt_add_of_pos_right, apply dec_trivial end theorem archimedean_lower (x : ℝ) : ∃ z : ℤ, x ≥ of_int z := begin cases archimedean_upper (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_le_iff_neg_le Hz end theorem archimedean_lower_strict (x : ℝ) : ∃ z : ℤ, x > of_int z := begin cases archimedean_upper_strict (-x) with [z, Hz], existsi -z, rewrite [of_int_neg], apply iff.mp !neg_lt_iff_neg_lt Hz end private definition ex_floor (x : ℝ) := (@exists_greatest_of_bdd (λ z, x ≥ of_int z) _ (begin existsi some (archimedean_upper_strict x), let Har := some_spec (archimedean_upper_strict x), intros z Hz, apply not_le_of_gt, apply lt_of_lt_of_le, apply Har, have H : of_int (some (archimedean_upper_strict x)) ≤ of_int z, begin apply of_int_le_of_int_of_le, apply Hz end, exact H end) (by existsi some (archimedean_lower x); apply some_spec (archimedean_lower x))) noncomputable definition floor (x : ℝ) : ℤ := some (ex_floor x) noncomputable definition ceil (x : ℝ) : ℤ := - floor (-x) theorem floor_le (x : ℝ) : floor x ≤ x := and.left (some_spec (ex_floor x)) theorem lt_of_floor_lt {x : ℝ} {z : ℤ} (Hz : floor x < z) : x < z := begin apply lt_of_not_ge, cases some_spec (ex_floor x), apply a_1 _ Hz end theorem le_ceil (x : ℝ) : x ≤ ceil x := begin rewrite [↑ceil, of_int_neg], apply iff.mp !le_neg_iff_le_neg, apply floor_le end theorem lt_of_lt_ceil {x : ℝ} {z : ℤ} (Hz : z < ceil x) : z < x := begin rewrite ↑ceil at Hz, note Hz' := lt_of_floor_lt (iff.mp !lt_neg_iff_lt_neg Hz), rewrite [of_int_neg at Hz'], apply lt_of_neg_lt_neg Hz' end theorem floor_succ (x : ℝ) : floor (x + 1) = floor x + 1 := begin apply by_contradiction, intro H, cases lt_or_gt_of_ne H with [Hgt, Hlt], note Hl := lt_of_floor_lt Hgt, rewrite [of_int_add at Hl], apply not_le_of_gt (lt_of_add_lt_add_right Hl) !floor_le, note Hl := lt_of_floor_lt (iff.mp !add_lt_iff_lt_sub_right Hlt), rewrite [of_int_sub at Hl], apply not_le_of_gt (iff.mpr !add_lt_iff_lt_sub_right Hl) !floor_le end theorem floor_sub_one_lt_floor (x : ℝ) : floor (x - 1) < floor x := begin apply @lt_of_add_lt_add_right ℤ _ _ 1, rewrite [-floor_succ (x - 1), sub_add_cancel], apply lt_add_of_pos_right dec_trivial end theorem ceil_lt_ceil_succ (x : ℝ) : ceil x < ceil (x + 1) := begin rewrite [↑ceil, neg_add], apply neg_lt_neg, apply floor_sub_one_lt_floor end open nat theorem archimedean_small {ε : ℝ} (H : ε > 0) : ∃ (n : ℕ), 1 / succ n < ε := let n := int.nat_abs (ceil (2 / ε)) in have int.of_nat n ≥ ceil (2 / ε), by rewrite of_nat_nat_abs; apply le_abs_self, have int.of_nat (succ n) ≥ ceil (2 / ε), begin apply le.trans, exact this, apply int.of_nat_le_of_nat_of_le, apply le_succ end, have H₁ : int.succ n ≥ ceil (2 / ε), from of_int_le_of_int_of_le this, have H₂ : succ n ≥ 2 / ε, from !le.trans !le_ceil H₁, have H₃ : 2 / ε > 0, from div_pos_of_pos_of_pos two_pos H, have 1 / succ n < ε, from calc 1 / succ n ≤ 1 / (2 / ε) : one_div_le_one_div_of_le H₃ H₂ ... = ε / 2 : one_div_div ... < ε : div_two_lt_of_pos H, exists.intro n this end ints -------------------------------------------------- -- supremum property -- this development roughly follows the proof of completeness done in Isabelle. -- It does not depend on the previous proof of Cauchy completeness. Much of the same -- machinery can be used to show that Cauchy completeness implies the supremum property. section supremum open prod nat local postfix `~` := nat_of_pnat -- The top part of this section could be refactored. What is the appropriate place to define -- bounds, supremum, etc? In algebra/ordered_field? They potentially apply to more than just ℝ. parameter X : ℝ → Prop definition ub (x : ℝ) := ∀ y : ℝ, X y → y ≤ x definition is_sup (x : ℝ) := ub x ∧ ∀ y : ℝ, ub y → x ≤ y definition lb (x : ℝ) := ∀ y : ℝ, X y → x ≤ y definition is_inf (x : ℝ) := lb x ∧ ∀ y : ℝ, lb y → y ≤ x parameter elt : ℝ hypothesis inh : X elt parameter bound : ℝ hypothesis bdd : ub bound include inh bdd private definition avg (a b : ℚ) := a / 2 + b / 2 private noncomputable definition bisect (ab : ℚ × ℚ) := if ub (avg (pr1 ab) (pr2 ab)) then (pr1 ab, (avg (pr1 ab) (pr2 ab))) else (avg (pr1 ab) (pr2 ab), pr2 ab) private noncomputable definition under : ℚ := rat.of_int (floor (elt - 1)) private theorem under_spec1 : of_rat under < elt := have H : of_rat under < of_int (floor elt), begin apply of_int_lt_of_int_of_lt, apply floor_sub_one_lt_floor end, lt_of_lt_of_le H !floor_le private theorem under_spec : ¬ ub under := begin rewrite ↑ub, apply not_forall_of_exists_not, existsi elt, apply iff.mpr !not_implies_iff_and_not, apply and.intro, apply inh, apply not_le_of_gt under_spec1 end private noncomputable definition over : ℚ := rat.of_int (ceil (bound + 1)) -- b private theorem over_spec1 : bound < of_rat over := have H : of_int (ceil bound) < of_rat over, begin apply of_int_lt_of_int_of_lt, apply ceil_lt_ceil_succ end, lt_of_le_of_lt !le_ceil H private theorem over_spec : ub over := begin rewrite ↑ub, intro y Hy, apply le_of_lt, apply lt_of_le_of_lt, apply bdd, apply Hy, apply over_spec1 end private noncomputable definition under_seq := λ n : ℕ, pr1 (iterate bisect n (under, over)) -- A private noncomputable definition over_seq := λ n : ℕ, pr2 (iterate bisect n (under, over)) -- B private noncomputable definition avg_seq := λ n : ℕ, avg (over_seq n) (under_seq n) -- C private theorem avg_symm (n : ℕ) : avg_seq n = avg (under_seq n) (over_seq n) := by rewrite [↑avg_seq, ↑avg, add.comm] private theorem over_0 : over_seq 0 = over := rfl private theorem under_0 : under_seq 0 = under := rfl private theorem succ_helper (n : ℕ) : avg (pr1 (iterate bisect n (under, over))) (pr2 (iterate bisect n (under, over))) = avg_seq n := by rewrite avg_symm private theorem under_succ (n : ℕ) : under_seq (succ n) = (if ub (avg_seq n) then under_seq n else avg_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = under_seq n, by rewrite [↑under_seq, ↑bisect at {2}, -succ_helper at Hub, if_pos Hub], apply H, rewrite [if_neg Hub], have H : pr1 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_neg Hub, avg_symm], apply H end private theorem over_succ (n : ℕ) : over_seq (succ n) = (if ub (avg_seq n) then avg_seq n else over_seq n) := begin cases em (ub (avg_seq n)) with [Hub, Hub], rewrite [if_pos Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = avg_seq n, by rewrite [↑bisect at {2}, -succ_helper at Hub, if_pos Hub, avg_symm], apply H, rewrite [if_neg Hub], have H : pr2 (bisect (iterate bisect n (under, over))) = over_seq n, by rewrite [↑over_seq, ↑bisect at {2}, -succ_helper at Hub, if_neg Hub], apply H end private theorem nat.zero_eq_0 : (zero : ℕ) = 0 := rfl private theorem width (n : ℕ) : over_seq n - under_seq n = (over - under) / ((2^n) : ℚ) := nat.induction_on n (by xrewrite [nat.zero_eq_0, over_0, under_0, pow_zero, div_one]) (begin intro a Ha, rewrite [over_succ, under_succ], let Hou := calc (over_seq a) / 2 - (under_seq a) / 2 = ((over - under) / 2^a) / 2 : by rewrite [div_sub_div_same, Ha] ... = (over - under) / ((2^a) * 2) : by rewrite div_div_eq_div_mul ... = (over - under) / 2^(a + 1) : by rewrite pow_add, cases em (ub (avg_seq a)), rewrite [*if_pos a_1, -add_one, -Hou, ↑avg_seq, ↑avg, sub_eq_add_neg, add.assoc, -sub_eq_add_neg, div_two_sub_self], rewrite [*if_neg a_1, -add_one, -Hou, ↑avg_seq, ↑avg, sub_add_eq_sub_sub, sub_self_div_two] end) private theorem width_narrows : ∃ n : ℕ, over_seq n - under_seq n ≤ 1 := begin cases binary_bound (over - under) with [a, Ha], existsi a, rewrite (width a), apply div_le_of_le_mul, apply pow_pos dec_trivial, rewrite rat.mul_one, apply Ha end private noncomputable definition over' := over_seq (some width_narrows) private noncomputable definition under' := under_seq (some width_narrows) private noncomputable definition over_seq' := λ n, over_seq (n + some width_narrows) private noncomputable definition under_seq' := λ n, under_seq (n + some width_narrows) private theorem over_seq'0 : over_seq' 0 = over' := by rewrite [↑over_seq', nat.zero_add] private theorem under_seq'0 : under_seq' 0 = under' := by rewrite [↑under_seq', nat.zero_add] private theorem under_over' : over' - under' ≤ 1 := some_spec width_narrows private theorem width' (n : ℕ) : over_seq' n - under_seq' n ≤ 1 / 2^n := nat.induction_on n (begin xrewrite [nat.zero_eq_0, over_seq'0, under_seq'0, pow_zero, div_one], apply under_over' end) (begin intros a Ha, rewrite [↑over_seq' at *, ↑under_seq' at *, *succ_add at *, width at *, -add_one, -(add_one a), pow_add, pow_add _ a 1, *pow_one], apply div_mul_le_div_mul_of_div_le_div_pos' Ha dec_trivial end) private theorem PA (n : ℕ) : ¬ ub (under_seq n) := nat.induction_on n (by rewrite under_0; apply under_spec) (begin intro a Ha, rewrite under_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem PB (n : ℕ) : ub (over_seq n) := nat.induction_on n (by rewrite over_0; apply over_spec) (begin intro a Ha, rewrite over_succ, cases em (ub (avg_seq a)), rewrite (if_pos a_1), assumption, rewrite (if_neg a_1), assumption end) private theorem under_lt_over : under < over := begin cases exists_not_of_not_forall under_spec with [x, Hx], cases and_not_of_not_implies Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply over_spec _ HXx end private theorem under_seq_lt_over_seq : ∀ m n : ℕ, under_seq m < over_seq n := begin intros, cases exists_not_of_not_forall (PA m) with [x, Hx], cases iff.mp !not_implies_iff_and_not Hx with [HXx, Hxu], apply lt_of_of_rat_lt_of_rat, apply lt_of_lt_of_le, apply lt_of_not_ge Hxu, apply PB, apply HXx end private theorem under_seq_lt_over_seq_single : ∀ n : ℕ, under_seq n < over_seq n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq' : ∀ m n : ℕ, under_seq' m < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq'_lt_over_seq'_single : ∀ n : ℕ, under_seq' n < over_seq' n := by intros; apply under_seq_lt_over_seq private theorem under_seq_mono_helper (i k : ℕ) : under_seq i ≤ under_seq (i + k) := (nat.induction_on k (by rewrite nat.add_zero; apply rat.le_refl) (begin intros a Ha, rewrite [add_succ, under_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite (if_pos Havg), apply Ha, rewrite [if_neg Havg, ↑avg_seq, ↑avg], apply rat.le_trans, apply Ha, rewrite -(add_halves (under_seq (i + a))) at {1}, apply add_le_add_right, apply div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial end)) private theorem under_seq_mono (i j : ℕ) (H : i ≤ j) : under_seq i ≤ under_seq j := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply under_seq_mono_helper end private theorem over_seq_mono_helper (i k : ℕ) : over_seq (i + k) ≤ over_seq i := nat.induction_on k (by rewrite nat.add_zero; apply rat.le_refl) (begin intros a Ha, rewrite [add_succ, over_succ], cases em (ub (avg_seq (i + a))) with [Havg, Havg], rewrite [if_pos Havg, ↑avg_seq, ↑avg], apply rat.le_trans, rotate 1, apply Ha, rotate 1, apply add_le_of_le_sub_left, rewrite sub_self_div_two, apply div_le_div_of_le_of_pos, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply dec_trivial, rewrite [if_neg Havg], apply Ha end) private theorem over_seq_mono (i j : ℕ) (H : i ≤ j) : over_seq j ≤ over_seq i := begin cases le.elim H with [k, Hk'], rewrite -Hk', apply over_seq_mono_helper end private theorem rat_power_two_inv_ge (k : ℕ+) : 1 / 2^k~ ≤ k⁻¹ := one_div_le_one_div_of_le !rat_of_pnat_is_pos !rat_power_two_le open rat_seq private theorem regular_lemma_helper {s : seq} {m n : ℕ+} (Hm : m ≤ n) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : abs (s m - s n) ≤ m⁻¹ + n⁻¹ := begin cases H m n Hm with [T1under, T1over], cases H m m (!pnat.le_refl) with [T2under, T2over], apply rat.le_trans, apply dist_bdd_within_interval, apply under_seq'_lt_over_seq'_single, rotate 1, repeat assumption, apply rat.le_trans, apply width', apply rat.le_trans, apply rat_power_two_inv_ge, apply le_add_of_nonneg_right, apply rat.le_of_lt (!pnat.inv_pos) end private theorem regular_lemma (s : seq) (H : ∀ n i : ℕ+, i ≥ n → under_seq' n~ ≤ s i ∧ s i ≤ over_seq' n~) : regular s := begin rewrite ↑regular, intros, cases em (m ≤ n) with [Hm, Hn], apply regular_lemma_helper Hm H, note T := regular_lemma_helper (pnat.le_of_lt (pnat.lt_of_not_le Hn)) H, rewrite [abs_sub at T, {n⁻¹ + _}add.comm at T], exact T end private noncomputable definition p_under_seq : seq := λ n : ℕ+, under_seq' n~ private noncomputable definition p_over_seq : seq := λ n : ℕ+, over_seq' n~ private theorem under_seq_regular : regular p_under_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply under_seq_mono, apply add_le_add_right, apply Hni, apply rat.le_of_lt, apply under_seq_lt_over_seq end private theorem over_seq_regular : regular p_over_seq := begin apply regular_lemma, intros n i Hni, apply and.intro, apply rat.le_of_lt, apply under_seq_lt_over_seq, apply over_seq_mono, apply add_le_add_right, apply Hni end private noncomputable definition sup_over : ℝ := quot.mk (reg_seq.mk p_over_seq over_seq_regular) private noncomputable definition sup_under : ℝ := quot.mk (reg_seq.mk p_under_seq under_seq_regular) private theorem over_bound : ub sup_over := begin rewrite ↑ub, intros y Hy, apply le_of_le_reprs, intro n, apply PB, apply Hy end private theorem under_lowest_bound : ∀ y : ℝ, ub y → sup_under ≤ y := begin intros y Hy, apply le_of_reprs_le, intro n, cases exists_not_of_not_forall (PA _) with [x, Hx], cases and_not_of_not_implies Hx with [HXx, Hxn], apply le.trans, apply le_of_lt, apply lt_of_not_ge Hxn, apply Hy, apply HXx end private theorem under_over_equiv : p_under_seq ≡ p_over_seq := begin intros, apply rat.le_trans, have H : p_under_seq n < p_over_seq n, from !under_seq_lt_over_seq, rewrite [abs_of_neg (iff.mpr !sub_neg_iff_lt H), neg_sub], apply width', apply rat.le_trans, apply rat_power_two_inv_ge, apply le_add_of_nonneg_left, apply rat.le_of_lt !pnat.inv_pos end private theorem under_over_eq : sup_under = sup_over := quot.sound under_over_equiv theorem exists_is_sup_of_inh_of_bdd : ∃ x : ℝ, is_sup x := exists.intro sup_over (and.intro over_bound (under_over_eq ▸ under_lowest_bound)) end supremum definition bounding_set (X : ℝ → Prop) (x : ℝ) : Prop := ∀ y : ℝ, X y → x ≤ y theorem exists_is_inf_of_inh_of_bdd (X : ℝ → Prop) (elt : ℝ) (inh : X elt) (bound : ℝ) (bdd : lb X bound) : ∃ x : ℝ, is_inf X x := begin have Hinh : bounding_set X bound, begin intros y Hy, apply bdd, apply Hy end, have Hub : ub (bounding_set X) elt, begin intros y Hy, apply Hy, apply inh end, cases exists_is_sup_of_inh_of_bdd _ _ Hinh _ Hub with [supr, Hsupr], existsi supr, cases Hsupr with [Hubs1, Hubs2], apply and.intro, intros, apply Hubs2, intros z Hz, apply Hz, apply a, intros y Hlby, apply Hubs1, intros z Hz, apply Hlby, apply Hz end end real
675f6970597ee871e69bb87f8c448638178b916b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/special_functions/trigonometric/angle.lean
088711e5b3384216f72ab0560add953cc9a2c093
[ "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
5,304
lean
/- Copyright (c) 2019 Calle Sönne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne -/ import analysis.special_functions.trigonometric.basic /-! # The type of angles In this file we define `real.angle` to be the quotient group `ℝ/2πℤ` and prove a few simple lemmas about trigonometric functions and angles. -/ open_locale real noncomputable theory namespace real /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (add_subgroup.zmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance : has_coe ℝ angle := ⟨quotient_add_group.mk' _⟩ /-- Coercion `ℝ → angle` as an additive homomorphism. -/ def coe_hom : ℝ →+ angle := quotient_add_group.mk' _ @[simp] lemma coe_coe_hom : (coe_hom : ℝ → angle) = coe := rfl @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑((n : ℝ) * x) = n • (↑x : angle) := by simpa only [nsmul_eq_mul] using coe_hom.map_nsmul x n @[simp, norm_cast] lemma coe_int_mul_eq_zsmul (x : ℝ) (n : ℤ) : ↑((n : ℝ) * x : ℝ) = n • (↑x : angle) := by simpa only [zsmul_eq_mul] using coe_hom.map_zsmul x n lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, add_subgroup.zmultiples_eq_closure, add_subgroup.mem_closure_singleton, zsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := angle_eq_iff_two_pi_dvd_sub.2 ⟨1, by rw [sub_zero, int.cast_one, mul_one]⟩ theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [← sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero] }, { left, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero, zero_add] }, apply_instance, }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero], rw [← sub_eq_zero, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw [coe_sub, coe_sub] at h, exact sub_right_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _ _), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, change n • _ = _ at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero, zsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle end real
fe5544de0b85c05b7c6a16f5776b55d61e5d9c8f
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data/UInt.lean
9fef30a94c3aebf271cfa5f6982246547fafc5b8
[ "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
14,947
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Fin.Basic import Init.System.Platform open Nat @[extern "lean_uint8_of_nat"] def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt8 := UInt8.ofNat @[extern "lean_uint8_to_nat"] def UInt8.toNat (n : UInt8) : Nat := n.val.val @[extern "lean_uint8_add"] def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩ @[extern "lean_uint8_sub"] def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩ @[extern "lean_uint8_mul"] def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩ @[extern "lean_uint8_div"] def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩ @[extern "lean_uint8_mod"] def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩ @[extern "lean_uint8_modn"] def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val % n⟩ @[extern "lean_uint8_land"] def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩ @[extern "lean_uint8_lor"] def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩ @[extern "lean_uint8_xor"] def UInt8.xor (a b : UInt8) : UInt8 := ⟨Fin.xor a.val b.val⟩ @[extern "lean_uint8_shift_left"] def UInt8.shiftLeft (a b : UInt8) : UInt8 := ⟨a.val <<< (modn b 8).val⟩ @[extern "lean_uint8_shift_right"] def UInt8.shiftRight (a b : UInt8) : UInt8 := ⟨a.val >>> (modn b 8).val⟩ def UInt8.lt (a b : UInt8) : Prop := a.val < b.val def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val instance : OfNat UInt8 n := ⟨UInt8.ofNat n⟩ instance : Add UInt8 := ⟨UInt8.add⟩ instance : Sub UInt8 := ⟨UInt8.sub⟩ instance : Mul UInt8 := ⟨UInt8.mul⟩ instance : Mod UInt8 := ⟨UInt8.mod⟩ instance : HMod UInt8 Nat UInt8 := ⟨UInt8.modn⟩ instance : Div UInt8 := ⟨UInt8.div⟩ instance : LT UInt8 := ⟨UInt8.lt⟩ instance : LE UInt8 := ⟨UInt8.le⟩ @[extern "lean_uint8_complement"] def UInt8.complement (a:UInt8) : UInt8 := 0-(a+1) instance : Complement UInt8 := ⟨UInt8.complement⟩ instance : AndOp UInt8 := ⟨UInt8.land⟩ instance : OrOp UInt8 := ⟨UInt8.lor⟩ instance : Xor UInt8 := ⟨UInt8.xor⟩ instance : ShiftLeft UInt8 := ⟨UInt8.shiftLeft⟩ instance : ShiftRight UInt8 := ⟨UInt8.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern "lean_uint8_dec_lt"] def UInt8.decLt (a b : UInt8) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern "lean_uint8_dec_le"] def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b instance (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b @[extern "lean_uint16_of_nat"] def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt16 := UInt16.ofNat @[extern "lean_uint16_to_nat"] def UInt16.toNat (n : UInt16) : Nat := n.val.val @[extern "lean_uint16_add"] def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩ @[extern "lean_uint16_sub"] def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩ @[extern "lean_uint16_mul"] def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩ @[extern "lean_uint16_div"] def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩ @[extern "lean_uint16_mod"] def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩ @[extern "lean_uint16_modn"] def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val % n⟩ @[extern "lean_uint16_land"] def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩ @[extern "lean_uint16_lor"] def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩ @[extern "lean_uint16_xor"] def UInt16.xor (a b : UInt16) : UInt16 := ⟨Fin.xor a.val b.val⟩ @[extern "lean_uint16_shift_left"] def UInt16.shiftLeft (a b : UInt16) : UInt16 := ⟨a.val <<< (modn b 16).val⟩ @[extern "lean_uint16_to_uint8"] def UInt16.toUInt8 (a : UInt16) : UInt8 := a.toNat.toUInt8 @[extern "lean_uint8_to_uint16"] def UInt8.toUInt16 (a : UInt8) : UInt16 := a.toNat.toUInt16 @[extern "lean_uint16_shift_right"] def UInt16.shiftRight (a b : UInt16) : UInt16 := ⟨a.val >>> (modn b 16).val⟩ def UInt16.lt (a b : UInt16) : Prop := a.val < b.val def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val instance : OfNat UInt16 n := ⟨UInt16.ofNat n⟩ instance : Add UInt16 := ⟨UInt16.add⟩ instance : Sub UInt16 := ⟨UInt16.sub⟩ instance : Mul UInt16 := ⟨UInt16.mul⟩ instance : Mod UInt16 := ⟨UInt16.mod⟩ instance : HMod UInt16 Nat UInt16 := ⟨UInt16.modn⟩ instance : Div UInt16 := ⟨UInt16.div⟩ instance : LT UInt16 := ⟨UInt16.lt⟩ instance : LE UInt16 := ⟨UInt16.le⟩ @[extern "lean_uint16_complement"] def UInt16.complement (a:UInt16) : UInt16 := 0-(a+1) instance : Complement UInt16 := ⟨UInt16.complement⟩ instance : AndOp UInt16 := ⟨UInt16.land⟩ instance : OrOp UInt16 := ⟨UInt16.lor⟩ instance : Xor UInt16 := ⟨UInt16.xor⟩ instance : ShiftLeft UInt16 := ⟨UInt16.shiftLeft⟩ instance : ShiftRight UInt16 := ⟨UInt16.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern "lean_uint16_dec_lt"] def UInt16.decLt (a b : UInt16) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern "lean_uint16_dec_le"] def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b instance (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b @[extern "lean_uint32_of_nat"] def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩ @[extern "lean_uint32_of_nat"] def UInt32.ofNat' (n : Nat) (h : n < UInt32.size) : UInt32 := ⟨⟨n, h⟩⟩ abbrev Nat.toUInt32 := UInt32.ofNat @[extern "lean_uint32_add"] def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩ @[extern "lean_uint32_sub"] def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩ @[extern "lean_uint32_mul"] def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩ @[extern "lean_uint32_div"] def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩ @[extern "lean_uint32_mod"] def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩ @[extern "lean_uint32_modn"] def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val % n⟩ @[extern "lean_uint32_land"] def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩ @[extern "lean_uint32_lor"] def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩ @[extern "lean_uint32_xor"] def UInt32.xor (a b : UInt32) : UInt32 := ⟨Fin.xor a.val b.val⟩ @[extern "lean_uint32_shift_left"] def UInt32.shiftLeft (a b : UInt32) : UInt32 := ⟨a.val <<< (modn b 32).val⟩ @[extern "lean_uint32_shift_right"] def UInt32.shiftRight (a b : UInt32) : UInt32 := ⟨a.val >>> (modn b 32).val⟩ @[extern "lean_uint32_to_uint8"] def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8 @[extern "lean_uint32_to_uint16"] def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16 @[extern "lean_uint8_to_uint32"] def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32 @[extern "lean_uint16_to_uint32"] def UInt16.toUInt32 (a : UInt16) : UInt32 := a.toNat.toUInt32 instance : OfNat UInt32 n := ⟨UInt32.ofNat n⟩ instance : Add UInt32 := ⟨UInt32.add⟩ instance : Sub UInt32 := ⟨UInt32.sub⟩ instance : Mul UInt32 := ⟨UInt32.mul⟩ instance : Mod UInt32 := ⟨UInt32.mod⟩ instance : HMod UInt32 Nat UInt32 := ⟨UInt32.modn⟩ instance : Div UInt32 := ⟨UInt32.div⟩ @[extern "lean_uint32_complement"] def UInt32.complement (a:UInt32) : UInt32 := 0-(a+1) instance : Complement UInt32 := ⟨UInt32.complement⟩ instance : AndOp UInt32 := ⟨UInt32.land⟩ instance : OrOp UInt32 := ⟨UInt32.lor⟩ instance : Xor UInt32 := ⟨UInt32.xor⟩ instance : ShiftLeft UInt32 := ⟨UInt32.shiftLeft⟩ instance : ShiftRight UInt32 := ⟨UInt32.shiftRight⟩ @[extern "lean_uint64_of_nat"] def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt64 := UInt64.ofNat @[extern "lean_uint64_to_nat"] def UInt64.toNat (n : UInt64) : Nat := n.val.val @[extern "lean_uint64_add"] def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩ @[extern "lean_uint64_sub"] def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩ @[extern "lean_uint64_mul"] def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩ @[extern "lean_uint64_div"] def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩ @[extern "lean_uint64_mod"] def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩ @[extern "lean_uint64_modn"] def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val % n⟩ @[extern "lean_uint64_land"] def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩ @[extern "lean_uint64_lor"] def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩ @[extern "lean_uint64_xor"] def UInt64.xor (a b : UInt64) : UInt64 := ⟨Fin.xor a.val b.val⟩ @[extern "lean_uint64_shift_left"] def UInt64.shiftLeft (a b : UInt64) : UInt64 := ⟨a.val <<< (modn b 64).val⟩ @[extern "lean_uint64_shift_right"] def UInt64.shiftRight (a b : UInt64) : UInt64 := ⟨a.val >>> (modn b 64).val⟩ def UInt64.lt (a b : UInt64) : Prop := a.val < b.val def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val @[extern "lean_uint64_to_uint8"] def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8 @[extern "lean_uint64_to_uint16"] def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16 @[extern "lean_uint64_to_uint32"] def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32 @[extern "lean_uint8_to_uint64"] def UInt8.toUInt64 (a : UInt8) : UInt64 := a.toNat.toUInt64 @[extern "lean_uint16_to_uint64"] def UInt16.toUInt64 (a : UInt16) : UInt64 := a.toNat.toUInt64 @[extern "lean_uint32_to_uint64"] def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64 instance : OfNat UInt64 n := ⟨UInt64.ofNat n⟩ instance : Add UInt64 := ⟨UInt64.add⟩ instance : Sub UInt64 := ⟨UInt64.sub⟩ instance : Mul UInt64 := ⟨UInt64.mul⟩ instance : Mod UInt64 := ⟨UInt64.mod⟩ instance : HMod UInt64 Nat UInt64 := ⟨UInt64.modn⟩ instance : Div UInt64 := ⟨UInt64.div⟩ instance : LT UInt64 := ⟨UInt64.lt⟩ instance : LE UInt64 := ⟨UInt64.le⟩ @[extern "lean_uint64_complement"] def UInt64.complement (a:UInt64) : UInt64 := 0-(a+1) instance : Complement UInt64 := ⟨UInt64.complement⟩ instance : AndOp UInt64 := ⟨UInt64.land⟩ instance : OrOp UInt64 := ⟨UInt64.lor⟩ instance : Xor UInt64 := ⟨UInt64.xor⟩ instance : ShiftLeft UInt64 := ⟨UInt64.shiftLeft⟩ instance : ShiftRight UInt64 := ⟨UInt64.shiftRight⟩ @[extern "lean_bool_to_uint64"] def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0 set_option bootstrap.genMatcherCode false in @[extern "lean_uint64_dec_lt"] def UInt64.decLt (a b : UInt64) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern "lean_uint64_dec_le"] def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b instance (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b theorem usize_size_gt_zero : USize.size > 0 := Nat.pos_pow_of_pos System.Platform.numBits (Nat.zero_lt_succ _) @[extern "lean_usize_of_nat"] def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usize_size_gt_zero⟩ abbrev Nat.toUSize := USize.ofNat @[extern "lean_usize_to_nat"] def USize.toNat (n : USize) : Nat := n.val.val @[extern "lean_usize_add"] def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩ @[extern "lean_usize_sub"] def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩ @[extern "lean_usize_mul"] def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩ @[extern "lean_usize_div"] def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩ @[extern "lean_usize_mod"] def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩ @[extern "lean_usize_modn"] def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val % n⟩ @[extern "lean_usize_land"] def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩ @[extern "lean_usize_lor"] def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩ @[extern "lean_usize_xor"] def USize.xor (a b : USize) : USize := ⟨Fin.xor a.val b.val⟩ @[extern "lean_usize_shift_left"] def USize.shiftLeft (a b : USize) : USize := ⟨a.val <<< (modn b System.Platform.numBits).val⟩ @[extern "lean_usize_shift_right"] def USize.shiftRight (a b : USize) : USize := ⟨a.val >>> (modn b System.Platform.numBits).val⟩ @[extern "lean_uint32_to_usize"] def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize @[extern "lean_usize_to_uint32"] def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32 def USize.lt (a b : USize) : Prop := a.val < b.val def USize.le (a b : USize) : Prop := a.val ≤ b.val instance : OfNat USize n := ⟨USize.ofNat n⟩ instance : Add USize := ⟨USize.add⟩ instance : Sub USize := ⟨USize.sub⟩ instance : Mul USize := ⟨USize.mul⟩ instance : Mod USize := ⟨USize.mod⟩ instance : HMod USize Nat USize := ⟨USize.modn⟩ instance : Div USize := ⟨USize.div⟩ instance : LT USize := ⟨USize.lt⟩ instance : LE USize := ⟨USize.le⟩ @[extern "lean_usize_complement"] def USize.complement (a:USize) : USize := 0-(a+1) instance : Complement USize := ⟨USize.complement⟩ instance : AndOp USize := ⟨USize.land⟩ instance : OrOp USize := ⟨USize.lor⟩ instance : Xor USize := ⟨USize.xor⟩ instance : ShiftLeft USize := ⟨USize.shiftLeft⟩ instance : ShiftRight USize := ⟨USize.shiftRight⟩ set_option bootstrap.genMatcherCode false in @[extern "lean_usize_dec_lt"] def USize.decLt (a b : USize) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern "lean_usize_dec_le"] def USize.decLe (a b : USize) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : USize) : Decidable (a < b) := USize.decLt a b instance (a b : USize) : Decidable (a ≤ b) := USize.decLe a b theorem USize.modn_lt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u % m) < m | ⟨u⟩, h => Fin.modn_lt u h
f1b945c5c719efdb738a8eb967fced98eeb560cb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/monoid.lean
c017202aa05d668687f0a7e4cbbe320343f6bb8e
[ "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
27,612
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.big_operators.finprod import data.set.pointwise.basic import topology.algebra.mul_action import algebra.big_operators.pi /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ universes u v open classical set filter topological_space open_locale classical topological_space big_operators pointwise variables {ι α X M N : Type*} [topological_space X] @[to_additive] lemma continuous_one [topological_space M] [has_one M] : continuous (1 : X → M) := @continuous_const _ _ _ _ 1 /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `M`, for example, is obtained by requiring both the instances `add_monoid M` and `has_continuous_add M`. Continuity in only the left/right argument can be stated using `has_continuous_const_vadd α α`/`has_continuous_const_vadd αᵐᵒᵖ α`. -/ class has_continuous_add (M : Type u) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `M`, for example, is obtained by requiring both the instances `monoid M` and `has_continuous_mul M`. Continuity in only the left/right argument can be stated using `has_continuous_const_smul α α`/`has_continuous_const_smul αᵐᵒᵖ α`. -/ @[to_additive] class has_continuous_mul (M : Type u) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[to_additive] instance has_continuous_mul.to_has_continuous_smul : has_continuous_smul M M := ⟨continuous_mul⟩ @[to_additive] instance has_continuous_mul.to_has_continuous_smul_op : has_continuous_smul Mᵐᵒᵖ M := ⟨show continuous ((λ p : M × M, p.1 * p.2) ∘ prod.swap ∘ prod.map mul_opposite.unop id), from continuous_mul.comp $ continuous_swap.comp $ continuous.prod_map mul_opposite.continuous_unop continuous_id⟩ @[continuity, to_additive] lemma continuous.mul {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul {f g : X → M} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma filter.tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds /-- Construct a unit from limits of units and their inverses. -/ @[to_additive filter.tendsto.add_units "Construct an additive unit from limits of additive units and their negatives.", simps] def filter.tendsto.units [topological_space N] [monoid N] [has_continuous_mul N] [t2_space N] {f : ι → Nˣ} {r₁ r₂ : N} {l : filter ι} [l.ne_bot] (h₁ : tendsto (λ x, ↑(f x)) l (𝓝 r₁)) (h₂ : tendsto (λ x, ↑(f x)⁻¹) l (𝓝 r₂)) : Nˣ := { val := r₁, inv := r₂, val_inv := tendsto_nhds_unique (by simpa using h₁.mul h₂) tendsto_const_nhds, inv_val := tendsto_nhds_unique (by simpa using h₂.mul h₁) tendsto_const_nhds } @[to_additive] lemma continuous_at.mul {f g : X → M} {x : X} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul {f g : X → M} {s : set X} {x : X} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨(continuous_fst.fst'.mul continuous_fst.snd').prod_mk (continuous_snd.fst'.mul continuous_snd.snd')⟩ @[to_additive] instance pi.has_continuous_mul {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_mul (C i)] [∀ i, has_continuous_mul (C i)] : has_continuous_mul (Π i, C i) := { continuous_mul := continuous_pi (λ i, (continuous_apply i).fst'.mul (continuous_apply i).snd') } /-- A version of `pi.has_continuous_mul` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_mul` for non-dependent functions. -/ @[to_additive "A version of `pi.has_continuous_add` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_add` for non-dependent functions."] instance pi.has_continuous_mul' : has_continuous_mul (ι → M) := pi.has_continuous_mul @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type u} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type u) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section pointwise_limits variables (M₁ M₂ : Type*) [topological_space M₂] [t2_space M₂] @[to_additive] lemma is_closed_set_of_map_one [has_one M₁] [has_one M₂] : is_closed {f : M₁ → M₂ | f 1 = 1} := is_closed_eq (continuous_apply 1) continuous_const @[to_additive] lemma is_closed_set_of_map_mul [has_mul M₁] [has_mul M₂] [has_continuous_mul M₂] : is_closed {f : M₁ → M₂ | ∀ x y, f (x * y) = f x * f y} := begin simp only [set_of_forall], exact is_closed_Inter (λ x, is_closed_Inter (λ y, is_closed_eq (continuous_apply _) ((continuous_apply _).mul (continuous_apply _)))) end variables {M₁ M₂} [mul_one_class M₁] [mul_one_class M₂] [has_continuous_mul M₂] {F : Type*} [monoid_hom_class F M₁ M₂] {l : filter α} /-- Construct a bundled monoid homomorphism `M₁ →* M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →* M₂` (or another type of bundled homomorphisms that has a `monoid_hom_class` instance) to `M₁ → M₂`. -/ @[to_additive "Construct a bundled additive monoid homomorphism `M₁ →+ M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →+ M₂` (or another type of bundled homomorphisms that has a `add_monoid_hom_class` instance) to `M₁ → M₂`.", simps { fully_applied := ff }] def monoid_hom_of_mem_closure_range_coe (f : M₁ → M₂) (hf : f ∈ closure (range (λ (f : F) (x : M₁), f x))) : M₁ →* M₂ := { to_fun := f, map_one' := (is_closed_set_of_map_one M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_one) hf, map_mul' := (is_closed_set_of_map_mul M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_mul) hf } /-- Construct a bundled monoid homomorphism from a pointwise limit of monoid homomorphisms. -/ @[to_additive "Construct a bundled additive monoid homomorphism from a pointwise limit of additive monoid homomorphisms", simps { fully_applied := ff }] def monoid_hom_of_tendsto (f : M₁ → M₂) (g : α → F) [l.ne_bot] (h : tendsto (λ a x, g a x) l (𝓝 f)) : M₁ →* M₂ := monoid_hom_of_mem_closure_range_coe f $ mem_closure_of_tendsto h $ eventually_of_forall $ λ a, mem_range_self _ variables (M₁ M₂) @[to_additive] lemma monoid_hom.is_closed_range_coe : is_closed (range (coe_fn : (M₁ →* M₂) → (M₁ → M₂))) := is_closed_of_closure_subset $ λ f hf, ⟨monoid_hom_of_mem_closure_range_coe f hf, rfl⟩ end pointwise_limits @[to_additive] lemma inducing.has_continuous_mul {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space M] [topological_space N] [has_continuous_mul N] (f : F) (hf : inducing f) : has_continuous_mul M := ⟨hf.continuous_iff.2 $ by simpa only [(∘), map_mul f] using (hf.continuous.fst'.mul hf.continuous.snd')⟩ @[to_additive] lemma has_continuous_mul_induced {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space N] [has_continuous_mul N] (f : F) : @has_continuous_mul M (induced f ‹_›) _ := by { letI := induced f ‹_›, exact inducing.has_continuous_mul f ⟨rfl⟩ } @[to_additive] instance subsemigroup.has_continuous_mul [topological_space M] [semigroup M] [has_continuous_mul M] (S : subsemigroup M) : has_continuous_mul S := inducing.has_continuous_mul (⟨coe, λ _ _, rfl⟩ : mul_hom S M) ⟨rfl⟩ @[to_additive] instance submonoid.has_continuous_mul [topological_space M] [monoid M] [has_continuous_mul M] (S : submonoid M) : has_continuous_mul S := S.to_subsemigroup.has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive] lemma submonoid.top_closure_mul_self_subset (s : submonoid M) : closure (s : set M) * closure s ⊆ closure s := image2_subset_iff.2 $ λ x hx y hy, map_mem_closure₂ continuous_mul hx hy $ λ a ha b hb, s.mul_mem ha hb @[to_additive] lemma submonoid.top_closure_mul_self_eq (s : submonoid M) : closure (s : set M) * closure s = closure s := subset.antisymm s.top_closure_mul_self_subset (λ x hx, ⟨x, 1, hx, subset_closure s.one_mem, mul_one _⟩) /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ @[to_additive "The (topological-space) closure of an additive submonoid of a space `M` with `has_continuous_add` is itself an additive submonoid."] def submonoid.topological_closure (s : submonoid M) : submonoid M := { carrier := closure (s : set M), one_mem' := subset_closure s.one_mem, mul_mem' := λ a b ha hb, s.top_closure_mul_self_subset ⟨a, b, ha, hb, rfl⟩ } @[to_additive] lemma submonoid.submonoid_topological_closure (s : submonoid M) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma submonoid.is_closed_topological_closure (s : submonoid M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure @[to_additive] lemma submonoid.topological_closure_minimal (s : submonoid M) {t : submonoid M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a submonoid of a topological monoid is commutative, then so is its topological closure. -/ @[to_additive "If a submonoid of an additive topological monoid is commutative, then so is its topological closure."] def submonoid.comm_monoid_topological_closure [t2_space M] (s : submonoid M) (hs : ∀ (x y : s), x * y = y * x) : comm_monoid s.topological_closure := { mul_comm := have ∀ (x ∈ s) (y ∈ s), x * y = y * x, from λ x hx y hy, congr_arg subtype.val (hs ⟨x, hx⟩ ⟨y, hy⟩), λ ⟨x, hx⟩ ⟨y, hy⟩, subtype.ext $ eq_on_closure₂ this continuous_mul (continuous_snd.mul continuous_fst) x hx y hy, ..s.topological_closure.to_monoid } @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, is_open.mem_nhds Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma is_compact.mul {s t : set M} (hs : is_compact s) (ht : is_compact t) : is_compact (s * t) := by { rw [← image_mul_prod], exact (hs.prod ht).image continuous_mul } @[to_additive] lemma tendsto_list_prod {f : ι → α → M} {x : filter α} {a : ι → M} : ∀ l:list ι, (∀i∈l, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod {f : ι → X → M} (l : list ι) (h : ∀ i ∈ l, continuous (f i)) : continuous (λ a, (l.map (λ i, f i a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive] lemma continuous_on_list_prod {f : ι → X → M} (l : list ι) {t : set X} (h : ∀ i ∈ l, continuous_on (f i) t) : continuous_on (λ a, (l.map (λ i, f i a)).prod) t := begin intros x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx, refine tendsto_list_prod _ (λ i hi, _), specialize h i hi x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx at h, exact h, end @[continuity, to_additive] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := by { simp only [pow_succ], exact continuous_id.mul (continuous_pow _) } instance add_monoid.has_continuous_const_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_const_smul ℕ A := ⟨continuous_nsmul⟩ instance add_monoid.has_continuous_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_smul ℕ A := ⟨continuous_uncurry_of_discrete_topology continuous_nsmul⟩ @[continuity, to_additive continuous.nsmul] lemma continuous.pow {f : X → M} (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := (continuous_pow n).comp h @[to_additive] lemma continuous_on_pow {s : set M} (n : ℕ) : continuous_on (λ x, x ^ n) s := (continuous_pow n).continuous_on @[to_additive] lemma continuous_at_pow (x : M) (n : ℕ) : continuous_at (λ x, x ^ n) x := (continuous_pow n).continuous_at @[to_additive filter.tendsto.nsmul] lemma filter.tendsto.pow {l : filter α} {f : α → M} {x : M} (hf : tendsto f l (𝓝 x)) (n : ℕ) : tendsto (λ x, f x ^ n) l (𝓝 (x ^ n)) := (continuous_at_pow _ _).tendsto.comp hf @[to_additive continuous_within_at.nsmul] lemma continuous_within_at.pow {f : X → M} {x : X} {s : set X} (hf : continuous_within_at f s x) (n : ℕ) : continuous_within_at (λ x, f x ^ n) s x := hf.pow n @[to_additive continuous_at.nsmul] lemma continuous_at.pow {f : X → M} {x : X} (hf : continuous_at f x) (n : ℕ) : continuous_at (λ x, f x ^ n) x := hf.pow n @[to_additive continuous_on.nsmul] lemma continuous_on.pow {f : X → M} {s : set X} (hf : continuous_on f s) (n : ℕ) : continuous_on (λ x, f x ^ n) s := λ x hx, (hf x hx).pow n /-- Left-multiplication by a left-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_left {a b : M} (ha : b * a = 1) : filter.tendsto (λ x : M, a * x) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_left b)), convert filter.tendsto_id, ext x, simp [ha], end /-- Right-multiplication by a right-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_right {a b : M} (ha : a * b = 1) : filter.tendsto (λ x : M, x * a) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_right b)), convert filter.tendsto_id, ext x, simp [ha], end /-- If `R` acts on `A` via `A`, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = A`, or when `[algebra R A]` is available. -/ @[priority 100, to_additive "If `R` acts on `A` via `A`, then continuous addition implies continuous affine addition by constants."] instance is_scalar_tower.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [is_scalar_tower R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←smul_one_mul q (_ : A)] { single_pass := tt }, exact continuous_const.mul continuous_id, end } /-- If the action of `R` on `A` commutes with left-multiplication, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = Aᵐᵒᵖ` -/ @[priority 100, to_additive "If the action of `R` on `A` commutes with left-addition, then continuous addition implies continuous affine addition by constants. Notably, this instances applies when `R = Aᵃᵒᵖ`. "] instance smul_comm_class.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [smul_comm_class R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←mul_smul_one q (_ : A)] { single_pass := tt }, exact continuous_id.mul continuous_const, end } end has_continuous_mul namespace mul_opposite /-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/ @[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."] instance [topological_space α] [has_mul α] [has_continuous_mul α] : has_continuous_mul αᵐᵒᵖ := ⟨continuous_op.comp (continuous_unop.snd'.mul continuous_unop.fst')⟩ end mul_opposite namespace units open mul_opposite variables [topological_space α] [monoid α] [has_continuous_mul α] /-- If multiplication on a monoid is continuous, then multiplication on the units of the monoid, with respect to the induced topology, is continuous. Inversion is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_inv` has not yet been defined. -/ @[to_additive "If addition on an additive monoid is continuous, then addition on the additive units of the monoid, with respect to the induced topology, is continuous. Negation is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_neg` has not yet been defined."] instance : has_continuous_mul αˣ := inducing_embed_product.has_continuous_mul (embed_product α) end units @[to_additive] lemma continuous.units_map [monoid M] [monoid N] [topological_space M] [topological_space N] (f : M →* N) (hf : continuous f) : continuous (units.map f) := units.continuous_iff.2 ⟨hf.comp units.continuous_coe, hf.comp units.continuous_coe_inv⟩ section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := is_open.mem_nhds oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : multiset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simpa using tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : finset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[continuity, to_additive] lemma continuous_multiset_prod {f : ι → X → M} (s : multiset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, (s.map (λ i, f i a)).prod) := by { rcases s with ⟨l⟩, simpa using continuous_list_prod l } @[to_additive] lemma continuous_on_multiset_prod {f : ι → X → M} (s : multiset ι) {t : set X} : (∀i ∈ s, continuous_on (f i) t) → continuous_on (λ a, (s.map (λ i, f i a)).prod) t := by { rcases s with ⟨l⟩, simpa using continuous_on_list_prod l } @[continuity, to_additive] lemma continuous_finset_prod {f : ι → X → M} (s : finset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, ∏ i in s, f i a) := continuous_multiset_prod _ @[to_additive] lemma continuous_on_finset_prod {f : ι → X → M} (s : finset ι) {t : set X} : (∀ i ∈ s, continuous_on (f i) t) → continuous_on (λ a, ∏ i in s, f i a) t := continuous_on_multiset_prod _ @[to_additive] lemma eventually_eq_prod {X M : Type*} [comm_monoid M] {s : finset ι} {l : filter X} {f g : ι → X → M} (hs : ∀ i ∈ s, f i =ᶠ[l] g i) : ∏ i in s, f i =ᶠ[l] ∏ i in s, g i := begin replace hs: ∀ᶠ x in l, ∀ i ∈ s, f i x = g i x, { rwa eventually_all_finset }, filter_upwards [hs] with x hx, simp only [finset.prod_apply, finset.prod_congr rfl hx], end open function @[to_additive] lemma locally_finite.exists_finset_mul_support {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support $ f i)) (x₀ : X) : ∃ I : finset ι, ∀ᶠ x in 𝓝 x₀, mul_support (λ i, f i x) ⊆ I := begin rcases hf x₀ with ⟨U, hxU, hUf⟩, refine ⟨hUf.to_finset, mem_of_superset hxU $ λ y hy i hi, _⟩, rw [hUf.coe_to_finset], exact ⟨y, hi, hy⟩ end @[to_additive] lemma finprod_eventually_eq_prod {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support (f i))) (x : X) : ∃ s : finset ι, ∀ᶠ y in 𝓝 x, (∏ᶠ i, f i y) = ∏ i in s, f i y := let ⟨I, hI⟩ := hf.exists_finset_mul_support x in ⟨I, hI.mono (λ y hy, finprod_eq_prod_of_mul_support_subset _ $ λ i hi, hy hi)⟩ @[to_additive] lemma continuous_finprod {f : ι → X → M} (hc : ∀ i, continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i, f i x) := begin refine continuous_iff_continuous_at.2 (λ x, _), rcases finprod_eventually_eq_prod hf x with ⟨s, hs⟩, refine continuous_at.congr _ (eventually_eq.symm hs), exact tendsto_finset_prod _ (λ i hi, (hc i).continuous_at), end @[to_additive] lemma continuous_finprod_cond {f : ι → X → M} {p : ι → Prop} (hc : ∀ i, p i → continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i (hi : p i), f i x) := begin simp only [← finprod_subtype_eq_finprod_cond], exact continuous_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective) end end instance [topological_space M] [has_mul M] [has_continuous_mul M] : has_continuous_add (additive M) := { continuous_add := @continuous_mul M _ _ _ } instance [topological_space M] [has_add M] [has_continuous_add M] : has_continuous_mul (multiplicative M) := { continuous_mul := @continuous_add M _ _ _ } section lattice_ops variables {ι' : Sort*} [has_mul M] @[to_additive] lemma has_continuous_mul_Inf {ts : set (topological_space M)} (h : Π t ∈ ts, @has_continuous_mul M t _) : @has_continuous_mul M (Inf ts) _ := { continuous_mul := continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom₂ ht ht (@has_continuous_mul.continuous_mul M t _ (h t ht))) } @[to_additive] lemma has_continuous_mul_infi {ts : ι' → topological_space M} (h' : Π i, @has_continuous_mul M (ts i) _) : @has_continuous_mul M (⨅ i, ts i) _ := by { rw ← Inf_range, exact has_continuous_mul_Inf (set.forall_range_iff.mpr h') } @[to_additive] lemma has_continuous_mul_inf {t₁ t₂ : topological_space M} (h₁ : @has_continuous_mul M t₁ _) (h₂ : @has_continuous_mul M t₂ _) : @has_continuous_mul M (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine has_continuous_mul_infi (λ b, _), cases b; assumption } end lattice_ops
0e81d0b68508a1a28f295e69305807d1134ea68f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/legendre_symbol/zmod_char.lean
5921d6bbd543d02cde9be50b116d992e9e0ade60
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,129
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import data.int.range import data.zmod.basic import number_theory.legendre_symbol.mul_character /-! # Quadratic characters on ℤ/nℤ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines some quadratic characters on the rings ℤ/4ℤ and ℤ/8ℤ. We set them up to be of type `mul_char (zmod n) ℤ`, where `n` is `4` or `8`. ## Tags quadratic character, zmod -/ /-! ### Quadratic characters mod 4 and 8 We define the primitive quadratic characters `χ₄`on `zmod 4` and `χ₈`, `χ₈'` on `zmod 8`. -/ namespace zmod section quad_char_mod_p /-- Define the nontrivial quadratic character on `zmod 4`, `χ₄`. It corresponds to the extension `ℚ(√-1)/ℚ`. -/ @[simps] def χ₄ : mul_char (zmod 4) ℤ := { to_fun := (![0,1,0,-1] : (zmod 4 → ℤ)), map_one' := rfl, map_mul' := dec_trivial, map_nonunit' := dec_trivial } /-- `χ₄` takes values in `{0, 1, -1}` -/ lemma is_quadratic_χ₄ : χ₄.is_quadratic := by { intro a, dec_trivial!, } /-- The value of `χ₄ n`, for `n : ℕ`, depends only on `n % 4`. -/ lemma χ₄_nat_mod_four (n : ℕ) : χ₄ n = χ₄ (n % 4 : ℕ) := by rw ← zmod.nat_cast_mod n 4 /-- The value of `χ₄ n`, for `n : ℤ`, depends only on `n % 4`. -/ lemma χ₄_int_mod_four (n : ℤ) : χ₄ n = χ₄ (n % 4 : ℤ) := by { rw ← zmod.int_cast_mod n 4, norm_cast, } /-- An explicit description of `χ₄` on integers / naturals -/ lemma χ₄_int_eq_if_mod_four (n : ℤ) : χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 := begin have help : ∀ (m : ℤ), 0 ≤ m → m < 4 → χ₄ m = if m % 2 = 0 then 0 else if m = 1 then 1 else -1 := dec_trivial, rw [← int.mod_mod_of_dvd n (by norm_num : (2 : ℤ) ∣ 4), ← zmod.int_cast_mod n 4], exact help (n % 4) (int.mod_nonneg n (by norm_num)) (int.mod_lt n (by norm_num)), end lemma χ₄_nat_eq_if_mod_four (n : ℕ) : χ₄ n = if n % 2 = 0 then 0 else if n % 4 = 1 then 1 else -1 := by exact_mod_cast χ₄_int_eq_if_mod_four n /-- Alternative description of `χ₄ n` for odd `n : ℕ` in terms of powers of `-1` -/ lemma χ₄_eq_neg_one_pow {n : ℕ} (hn : n % 2 = 1) : χ₄ n = (-1)^(n / 2) := begin rw χ₄_nat_eq_if_mod_four, simp only [hn, nat.one_ne_zero, if_false], nth_rewrite 0 ← nat.div_add_mod n 4, nth_rewrite 0 (by norm_num : 4 = 2 * 2), rw [mul_assoc, add_comm, nat.add_mul_div_left _ _ (by norm_num : 0 < 2), pow_add, pow_mul, neg_one_sq, one_pow, mul_one], have help : ∀ m : ℕ, m < 4 → m % 2 = 1 → ite (m = 1) (1 : ℤ) (-1) = (-1) ^ (m / 2) := dec_trivial, exact help (n % 4) (nat.mod_lt n (by norm_num)) ((nat.mod_mod_of_dvd n (by norm_num : 2 ∣ 4)).trans hn), end /-- If `n % 4 = 1`, then `χ₄ n = 1`. -/ lemma χ₄_nat_one_mod_four {n : ℕ} (hn : n % 4 = 1) : χ₄ n = 1 := by { rw [χ₄_nat_mod_four, hn], refl } /-- If `n % 4 = 3`, then `χ₄ n = -1`. -/ lemma χ₄_nat_three_mod_four {n : ℕ} (hn : n % 4 = 3) : χ₄ n = -1 := by { rw [χ₄_nat_mod_four, hn], refl } /-- If `n % 4 = 1`, then `χ₄ n = 1`. -/ lemma χ₄_int_one_mod_four {n : ℤ} (hn : n % 4 = 1) : χ₄ n = 1 := by { rw [χ₄_int_mod_four, hn], refl } /-- If `n % 4 = 3`, then `χ₄ n = -1`. -/ lemma χ₄_int_three_mod_four {n : ℤ} (hn : n % 4 = 3) : χ₄ n = -1 := by { rw [χ₄_int_mod_four, hn], refl } /-- If `n % 4 = 1`, then `(-1)^(n/2) = 1`. -/ lemma _root_.neg_one_pow_div_two_of_one_mod_four {n : ℕ} (hn : n % 4 = 1) : (-1 : ℤ) ^ (n / 2) = 1 := by { rw [← χ₄_eq_neg_one_pow (nat.odd_of_mod_four_eq_one hn), ← nat_cast_mod, hn], refl } /-- If `n % 4 = 3`, then `(-1)^(n/2) = -1`. -/ lemma _root_.neg_one_pow_div_two_of_three_mod_four {n : ℕ} (hn : n % 4 = 3) : (-1 : ℤ) ^ (n / 2) = -1 := by { rw [← χ₄_eq_neg_one_pow (nat.odd_of_mod_four_eq_three hn), ← nat_cast_mod, hn], refl } /-- Define the first primitive quadratic character on `zmod 8`, `χ₈`. It corresponds to the extension `ℚ(√2)/ℚ`. -/ @[simps] def χ₈ : mul_char (zmod 8) ℤ := { to_fun := (![0,1,0,-1,0,-1,0,1] : (zmod 8 → ℤ)), map_one' := rfl, map_mul' := dec_trivial, map_nonunit' := dec_trivial } /-- `χ₈` takes values in `{0, 1, -1}` -/ lemma is_quadratic_χ₈ : χ₈.is_quadratic := by { intro a, dec_trivial!, } /-- The value of `χ₈ n`, for `n : ℕ`, depends only on `n % 8`. -/ lemma χ₈_nat_mod_eight (n : ℕ) : χ₈ n = χ₈ (n % 8 : ℕ) := by rw ← zmod.nat_cast_mod n 8 /-- The value of `χ₈ n`, for `n : ℤ`, depends only on `n % 8`. -/ lemma χ₈_int_mod_eight (n : ℤ) : χ₈ n = χ₈ (n % 8 : ℤ) := by { rw ← zmod.int_cast_mod n 8, norm_cast, } /-- An explicit description of `χ₈` on integers / naturals -/ lemma χ₈_int_eq_if_mod_eight (n : ℤ) : χ₈ n = if n % 2 = 0 then 0 else if n % 8 = 1 ∨ n % 8 = 7 then 1 else -1 := begin have help : ∀ (m : ℤ), 0 ≤ m → m < 8 → χ₈ m = if m % 2 = 0 then 0 else if m = 1 ∨ m = 7 then 1 else -1 := dec_trivial, rw [← int.mod_mod_of_dvd n (by norm_num : (2 : ℤ) ∣ 8), ← zmod.int_cast_mod n 8], exact help (n % 8) (int.mod_nonneg n (by norm_num)) (int.mod_lt n (by norm_num)), end lemma χ₈_nat_eq_if_mod_eight (n : ℕ) : χ₈ n = if n % 2 = 0 then 0 else if n % 8 = 1 ∨ n % 8 = 7 then 1 else -1 := by exact_mod_cast χ₈_int_eq_if_mod_eight n /-- Define the second primitive quadratic character on `zmod 8`, `χ₈'`. It corresponds to the extension `ℚ(√-2)/ℚ`. -/ @[simps] def χ₈' : mul_char (zmod 8) ℤ := { to_fun := (![0,1,0,1,0,-1,0,-1] : (zmod 8 → ℤ)), map_one' := rfl, map_mul' := dec_trivial, map_nonunit' := dec_trivial } /-- `χ₈'` takes values in `{0, 1, -1}` -/ lemma is_quadratic_χ₈' : χ₈'.is_quadratic := by { intro a, dec_trivial!, } /-- An explicit description of `χ₈'` on integers / naturals -/ lemma χ₈'_int_eq_if_mod_eight (n : ℤ) : χ₈' n = if n % 2 = 0 then 0 else if n % 8 = 1 ∨ n % 8 = 3 then 1 else -1 := begin have help : ∀ (m : ℤ), 0 ≤ m → m < 8 → χ₈' m = if m % 2 = 0 then 0 else if m = 1 ∨ m = 3 then 1 else -1 := dec_trivial, rw [← int.mod_mod_of_dvd n (by norm_num : (2 : ℤ) ∣ 8), ← zmod.int_cast_mod n 8], exact help (n % 8) (int.mod_nonneg n (by norm_num)) (int.mod_lt n (by norm_num)), end lemma χ₈'_nat_eq_if_mod_eight (n : ℕ) : χ₈' n = if n % 2 = 0 then 0 else if n % 8 = 1 ∨ n % 8 = 3 then 1 else -1 := by exact_mod_cast χ₈'_int_eq_if_mod_eight n /-- The relation between `χ₄`, `χ₈` and `χ₈'` -/ lemma χ₈'_eq_χ₄_mul_χ₈ (a : zmod 8) : χ₈' a = χ₄ a * χ₈ a := by dec_trivial! lemma χ₈'_int_eq_χ₄_mul_χ₈ (a : ℤ) : χ₈' a = χ₄ a * χ₈ a := begin rw ← @cast_int_cast 8 (zmod 4) _ 4 _ (by norm_num) a, exact χ₈'_eq_χ₄_mul_χ₈ a, end end quad_char_mod_p end zmod
d955f342852358c4f10d8dc6bc26c65b9c6aa621
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/meta_ind_univ.lean
6c896a507922302c95da267ce549af89d15cdf6b
[ "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
200
lean
-- should fail inductive foo : Type → Type | mk : Π (α β : Type), (β → α) → foo α -- should be fine meta inductive foom : Type → Type | mk : Π (α β : Type), (β → α) → foom α
ddee0dadb6b3046dbd4e91829500a91ff106beab
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/stone_cech.lean
5d02803742259c2a966ae8055c90ceeb7af6163e
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
11,335
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.bases topology.dense_embedding /-! # Stone-Čech compactification Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ noncomputable theory open filter lattice set open_locale topological_space universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := {t | ∃ (s : set α), t = {u | s ∈ u.val}} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, u.val.inter_sets ua ub, assume v hv, ⟨_, _⟩⟩; apply v.val.sets_of_superset hv; simp end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq.symm (eq_univ_of_forall (λ u, u.val.univ_sets))⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u.val} := topological_space.is_open_of_is_topological_basis ultrafilter_basis_is_basis ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u.val} := begin change is_open (- _), convert ultrafilter_is_open_basic (-s), ext u, exact (ultrafilter_iff_compl_mem_iff_not_mem.mp u.property s).symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : u.val ≤ 𝓝 x ↔ x = mjoin u := begin rw [eq_comm, ultrafilter.eq_iff_val_le_val], change u.val ≤ 𝓝 x ↔ x.val.sets ⊆ {a | {v : ultrafilter α | a ∈ v.val} ∈ u.val}, simp only [topological_space.nhds_generate_from, lattice.le_infi_iff, ultrafilter_basis, le_principal_iff], split; intro h, { intros a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros _ ⟨xi, a, rfl⟩, exact h xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨compact_iff_ultrafilter_le_nhds.mpr $ assume f uf _, ⟨mjoin ⟨f, uf⟩, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume f x y u fx fy, have hx : x = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (𝓝 b) ≤ b.val := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine lattice.infi_le_of_le {u | s ∈ u.val} _, refine lattice.infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, exact principal_mono.2 (λ a, id) end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α).val := singleton_mem_pure_sets, rw h at this, exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm end open topological_space /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact dense_inducing.mk' pure continuous_bot (assume x, mem_closure_iff_ultrafilter.mpr ⟨x.map ultrafilter.pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩) (assume a s as, ⟨{u | s ∈ u.val}, mem_nhds_sets (ultrafilter_is_open_basic s) (mem_of_nhds as : a ∈ s), assume b hb, mem_pure_sets.mp hb⟩) -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, letI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq_of_cont continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap ultrafilter.pure (𝓝 b)) (𝓝 c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_iff_ultrafilter_le_nhds.mp compact_univ (b.map f).val (b.map f).property (by rw [le_principal_iff]; exact univ_mem_sets) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, letI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ b.val.map f ≤ 𝓝 c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : b'.val ≤ 𝓝 b, from ultrafilter_converges_iff.mpr (bind_pure _).symm, rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) b.val, rw ultrafilter_extend_extends, exact le_refl _ end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance instance [inhabited α] : inhabited (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma stone_cech_unit_dense : closure (range (@stone_cech_unit α _)) = univ := begin convert quotient_dense_of_dense (eq_univ_iff_forall.mp dense_inducing_pure.closure_range), rw [←range_comp], refl end section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : u.val ≤ 𝓝 x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g u gx, let g' : ultrafilter α := ⟨g, u⟩ in have (g'.map ultrafilter.pure).val ≤ 𝓝 g', by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g'.map stone_cech_unit).val ≤ 𝓝 ⟦g'⟧, from (continuous_at_iff_ultrafilter g').mp (continuous_quotient_mk.tendsto g') _ (ultrafilter_map u) this, by rwa (show ⟦g'⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros g ⟨x⟩ ⟨y⟩ u gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim : ∀ z : ultrafilter α, g ≤ 𝓝 ⟦z⟧ → tendsto ff g (𝓝 (ff ⟦z⟧)) := assume z gz, calc map ff g ≤ map ff (𝓝 ⟦z⟧) : map_mono gz ... ≤ 𝓝 (ff ⟦z⟧) : (continuous_stone_cech_extend hf).tendsto _, exact tendsto_nhds_unique u.1 (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
b3951c3e8c6cefcbf55894b793da3303d027b661
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/calculus/conformal/inner_product.lean
6daefbcfb7ebf8a66a459fc97d6b786671fe7a18
[ "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
2,521
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.calculus.conformal.normed_space import analysis.inner_product_space.conformal_linear_map /-! # Conformal maps between inner product spaces A function between inner product spaces is which has a derivative at `x` is conformal at `x` iff the derivative preserves inner products up to a scalar multiple. -/ noncomputable theory variables {E F : Type*} variables [normed_add_comm_group E] [normed_add_comm_group F] variables [inner_product_space ℝ E] [inner_product_space ℝ F] open_locale real_inner_product_space /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `fderiv ℝ f x` at that point scales every inner product by a positive scalar. -/ lemma conformal_at_iff' {f : E → F} {x : E} : conformal_at f x ↔ ∃ (c : ℝ), 0 < c ∧ ∀ (u v : E), ⟪fderiv ℝ f x u, fderiv ℝ f x v⟫ = c * ⟪u, v⟫ := by rw [conformal_at_iff_is_conformal_map_fderiv, is_conformal_map_iff] /-- A real differentiable map `f` is conformal at point `x` if and only if its differential `f'` at that point scales every inner product by a positive scalar. -/ lemma conformal_at_iff {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) : conformal_at f x ↔ ∃ (c : ℝ), 0 < c ∧ ∀ (u v : E), ⟪f' u, f' v⟫ = c * ⟪u, v⟫ := by simp only [conformal_at_iff', h.fderiv] /-- The conformal factor of a conformal map at some point `x`. Some authors refer to this function as the characteristic function of the conformal map. -/ def conformal_factor_at {f : E → F} {x : E} (h : conformal_at f x) : ℝ := classical.some (conformal_at_iff'.mp h) lemma conformal_factor_at_pos {f : E → F} {x : E} (h : conformal_at f x) : 0 < conformal_factor_at h := (classical.some_spec $ conformal_at_iff'.mp h).1 lemma conformal_factor_at_inner_eq_mul_inner' {f : E → F} {x : E} (h : conformal_at f x) (u v : E) : ⟪(fderiv ℝ f x) u, (fderiv ℝ f x) v⟫ = (conformal_factor_at h : ℝ) * ⟪u, v⟫ := (classical.some_spec $ conformal_at_iff'.mp h).2 u v lemma conformal_factor_at_inner_eq_mul_inner {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) : ⟪f' u, f' v⟫ = (conformal_factor_at H : ℝ) * ⟪u, v⟫ := (H.differentiable_at.has_fderiv_at.unique h) ▸ conformal_factor_at_inner_eq_mul_inner' H u v
9da4954fa92c34932edffbed603dc5b13cd90cf6
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/complex/re_im_topology.lean
4aebad8a16e83f169c12cec3c94f4f5dbf89ec42
[ "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,071
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.complex.basic import topology.fiber_bundle /-! # Closure, interior, and frontier of preimages under `re` and `im` In this fact we use the fact that `ℂ` is naturally homeomorphic to `ℝ × ℝ` to deduce some topological properties of `complex.re` and `complex.im`. ## Main statements Each statement about `complex.re` listed below has a counterpart about `complex.im`. * `complex.is_trivial_topological_fiber_bundle_re`: `complex.re` turns `ℂ` into a trivial topological fiber bundle over `ℝ`; * `complex.is_open_map_re`, `complex.quotient_map_re`: in particular, `complex.re` is an open map and is a quotient map; * `complex.interior_preimage_re`, `complex.closure_preimage_re`, `complex.frontier_preimage_re`: formulas for `interior (complex.re ⁻¹' s)` etc; * `complex.interior_set_of_re_le` etc: particular cases of the above formulas in the cases when `s` is one of the infinite intervals `set.Ioi a`, `set.Ici a`, `set.Iio a`, and `set.Iic a`, formulated as `interior {z : ℂ | z.re ≤ a} = {z | z.re < a}` etc. ## Tags complex, real part, imaginary part, closure, interior, frontier -/ open topological_fiber_bundle set noncomputable theory namespace complex /-- `complex.re` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/ lemma is_trivial_topological_fiber_bundle_re : is_trivial_topological_fiber_bundle ℝ re := ⟨equiv_real_prodₗ.to_homeomorph, λ z, rfl⟩ /-- `complex.im` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/ lemma is_trivial_topological_fiber_bundle_im : is_trivial_topological_fiber_bundle ℝ im := ⟨equiv_real_prodₗ.to_homeomorph.trans (homeomorph.prod_comm ℝ ℝ), λ z, rfl⟩ lemma is_topological_fiber_bundle_re : is_topological_fiber_bundle ℝ re := is_trivial_topological_fiber_bundle_re.is_topological_fiber_bundle lemma is_topological_fiber_bundle_im : is_topological_fiber_bundle ℝ im := is_trivial_topological_fiber_bundle_im.is_topological_fiber_bundle lemma is_open_map_re : is_open_map re := is_topological_fiber_bundle_re.is_open_map_proj lemma is_open_map_im : is_open_map im := is_topological_fiber_bundle_im.is_open_map_proj lemma quotient_map_re : quotient_map re := is_topological_fiber_bundle_re.quotient_map_proj lemma quotient_map_im : quotient_map im := is_topological_fiber_bundle_im.quotient_map_proj lemma interior_preimage_re (s : set ℝ) : interior (re ⁻¹' s) = re ⁻¹' (interior s) := (is_open_map_re.preimage_interior_eq_interior_preimage continuous_re _).symm lemma interior_preimage_im (s : set ℝ) : interior (im ⁻¹' s) = im ⁻¹' (interior s) := (is_open_map_im.preimage_interior_eq_interior_preimage continuous_im _).symm lemma closure_preimage_re (s : set ℝ) : closure (re ⁻¹' s) = re ⁻¹' (closure s) := (is_open_map_re.preimage_closure_eq_closure_preimage continuous_re _).symm lemma closure_preimage_im (s : set ℝ) : closure (im ⁻¹' s) = im ⁻¹' (closure s) := (is_open_map_im.preimage_closure_eq_closure_preimage continuous_im _).symm lemma frontier_preimage_re (s : set ℝ) : frontier (re ⁻¹' s) = re ⁻¹' (frontier s) := (is_open_map_re.preimage_frontier_eq_frontier_preimage continuous_re _).symm lemma frontier_preimage_im (s : set ℝ) : frontier (im ⁻¹' s) = im ⁻¹' (frontier s) := (is_open_map_im.preimage_frontier_eq_frontier_preimage continuous_im _).symm @[simp] lemma interior_set_of_re_le (a : ℝ) : interior {z : ℂ | z.re ≤ a} = {z | z.re < a} := by simpa only [interior_Iic] using interior_preimage_re (Iic a) @[simp] lemma interior_set_of_im_le (a : ℝ) : interior {z : ℂ | z.im ≤ a} = {z | z.im < a} := by simpa only [interior_Iic] using interior_preimage_im (Iic a) @[simp] lemma interior_set_of_le_re (a : ℝ) : interior {z : ℂ | a ≤ z.re} = {z | a < z.re} := by simpa only [interior_Ici] using interior_preimage_re (Ici a) @[simp] lemma interior_set_of_le_im (a : ℝ) : interior {z : ℂ | a ≤ z.im} = {z | a < z.im} := by simpa only [interior_Ici] using interior_preimage_im (Ici a) @[simp] lemma closure_set_of_re_lt (a : ℝ) : closure {z : ℂ | z.re < a} = {z | z.re ≤ a} := by simpa only [closure_Iio] using closure_preimage_re (Iio a) @[simp] lemma closure_set_of_im_lt (a : ℝ) : closure {z : ℂ | z.im < a} = {z | z.im ≤ a} := by simpa only [closure_Iio] using closure_preimage_im (Iio a) @[simp] lemma closure_set_of_lt_re (a : ℝ) : closure {z : ℂ | a < z.re} = {z | a ≤ z.re} := by simpa only [closure_Ioi] using closure_preimage_re (Ioi a) @[simp] lemma closure_set_of_lt_im (a : ℝ) : closure {z : ℂ | a < z.im} = {z | a ≤ z.im} := by simpa only [closure_Ioi] using closure_preimage_im (Ioi a) @[simp] lemma frontier_set_of_re_le (a : ℝ) : frontier {z : ℂ | z.re ≤ a} = {z | z.re = a} := by simpa only [frontier_Iic] using frontier_preimage_re (Iic a) @[simp] lemma frontier_set_of_im_le (a : ℝ) : frontier {z : ℂ | z.im ≤ a} = {z | z.im = a} := by simpa only [frontier_Iic] using frontier_preimage_im (Iic a) @[simp] lemma frontier_set_of_le_re (a : ℝ) : frontier {z : ℂ | a ≤ z.re} = {z | z.re = a} := by simpa only [frontier_Ici] using frontier_preimage_re (Ici a) @[simp] lemma frontier_set_of_le_im (a : ℝ) : frontier {z : ℂ | a ≤ z.im} = {z | z.im = a} := by simpa only [frontier_Ici] using frontier_preimage_im (Ici a) @[simp] lemma frontier_set_of_re_lt (a : ℝ) : frontier {z : ℂ | z.re < a} = {z | z.re = a} := by simpa only [frontier_Iio] using frontier_preimage_re (Iio a) @[simp] lemma frontier_set_of_im_lt (a : ℝ) : frontier {z : ℂ | z.im < a} = {z | z.im = a} := by simpa only [frontier_Iio] using frontier_preimage_im (Iio a) @[simp] lemma frontier_set_of_lt_re (a : ℝ) : frontier {z : ℂ | a < z.re} = {z | z.re = a} := by simpa only [frontier_Ioi] using frontier_preimage_re (Ioi a) @[simp] lemma frontier_set_of_lt_im (a : ℝ) : frontier {z : ℂ | a < z.im} = {z | z.im = a} := by simpa only [frontier_Ioi] using frontier_preimage_im (Ioi a) lemma closure_preimage_re_inter_preimage_im (s t : set ℝ) : closure (re ⁻¹' s ∩ im ⁻¹' t) = re ⁻¹' (closure s) ∩ im ⁻¹' (closure t) := by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective, equiv_real_prodₗ.symm.to_homeomorph.preimage_closure] using @closure_prod_eq _ _ _ _ s t lemma interior_preimage_re_inter_preimage_im (s t : set ℝ) : interior (re ⁻¹' s ∩ im ⁻¹' t) = re ⁻¹' (interior s) ∩ im ⁻¹' (interior t) := by rw [interior_inter, interior_preimage_re, interior_preimage_im] lemma frontier_preimage_re_inter_preimage_im (s t : set ℝ) : frontier (re ⁻¹' s ∩ im ⁻¹' t) = re ⁻¹' (closure s) ∩ im ⁻¹' (frontier t) ∪ re ⁻¹' (frontier s) ∩ im ⁻¹' (closure t) := by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective, equiv_real_prodₗ.symm.to_homeomorph.preimage_frontier] using frontier_prod_eq s t lemma frontier_set_of_le_re_and_le_im (a b : ℝ) : frontier {z | a ≤ re z ∧ b ≤ im z} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ b ≤ im z} := by simpa only [closure_Ici, frontier_Ici] using frontier_preimage_re_inter_preimage_im (Ici a) (Ici b) lemma frontier_set_of_le_re_and_im_le (a b : ℝ) : frontier {z | a ≤ re z ∧ im z ≤ b} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ im z ≤ b} := by simpa only [closure_Ici, closure_Iic, frontier_Ici, frontier_Iic] using frontier_preimage_re_inter_preimage_im (Ici a) (Iic b) end complex open complex lemma is_open.re_prod_im {s t : set ℝ} (hs : is_open s) (ht : is_open t) : is_open (re ⁻¹' s ∩ im ⁻¹' t) := (hs.preimage continuous_re).inter (ht.preimage continuous_im) lemma is_closed.re_prod_im {s t : set ℝ} (hs : is_closed s) (ht : is_closed t) : is_closed (re ⁻¹' s ∩ im ⁻¹' t) := (hs.preimage continuous_re).inter (ht.preimage continuous_im)
264f29535ab039c1e1dd827ea670d418e93d7640
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/module/weak_dual.lean
0b4822cf8b21c9880d5e95de0b64725ede477d08
[ "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
12,624
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä, Moritz Doll -/ import topology.algebra.module.basic import linear_algebra.bilinear_map /-! # Weak dual topology > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the weak topology given two vector spaces `E` and `F` over a commutative semiring `𝕜` and a bilinear form `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜`. The weak topology on `E` is the coarsest topology such that for all `y : F` every map `λ x, B x y` is continuous. In the case that `F = E →L[𝕜] 𝕜` and `B` being the canonical pairing, we obtain the weak-* topology, `weak_dual 𝕜 E := (E →L[𝕜] 𝕜)`. Interchanging the arguments in the bilinear form yields the weak topology `weak_space 𝕜 E := E`. ## Main definitions The main definitions are the types `weak_bilin B` for the general case and the two special cases `weak_dual 𝕜 E` and `weak_space 𝕜 E` with the respective topology instances on it. * Given `B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜`, the type `weak_bilin B` is a type synonym for `E`. * The instance `weak_bilin.topological_space` is the weak topology induced by the bilinear form `B`. * `weak_dual 𝕜 E` is a type synonym for `dual 𝕜 E` (when the latter is defined): both are equal to the type `E →L[𝕜] 𝕜` of continuous linear maps from a module `E` over `𝕜` to the ring `𝕜`. * The instance `weak_dual.topological_space` is the weak-* topology on `weak_dual 𝕜 E`, i.e., the coarsest topology making the evaluation maps at all `z : E` continuous. * `weak_space 𝕜 E` is a type synonym for `E` (when the latter is defined). * The instance `weak_dual.topological_space` is the weak topology on `E`, i.e., the coarsest topology such that all `v : dual 𝕜 E` remain continuous. ## Main results We establish that `weak_bilin B` has the following structure: * `weak_bilin.has_continuous_add`: The addition in `weak_bilin B` is continuous. * `weak_bilin.has_continuous_smul`: The scalar multiplication in `weak_bilin B` is continuous. We prove the following results characterizing the weak topology: * `eval_continuous`: For any `y : F`, the evaluation mapping `λ x, B x y` is continuous. * `continuous_of_continuous_eval`: For a mapping to `weak_bilin B` to be continuous, it suffices that its compositions with pairing with `B` at all points `y : F` is continuous. * `tendsto_iff_forall_eval_tendsto`: Convergence in `weak_bilin B` can be characterized in terms of convergence of the evaluations at all points `y : F`. ## Notations No new notation is introduced. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags weak-star, weak dual, duality -/ noncomputable theory open filter open_locale topology variables {α 𝕜 𝕝 R E F M : Type*} section weak_topology /-- The space `E` equipped with the weak topology induced by the bilinear form `B`. -/ @[derive [add_comm_monoid, module 𝕜], nolint has_nonempty_instance unused_arguments] def weak_bilin [comm_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] [add_comm_monoid F] [module 𝕜 F] (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) := E namespace weak_bilin instance [comm_semiring 𝕜] [a : add_comm_group E] [module 𝕜 E] [add_comm_monoid F] [module 𝕜 F] (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : add_comm_group (weak_bilin B) := a @[priority 100] instance module' [comm_semiring 𝕜] [comm_semiring 𝕝] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] [m : module 𝕝 E] (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : module 𝕝 (weak_bilin B) := m instance [comm_semiring 𝕜] [comm_semiring 𝕝] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] [has_smul 𝕝 𝕜] [module 𝕝 E] [s : is_scalar_tower 𝕝 𝕜 E] (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) : is_scalar_tower 𝕝 𝕜 (weak_bilin B) := s section semiring variables [topological_space 𝕜] [comm_semiring 𝕜] variables [add_comm_monoid E] [module 𝕜 E] variables [add_comm_monoid F] [module 𝕜 F] variables (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) instance : topological_space (weak_bilin B) := topological_space.induced (λ x y, B x y) Pi.topological_space /-- The coercion `(λ x y, B x y) : E → (F → 𝕜)` is continuous. -/ lemma coe_fn_continuous : continuous (λ (x : weak_bilin B) y, B x y) := continuous_induced_dom lemma eval_continuous (y : F) : continuous (λ x : weak_bilin B, B x y) := ( continuous_pi_iff.mp (coe_fn_continuous B)) y lemma continuous_of_continuous_eval [topological_space α] {g : α → weak_bilin B} (h : ∀ y, continuous (λ a, B (g a) y)) : continuous g := continuous_induced_rng.2 (continuous_pi_iff.mpr h) /-- The coercion `(λ x y, B x y) : E → (F → 𝕜)` is an embedding. -/ lemma embedding {B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜} (hB : function.injective B) : embedding (λ (x : weak_bilin B) y, B x y) := function.injective.embedding_induced $ linear_map.coe_injective.comp hB theorem tendsto_iff_forall_eval_tendsto {l : filter α} {f : α → (weak_bilin B)} {x : weak_bilin B} (hB : function.injective B) : tendsto f l (𝓝 x) ↔ ∀ y, tendsto (λ i, B (f i) y) l (𝓝 (B x y)) := by rw [← tendsto_pi_nhds, embedding.tendsto_nhds_iff (embedding hB)] /-- Addition in `weak_space B` is continuous. -/ instance [has_continuous_add 𝕜] : has_continuous_add (weak_bilin B) := begin refine ⟨continuous_induced_rng.2 _⟩, refine cast (congr_arg _ _) (((coe_fn_continuous B).comp continuous_fst).add ((coe_fn_continuous B).comp continuous_snd)), ext, simp only [function.comp_app, pi.add_apply, map_add, linear_map.add_apply], end /-- Scalar multiplication by `𝕜` on `weak_bilin B` is continuous. -/ instance [has_continuous_smul 𝕜 𝕜] : has_continuous_smul 𝕜 (weak_bilin B) := begin refine ⟨continuous_induced_rng.2 _⟩, refine cast (congr_arg _ _) (continuous_fst.smul ((coe_fn_continuous B).comp continuous_snd)), ext, simp only [function.comp_app, pi.smul_apply, linear_map.map_smulₛₗ, ring_hom.id_apply, linear_map.smul_apply], end end semiring section ring variables [topological_space 𝕜] [comm_ring 𝕜] variables [add_comm_group E] [module 𝕜 E] variables [add_comm_group F] [module 𝕜 F] variables (B : E →ₗ[𝕜] F →ₗ[𝕜] 𝕜) /-- `weak_space B` is a `topological_add_group`, meaning that addition and negation are continuous. -/ instance [has_continuous_add 𝕜] : topological_add_group (weak_bilin B) := { to_has_continuous_add := by apply_instance, continuous_neg := begin refine continuous_induced_rng.2 (continuous_pi_iff.mpr (λ y, _)), refine cast (congr_arg _ _) (eval_continuous B (-y)), ext, simp only [map_neg, function.comp_app, linear_map.neg_apply], end } end ring end weak_bilin end weak_topology section weak_star_topology /-- The canonical pairing of a vector space and its topological dual. -/ def top_dual_pairing (𝕜 E) [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜] [add_comm_monoid E] [module 𝕜 E] [topological_space E] [has_continuous_const_smul 𝕜 𝕜] : (E →L[𝕜] 𝕜) →ₗ[𝕜] E →ₗ[𝕜] 𝕜 := continuous_linear_map.coe_lm 𝕜 variables [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜] variables [has_continuous_const_smul 𝕜 𝕜] variables [add_comm_monoid E] [module 𝕜 E] [topological_space E] lemma dual_pairing_apply (v : (E →L[𝕜] 𝕜)) (x : E) : top_dual_pairing 𝕜 E v x = v x := rfl /-- The weak star topology is the topology coarsest topology on `E →L[𝕜] 𝕜` such that all functionals `λ v, top_dual_pairing 𝕜 E v x` are continuous. -/ @[derive [add_comm_monoid, module 𝕜, topological_space, has_continuous_add]] def weak_dual (𝕜 E) [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜] [has_continuous_const_smul 𝕜 𝕜] [add_comm_monoid E] [module 𝕜 E] [topological_space E] := weak_bilin (top_dual_pairing 𝕜 E) namespace weak_dual instance : inhabited (weak_dual 𝕜 E) := continuous_linear_map.inhabited instance weak_dual.continuous_linear_map_class : continuous_linear_map_class (weak_dual 𝕜 E) 𝕜 E 𝕜 := continuous_linear_map.continuous_semilinear_map_class /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (weak_dual 𝕜 E) (λ _, E → 𝕜) := fun_like.has_coe_to_fun /-- If a monoid `M` distributively continuously acts on `𝕜` and this action commutes with multiplication on `𝕜`, then it acts on `weak_dual 𝕜 E`. -/ instance (M) [monoid M] [distrib_mul_action M 𝕜] [smul_comm_class 𝕜 M 𝕜] [has_continuous_const_smul M 𝕜] : mul_action M (weak_dual 𝕜 E) := continuous_linear_map.mul_action /-- If a monoid `M` distributively continuously acts on `𝕜` and this action commutes with multiplication on `𝕜`, then it acts distributively on `weak_dual 𝕜 E`. -/ instance (M) [monoid M] [distrib_mul_action M 𝕜] [smul_comm_class 𝕜 M 𝕜] [has_continuous_const_smul M 𝕜] : distrib_mul_action M (weak_dual 𝕜 E) := continuous_linear_map.distrib_mul_action /-- If `𝕜` is a topological module over a semiring `R` and scalar multiplication commutes with the multiplication on `𝕜`, then `weak_dual 𝕜 E` is a module over `R`. -/ instance module' (R) [semiring R] [module R 𝕜] [smul_comm_class 𝕜 R 𝕜] [has_continuous_const_smul R 𝕜] : module R (weak_dual 𝕜 E) := continuous_linear_map.module instance (M) [monoid M] [distrib_mul_action M 𝕜] [smul_comm_class 𝕜 M 𝕜] [has_continuous_const_smul M 𝕜] : has_continuous_const_smul M (weak_dual 𝕜 E) := ⟨λ m, continuous_induced_rng.2 $ (weak_bilin.coe_fn_continuous (top_dual_pairing 𝕜 E)).const_smul m⟩ /-- If a monoid `M` distributively continuously acts on `𝕜` and this action commutes with multiplication on `𝕜`, then it continuously acts on `weak_dual 𝕜 E`. -/ instance (M) [monoid M] [distrib_mul_action M 𝕜] [smul_comm_class 𝕜 M 𝕜] [topological_space M] [has_continuous_smul M 𝕜] : has_continuous_smul M (weak_dual 𝕜 E) := ⟨continuous_induced_rng.2 $ continuous_fst.smul ((weak_bilin.coe_fn_continuous (top_dual_pairing 𝕜 E)).comp continuous_snd)⟩ lemma coe_fn_continuous : continuous (λ (x : weak_dual 𝕜 E) y, x y) := continuous_induced_dom lemma eval_continuous (y : E) : continuous (λ x : weak_dual 𝕜 E, x y) := continuous_pi_iff.mp coe_fn_continuous y lemma continuous_of_continuous_eval [topological_space α] {g : α → weak_dual 𝕜 E} (h : ∀ y, continuous (λ a, (g a) y)) : continuous g := continuous_induced_rng.2 (continuous_pi_iff.mpr h) instance [t2_space 𝕜] : t2_space (weak_dual 𝕜 E) := embedding.t2_space $ weak_bilin.embedding $ show function.injective (top_dual_pairing 𝕜 E), from continuous_linear_map.coe_injective end weak_dual /-- The weak topology is the topology coarsest topology on `E` such that all functionals `λ x, top_dual_pairing 𝕜 E v x` are continuous. -/ @[derive [add_comm_monoid, module 𝕜, topological_space, has_continuous_add], nolint has_nonempty_instance] def weak_space (𝕜 E) [comm_semiring 𝕜] [topological_space 𝕜] [has_continuous_add 𝕜] [has_continuous_const_smul 𝕜 𝕜] [add_comm_monoid E] [module 𝕜 E] [topological_space E] := weak_bilin (top_dual_pairing 𝕜 E).flip namespace weak_space variables {𝕜 E F} [add_comm_monoid F] [module 𝕜 F] [topological_space F] /-- A continuous linear map from `E` to `F` is still continuous when `E` and `F` are equipped with their weak topologies. -/ def map (f : E →L[𝕜] F) : weak_space 𝕜 E →L[𝕜] weak_space 𝕜 F := { cont := weak_bilin.continuous_of_continuous_eval _ (λ l, weak_bilin.eval_continuous _ (l ∘L f)), ..f } lemma map_apply (f : E →L[𝕜] F) (x : E) : weak_space.map f x = f x := rfl @[simp] lemma coe_map (f : E →L[𝕜] F) : (weak_space.map f : E → F) = f := rfl end weak_space theorem tendsto_iff_forall_eval_tendsto_top_dual_pairing {l : filter α} {f : α → weak_dual 𝕜 E} {x : weak_dual 𝕜 E} : tendsto f l (𝓝 x) ↔ ∀ y, tendsto (λ i, top_dual_pairing 𝕜 E (f i) y) l (𝓝 (top_dual_pairing 𝕜 E x y)) := weak_bilin.tendsto_iff_forall_eval_tendsto _ continuous_linear_map.coe_injective end weak_star_topology
db1ab3ad283a906c3a7569ccadd726eae1f0d545
ca1ad81c8733787aba30f7a8d63f418508e12812
/clfrags/src/hilbert/wr/and_or.lean
21d82e33b382819c93647e62590f8a1535285b7d
[]
no_license
greati/hilbert-classical-fragments
5cdbe07851e979c8a03c621a5efd4d24bbfa333a
18a21ac6b2e890060eb4ae65752fc0245394d226
refs/heads/master
1,591,973,117,184
1,573,822,710,000
1,573,822,710,000
194,334,439
2
0
null
null
null
null
UTF-8
Lean
false
false
440
lean
import core.connectives import hilbert.wr.or namespace clfrags namespace hilbert namespace wr namespace and_or axiom cd₁ : Π {a b c : Prop}, or c a → or c b → or c (and a b) axiom cd₂ : Π {a b c : Prop}, or c (and a b) → or c a axiom cd₃ : Π {a b c : Prop}, or c (and a b) → or c b end and_or end wr end hilbert end clfrags
201c5303dc730fda8ce54f85938b6b9b31f2353e
8c02fed42525b65813b55c064afe2484758d6d09
/src/smtexpr.lean
05abfeda77bf893ecd38e707a81a81adcfcc2056
[ "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
6,378
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import .common import .ops import .bitvector import smt2.syntax import smt2.builder universes u -- sbool: Boolean SMT formula -- sbitvec: Bit-vector SMT formula (takes its bitwidth) mutual inductive sbool, sbitvec with sbool : Type | tt: sbool | ff:sbool | var: string → sbool -- SMT variable | and: sbool → sbool → sbool | or: sbool → sbool → sbool | xor: sbool → sbool → sbool | eqb: sbool → sbool → sbool | neb: sbool → sbool → sbool | ite: sbool → sbool → sbool → sbool | not: sbool → sbool | eqbv: Π {sz:size}, sbitvec sz → sbitvec sz → sbool | nebv: Π {sz:size}, sbitvec sz → sbitvec sz → sbool | sle: Π {sz:size}, sbitvec sz → sbitvec sz → sbool | slt: Π {sz:size}, sbitvec sz → sbitvec sz → sbool | ule: Π {sz:size}, sbitvec sz → sbitvec sz → sbool | ult: Π {sz:size}, sbitvec sz → sbitvec sz → sbool with sbitvec : size → Type | const: Π (sz:size) (n:nat), sbitvec sz | var: Π (sz:size), string → sbitvec sz -- SMT variable | add: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | sub: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | mul: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | udiv: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | urem: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | sdiv: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | srem: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | and: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | or: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | xor: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | shl: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | lshr: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | ashr: Π {sz:size}, sbitvec sz → sbitvec sz → sbitvec sz | zext: Π {sz:size} (sz':size), sbitvec sz → sbitvec sz' | sext: Π {sz:size} (sz':size), sbitvec sz → sbitvec sz' | trunc: Π {sz:size} (sz':size), sbitvec sz → sbitvec sz' | extract: Π {sz sz':size} (highbit lowbit:nat) (H:sz'.val = highbit - lowbit + 1), sbitvec sz → sbitvec sz' | ite: Π {sz:size}, sbool → sbitvec sz → sbitvec sz → sbitvec sz namespace sbool open smt2.term open smt2.builder def of_bool (b:bool):sbool := cond b sbool.tt sbool.ff def and_simpl (t1 t2:sbool):sbool := match t1 with | sbool.tt := t2 | sbool.ff := sbool.ff | _ := match t2 with | sbool.tt := t1 | sbool.ff := sbool.ff | _ := sbool.and t1 t2 end end end sbool instance sbool_is_bool_like : bool_like sbool := ⟨sbool.tt, sbool.ff, sbool.and, sbool.or, sbool.xor, sbool.not⟩ instance sbool_has_ite : has_ite sbool sbool := ⟨sbool.ite⟩ namespace sbitvec open smt2.term open smt2.builder def of_int (sz:size) : ℤ → sbitvec sz | x@(int.of_nat q) := sbitvec.const sz (q % (2^sz.val)) | x@(int.neg_succ_of_nat p) := sbitvec.const sz (((2 ^ sz.val) - p - 1) % (2^sz.val)) @[simp] def one (sz:size) : sbitvec sz := of_int sz 1 @[simp] def zero (sz:size) : sbitvec sz := of_int sz 0 @[simp] def intmin (sz:size) : sbitvec sz := of_int sz (int_min_nat sz) @[simp] def intmax (sz:size) : sbitvec sz := of_int sz (int.of_nat ((2^(sz.val-1))-1)) @[simp] def uintmax (sz:size) : sbitvec sz := of_int sz (all_one_nat sz) def of_bool (b:sbool) : sbitvec (size.one) := sbitvec.ite b (sbitvec.one size.one) (sbitvec.zero size.one) def of_bv {sz:size} (b:bitvector sz) : sbitvec sz := of_int sz b.1 private theorem add_size_eq (n m:size): subtype.mk ((n.1 + m.1 - 1) - n.1 + 1) dec_trivial = m := begin apply subtype.eq, simp, rewrite nat.add_sub_assoc, { -- 1 + (n.val + (m.val - 1) - n.val) = m.val rewrite nat.add_sub_cancel_left, -- 1 + (m.val - 1) = m.val rewrite ← nat.add_sub_assoc, -- 1 + m.val - 1 = m.val rewrite nat.add_sub_cancel_left, -- 1 ≤ m.val apply m.2 }, { -- 1 ≤ m.val apply m.2 } end theorem decr_sbitvec: ∀ (sz:size) (v:sbitvec sz), 0 < sbitvec.sizeof sz v := begin intros, induction v, any_goals { unfold sbitvec.sizeof }, any_goals { try {simp}, rw nat.one_add, exact dec_trivial } end variable {sz:size} @[simp] def mk_zext (m:size) (a:sbitvec sz): sbitvec (sz.add m) := sbitvec.zext (sz.add m) a @[simp] def mk_sext (m:size) (a:sbitvec sz): sbitvec (sz.add m) := sbitvec.sext (sz.add m) a -- Returns false if it overflows. def overflow_chk (f:Π {sz':size}, sbitvec sz' → sbitvec sz' → sbitvec sz') (m:size) (signed:bool) (a b:sbitvec sz):sbool := if signed then let a' := sbitvec.mk_sext m a, b' := sbitvec.mk_sext m b, r' := f a' b', r := f a b, r'' := sbitvec.mk_sext m r in sbool.nebv r' r'' else let a' := sbitvec.mk_zext m a, b' := sbitvec.mk_zext m b, r' := f a' b' in let H:(m.val = (sz.val + m.val - 1) - sz.val + 1) := begin rw nat.add_comm sz.val m.val, rw nat.sub.right_comm, rw nat.add_sub_cancel, rw nat.sub_add_cancel, cases m, assumption end in let padding := sbitvec.extract (sz+m-1) sz H r' in sbool.nebv padding (sbitvec.zero m) def shl_overflow_chk (m:size) (signed:bool) (a b:sbitvec sz):sbool := overflow_chk (@sbitvec.shl) sz signed a (sbitvec.urem b (sbitvec.of_int sz sz.val)) end sbitvec instance sbitvec_is_uint_like : uint_like (sbitvec) := ⟨@sbitvec.add, @sbitvec.sub, @sbitvec.mul, @sbitvec.udiv, @sbitvec.urem, @sbitvec.sdiv, @sbitvec.srem, @sbitvec.and, @sbitvec.or, @sbitvec.xor, @sbitvec.shl, @sbitvec.lshr, @sbitvec.ashr, sbitvec.zero, sbitvec.uintmax, sbitvec.intmin, sbitvec.of_int, @sbitvec.zext, @sbitvec.sext, @sbitvec.trunc⟩ instance sbool_sbitvec_has_coe: has_coe sbool (sbitvec size.one) := ⟨sbitvec.of_bool⟩ @[reducible] instance sbitvec_has_comp : has_comp sbitvec sbool := ⟨@sbool.eqbv, @sbool.nebv, @sbool.sle, @sbool.slt, @sbool.ule, @sbool.ult⟩ instance sbitvec_has_ite {sz:size} : has_ite sbool (sbitvec sz) := ⟨sbitvec.ite⟩ instance sbitvec_has_overflow_check : has_overflow_check sbitvec sbool := ⟨(λ {sz:size}, @sbitvec.overflow_chk sz @sbitvec.add size.one), (λ {sz:size}, @sbitvec.overflow_chk sz @sbitvec.sub size.one), (λ {sz:size}, @sbitvec.overflow_chk sz @sbitvec.mul sz), (λ {sz:size}, @sbitvec.shl_overflow_chk sz sz)⟩
476fcd81883ee74a132dcd1255b7288f9d89484f
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/data/set/basic.lean
2d2d067c912240b1a96e3776524473d8a37596d0
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
39,772
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.ext tactic.finish data.subtype tactic.interactive open function namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, set.ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl /- set coercion to a type -/ instance : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ @[simp] theorem set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := begin split, { rintro ⟨a⟩ H2, show a ∈ (∅ : set α), by rw ←H2 ; trivial }, { intro H, cases exists_mem_of_ne_empty H with a _, exact ⟨a⟩ } end /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := set.ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := set.ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := set.ext $ by simp theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := set.ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := set.ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := set.ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := set.ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self] /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, set.ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := set.ext $ λ x, by simp [image]; rw eq_comm lemma inter_singleton_ne_empty {α : Type*} {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma subtype_val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := set.ext $ by simp [image, range] theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma nonempty_of_nonempty_range {α : Type*} {β : Type*} {f : α → β} (H : ¬range f = ∅) : nonempty α := begin cases exists_mem_of_ne_empty H with x h, cases mem_range.1 h with y _, exact ⟨y⟩ end theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' preimage f t = t ∩ range f := set.ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ preimage f t, by simp [preimage, h_eq, hx]⟩ @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep end range lemma subtype_val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype_val_image] /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y end set namespace set section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := set.ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := set.ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := set.ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := set.ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := set.ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := set.ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := set.ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := set.ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := set.ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] end prod end set
7036d916ee2e79ab8d29f6dccf55c9be362d0bae
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/t5.lean
d12e5f4d7ba56a1b66b8cfe165e32a83da1d5019
[ "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
307
lean
variable N : Type.{1} namespace foo variable N : Type.{2} namespace tst variable N : Type.{3} print raw N end end print raw N namespace foo print raw N namespace tst print raw N N -> N section variable N : Type.{4} -- Shadow previous ones. print raw N end end end
c8a6ef5cec74cdd2100f5fc3b47748edc0975d84
abd85493667895c57a7507870867b28124b3998f
/src/field_theory/mv_polynomial.lean
6339970a25b1c671dfb7c92e326f16dfd525830d
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
9,223
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in `n` variables. -/ import linear_algebra.finsupp_vector_space import field_theory.finite noncomputable theory open_locale classical open set linear_map submodule open_locale big_operators namespace mv_polynomial universes u v variables {σ : Type u} {α : Type v} instance [field α] : vector_space α (mv_polynomial σ α) := finsupp.vector_space _ _ section variables (σ α) [field α] (m : ℕ) def restrict_total_degree : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m } lemma mem_restrict_total_degree (p : mv_polynomial σ α) : p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end end section variables (σ α) def restrict_degree (m : ℕ) [field α] : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | ∀i, n i ≤ m } end lemma mem_restrict_degree [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_supported], refl end lemma mem_restrict_degree_iff_sup [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end lemma map_range_eq_map {β : Type*} [comm_ring α] [comm_ring β] (p : mv_polynomial σ α) (f : α → β) [is_semiring_hom f]: finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f := begin rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum, ← p.support.sum_hom (map f)], { refine finset.sum_congr rfl (assume n _, _), rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] }, apply_instance end section variables (σ α) lemma is_basis_monomials [field α] : is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) := suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)), begin apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩), split, { intros x y hxy, simpa using hxy }, { intros x, rcases x with ⟨x₁, x₂⟩, use x₁, rw punit_eq punit.star x₂ } end, begin apply finsupp.is_basis_single (λ _ _, (1 : α)), intro _, apply is_basis_singleton_one, end end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [field α] open_locale classical lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) := by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim] end mv_polynomial namespace mv_polynomial variables {α : Type*} {σ : Type*} variables [field α] [fintype α] [fintype σ] def indicator (a : σ → α) : mv_polynomial σ α := ∏ n, (1 - (X n - C (a n))^(fintype.card α - 1)) lemma eval_indicator_apply_eq_one (a : σ → α) : eval a (indicator a) = 1 := have 0 < fintype.card α - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.univ.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → α) : degrees (indicator c) ≤ finset.univ.sum (λs:σ, (fintype.card α - 1) •ℕ {s}) := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X _ end lemma indicator_mem_restrict_degree (c : σ → α) : indicator c ∈ restrict_degree σ α (fintype.card α - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.univ.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (α σ) def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α := ⟨ λp e, p.eval e, assume p q, funext $ assume e, eval_add, assume a p, funext $ assume e, by rw [smul_eq_C_mul, eval_mul, eval_C]; refl ⟩ end section lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = p.eval e := rfl end lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ := begin refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _), refine ⟨finset.univ.sum (λn:σ → α, e n • indicator n), _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @pi.finset_sum_apply (σ → α) (λ_, α) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [fintype σ] [field α] [fintype α] @[derive [add_comm_group, vector_space α, inhabited]] def R : Type u := restrict_degree σ α (fintype.card α - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) := calc vector_space.dim α (R σ α) = vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } : begin refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card α}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩ ... = cardinal.mk (σ → fin (fintype.card α)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → α) : begin refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _), refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩ end ... = fintype.card (σ → α) : cardinal.fintype_card _ def evalᵢ : R σ α →ₗ[α] (σ → α) → α := ((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ := begin refine injective_of_surjective _ _ _ (range_evalᵢ _ _), { rw [dim_R], exact cardinal.nat_lt_omega _ }, { rw [dim_R, dim_fun, dim_of_field, mul_one] } end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α) (h : ∀v:σ → α, p.eval v = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) : p = 0 := let p' : R σ α := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ α).ker := by rw [mem_ker]; ext v; exact h v, show p'.1 = (0 : R σ α).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
bf79360f892ca21e09695ea258aca0ab3f3cf88e
766b82465c89f7c306a9c07004605f5d564fd7f7
/src/game/sums/level01.lean
6e4eda60d42668706d6e15a35353c1f8eb1c5404
[ "Apache-2.0" ]
permissive
stanescuUW/integer-number-game
ca4293a46c51db178f3bdb248118075caf87f582
fced68b04a59ef0f4ea41b5beb2df87e0428c761
refs/heads/master
1,669,860,820,240
1,597,966,427,000
1,597,966,427,000
289,131,361
1
0
null
null
null
null
UTF-8
Lean
false
false
548
lean
import tactic import data.rat import data.real.basic import data.real.irrational import game.basic.level02 namespace uwyo -- hide open real -- hide /- # Chapter 2 : Sums ## Level 1 -/ /- Lemma There are irrational numbers that sum up to a rational. -/ theorem irrat_sum : ¬ (∀ (x y : ℝ), irrational x → irrational y → irrational (x+y)) := begin intro H, have H2 := H (sqrt 2) (-sqrt 2), have H3 := H2 irrational_sqrt_two (irrational.neg irrational_sqrt_two), apply H3, existsi (0 : ℚ), simp, done end end uwyo -- hide
5e7f2e0848ba8e722d5bb6d1d623816fdb1891c5
592f865bb4e2e537ae3552cb83c32fb99c8d4c68
/src/to_qShannon_theory_maybe/channel.lean
08bd8123292e30bfa022980a46574234c7b261e4
[]
no_license
BassemSafieldeen/Entropy_and_reversible_catalysis
250dbb9446690ab89d89a6a512c8f888e09e8596
5dd6ee062f61e26bbcf254477e3e24aa3fc489af
refs/heads/master
1,678,747,213,156
1,615,540,586,000
1,615,540,586,000
322,216,014
0
0
null
null
null
null
UTF-8
Lean
false
false
1,659
lean
import to_mathlib_maybe.Hilbert_space import to_qShannon_theory_maybe.state variables {ℋ : Type} [complex_hilbert_space ℋ] {ℋ₁ : Type} [complex_hilbert_space ℋ₁] {ℋ₂ : Type} [complex_hilbert_space ℋ₂] {U : module.End ℂ ℋ} [unitary U] {ρ : module.End ℂ ℋ} [quantum_state ρ] /-- A quantum channel is a linear map between linear operators that satisifies certain axioms. -/ class quantum_channel (𝒩 : (module.End ℂ ℋ₁) →ₗ[ℂ] (module.End ℂ ℋ₂)) := (quantum_channel_ness : 1=1) variables {𝒩 : (module.End ℂ ℋ₁) →ₗ[ℂ] (module.End ℂ ℋ₂)} [quantum_channel 𝒩] {σ σ' : (ℋ₁ →ₗ[ℂ] ℋ₁)} [quantum_state σ] [quantum_state σ'] example : 𝒩(σ + σ') = 𝒩(σ) + 𝒩(σ') := begin rw linear_map.map_add, end -- d×d matrix with 1 at (i j) and 0 otherwise def E (i j d : ℕ) : module.End ℂ ℋ := sorry -- cyclic shift operators def shift (k n : ℕ) := ∑ i ∈ finset.range n, (E i (i+k)%n n) -- shift by 1 on S1, ..., Sn def cycle_s (d n : ℕ) := (Id d) ⊗ (shift 1 n) ⊗ (Id n) -- shift by one on A def cycle_ancilla (d n : ℕ) := 1^⊗n ⊗ (shift 1 n) -- Dephasing channel sending χ to its diagonal in the eigenbasis of ρ' def dephasing_channel (ρ') := λ ρ, ∑ v ∈ eigenvectors ρ', inner v (ρ v) -- Unitary and ancilla on Naimark's dilated system corresponding to an arbitrary quantum channel def naimark_unitary (C : module.End ℂ ℋ →ₗ[ℂ] module.End ℂ ℋ) [quantum_channel C] : module.End ℂ ℋ := sorry def naimark_ancilla (C : module.End ℂ ℋ →ₗ[ℂ] module.End ℂ ℋ) [quantum_channel C] : module.End ℂ ℋ := sorry
4d2f7f0a1af5a6c25a76473d4ed79ccae2ca356a
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
a1ca6102d47dbcb185da059d5e88bf4762d8bfc8
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,345
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do /- We have disabled `Term.withoutErrToSorry` to improve error recovery. When we were using it, any tactic using `elabTerm` would be interrupted at elaboration errors. Tactics that do not want to proceed should check whether the result contains sythetic sorrys or disable `errToSorry` before invoking `elabTerm` -/ withRef stx do -- <| Term.withoutErrToSorry do let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here. match expectedType? with | none => return e | some expectedType => let eType ← inferType e -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really -- part of the elaboration, but part of the tactic. See issue #492 unless (← withAssignableSyntheticOpaque do isDefEq eType expectedType) do Term.throwTypeMismatchError none expectedType eType e return e /- Try to close main goal using `x target`, where `target` is the type of the main goal. -/ def closeMainGoalUsing (x : Expr → TacticM Expr) (checkUnassigned := true) : TacticM Unit := withMainContext do closeMainGoal (checkUnassigned := checkUnassigned) (← x (← getMainTarget)) def logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do if (← Term.logUnassignedUsingErrorInfos mvarIds) then throwAbortTactic def filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do let mctx ← getMCtx return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match stx with | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do let mvarCounterSaved := (← getMCtx).mvarCounter let r ← elabTermEnsuringType e type logUnassignedAndAbort (← filterOldMVars (← getMVars r) mvarCounterSaved) return r | _ => throwUnsupportedSyntax def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let mvarCounterSaved := (← getMCtx).mvarCounter let val ← elabTermEnsuringType stx expectedType? let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← getMVarDecl mvarId).kind.isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← getMVarDecl mvarId).kind.isNatural let naturalMVarIds ← filterOldMVars naturalMVarIds mvarCounterSaved logUnassignedAndAbort naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds pure (val, newMVarIds) /- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do withMainContext do let (val, mvarIds') ← elabTermWithHoles stx (← getMainTarget) tagSuffix allowNaturalHoles assignExprMVar (← getMainGoal) val replaceMainGoal mvarIds' @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine'»] def evalRefine' : Tactic := fun stx => match stx with | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true) | _ => throwUnsupportedSyntax /-- Given a tactic ``` apply f ``` we want the `apply` tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. A similar method is also used in Lean 3. This method is useful when applying lemmas such as: ``` theorem infLeRight {s t : Set α} : s ⊓ t ≤ t ``` where `s ≤ t` here is defined as ``` ∀ {x : α}, x ∈ s → x ∈ t ``` -/ def elabTermForApply (stx : Syntax) : TacticM Expr := do if stx.isIdent then match (← Term.resolveId? stx (withInfo := true)) with | some e => return e | _ => pure () elabTerm stx none (mayPostpone := true) def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do withMainContext do let val ← elabTermForApply e let mvarIds' ← tac (← getMainGoal) val Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match stx with | `(tactic| apply $e) => evalApplyLikeTactic Meta.apply e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun stx => withMainContext do let mvarIds' ← Meta.constructor (← getMainGoal) Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.existsIntro] def evalExistsIntro : Tactic := fun stx => match stx with | `(tactic| exists $e) => evalApplyLikeTactic (fun mvarId e => return [(← Meta.existsIntro mvarId e)]) e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx => withReducible <| evalTactic stx[1] @[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx => withReducibleAndInstances <| evalTactic stx[1] /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := withMainContext do let e ← elabTerm stx none match e with | Expr.fvar fvarId _ => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let mvarId ← getMainGoal let (fvarId, mvarId) ← liftMetaM do let mvarId ← Meta.assert mvarId userName type e Meta.intro1Core mvarId preserveBinderNames replaceMainGoal [mvarId] return fvarId match userName? with | none => intro `h false | some userName => intro userName true @[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx => match stx with | `(tactic| rename $typeStx:term => $h:ident) => do withMainContext do /- Remark: we must not use `withoutModifyingState` because we may miss errors message. For example, suppose the following `elabTerm` logs an error during elaboration. In this scenario, the term `type` contains a synthetic `sorry`, and the error message `"failed to find ..."` is not logged by the outer loop. By using `withoutModifyingStateWithInfoAndMessages`, we ensure that the messages and the info trees are preserved while the rest of the state is backtracked. -/ let fvarId ← withoutModifyingStateWithInfoAndMessages <| withNewMCtxDepth do let type ← elabTerm typeStx none (mayPostpone := true) let fvarId? ← (← getLCtx).findDeclRevM? fun localDecl => do if (← isDefEq type localDecl.type) then return localDecl.fvarId else return none match fvarId? with | none => throwError "failed to find a hypothesis with type{indentExpr type}" | some fvarId => return fvarId let lctxNew := (← getLCtx).setUserName fvarId h.getId let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) (← getMainTarget) MetavarKind.syntheticOpaque (← getMainTag) assignExprMVar (← getMainGoal) mvarNew replaceMainGoal [mvarNew.mvarId!] | _ => throwUnsupportedSyntax /-- Make sure `expectedType` does not contain free and metavariables. It applies zeta-reduction to eliminate let-free-vars. -/ private def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError "expected type must not contain free or meta variables{indentExpr expectedType}" return expectedType @[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let d ← instantiateMVars d let r ← withDefault <| whnf d unless r.isConstOf ``true do throwError "failed to reduce to 'true'{indentExpr r}" let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf private def mkNativeAuxDecl (baseName : Name) (type val : Expr) : TermElabM Name := do let auxName ← Term.mkAuxName baseName let decl := Declaration.defnDecl { name := auxName, levelParams := [], type := type, value := val, hints := ReducibilityHints.abbrev, safety := DefinitionSafety.safe } addDecl decl compileDecl decl pure auxName @[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun stx => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let auxDeclName ← mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let s := d.appArg! -- get instance from `d` return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf end Lean.Elab.Tactic